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()
每次调用self.get_score时,它都不应该返回相同的值。该函数获取self .__ sma [-1]并将其乘以斜率...如果每个ticker具有不同的移动平均值,那么放入字典中的值不应该不同么?我有点困惑... – RageAgainstheMachine
@RageAgainstheMachine:你对'self.__ sma [-1] * slope'的理解是什么?它从'self .__ sma'中取出最后一个条目,并将其与'slope'相乘。每次都不一样吗? –
我的印象是,它需要最新的sma,但我认为我已经编写了代码,以便使列表中每个单独的代码最新的sma。我将如何完成这项工作? – RageAgainstheMachine