2016-11-26 111 views
0

我使用pyalgotrade創建交易策略。我正在瀏覽代碼列表(testlist),並將它們添加到字典(list_large {})中,以及我正在使用get_score函數獲得的分數。我最近的問題是,字典中的每個ticker(list_large {})獲得相同的分數。任何想法爲什麼?功能返回相同的值爲不同的輸入

代碼:

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() 

回答

0

檢查這個代碼的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以及你如何nt來更新它的值。但是,如果不使用.update,則可以簡化此邏輯:

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

每次調用self.get_score時,它都不應該返回相同的值。該函數獲取self .__ sma [-1]並將其乘以斜率...如果每個ticker具有不同的移動平均值,那麼放入字典中的值不應該不同麼?我有點困惑... – RageAgainstheMachine

+0

@RageAgainstheMachine:你對'self.__ sma [-1] * slope'的理解是什麼?它從'self .__ sma'中取出最後一個條目,並將其與'slope'相乘。每次都不一樣嗎? –

+0

我的印象是,它需要最新的sma,但我認爲我已經編寫了代碼,以便使列表中每個單獨的代碼最新的sma。我將如何完成這項工作? – RageAgainstheMachine

相關問題