函数为假定不同的输入返回相同的值

2024-04-20 00:04:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我用pyalgotrade来创建一个交易策略。我将浏览一个tickers列表(testlist),并将它们添加到一个字典(list{})中,与它们的分数一起使用get{u score函数得到分数。我的最新问题是字典(list{})中的每个ticker都得到相同的分数。知道为什么吗?你知道吗

代码:

from pyalgotrade import strategy
from pyalgotrade.tools import yahoofinance
import numpy as np
import pandas as pd
from collections import OrderedDict

from pyalgotrade.technical import ma
from talib import MA_Type
import talib

smaPeriod = 10
testlist = ['aapl','ddd','gg','z']

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        super(MyStrategy, self).__init__(feed, 1000)
        self.__position = [] 
        self.__instrument = instrument
        self.setUseAdjustedValues(True)
        self.__prices = feed[instrument].getPriceDataSeries()
        self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)

    def get_score(self,slope):
        MA_Score = self.__sma[-1] * slope
        return MA_Score

    def onBars(self, bars): 

        global bar 
        bar = bars[self.__instrument]

        slope = 8

        for instrument in bars.getInstruments():

            list_large = {}
            for tickers in testlist: #replace with real list when ready
                list_large.update({tickers : self.get_score(slope)}) 

            organized_list = OrderedDict(sorted(list_large.items(), key=lambda t: -t[1]))#organize the list from highest to lowest score

         print list_large


def run_strategy(inst):
    # Load the yahoo feed from the CSV file

    feed = yahoofinance.build_feed([inst],2015,2016, ".") # feed = yahoofinance.build_feed([inst],2015,2016, ".")

    # Evaluate the strategy with the feed.
    myStrategy = MyStrategy(feed, inst)
    myStrategy.run()
    print "Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity()


def main():
    instruments = ['ddd','msft']
    for inst in instruments:
            run_strategy(inst)


if __name__ == '__main__':
        main()

Tags: thefromimportselfdeffeedslopelist
1条回答
网友
1楼 · 发布于 2024-04-20 00:04:54

检查onBars()函数的以下代码:

slope = 8    # <   value of slope = 8 

for instrument in bars.getInstruments():
    list_large = {}
    for tickers in testlist: #replace with real list when ready
        list_large.update({tickers : self.get_score(slope)}) 
        #       Updating dict of each ticker based on ^

每次调用self.get_score(slope)时,它都返回相同的值,因此tickers的所有值在dict中保持相同的值

我不知道您想如何处理slope以及如何更新它的值。但这种逻辑可以简化,而不必使用.update,如:

list_large = {}
for tickers in testlist: 
    list_large[tickers] = self.get_score(slope)
     #           ^ Update value of `tickers` key

相关问题 更多 >