有一个包含许多(比如 10 个)股票名称的 pickle 文件,还有一个包含所有股票数据的文件夹位置,手头现金。当我走到这一步并试图在所有股票上运行 MACD 时。但是经过两次循环后,数据加载错误。并重复结果。
'''
import backtrader as bt
import pandas as pd
import pickle
import math
def run_test_macd():
with open("sp500tickers.pickle", "rb") as f:
tickers = pickle.load(f)
cerebro.addstrategy(GoldenCross.gold_cross_class)
for ticker in tickers:
macd_stock_test2(ticker)
def macd_stock_test2(ticker):
# print("stock test")
# print("ticker")
cerebro.broker.set_cash(1000000)
ticker_prices = pd.read_csv('stock_dfs/{}.csv'.format(ticker), index_col='Date', parse_dates=True)
# print(ticker_prices)
# ticker prices
feed = bt.feeds.PandasData(dataname=ticker_prices)
print(feed)
print(ticker)
cerebro.adddata(feed)
# cerebro.addsizer(bt.sizers.FixedSize, stake=1000)
# cerebro.addanalyzer(btanalyzers.DrawDown, _name='drawdown')
# cerebro.addanalyzer(btanalyzers.DrawDown, _name='returns')
print('starting protfolio value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('final protfolio value: %.2f' % cerebro.broker.getvalue())
# cerebro.addanalyzer(SQN)
#
# cerebro.addwriter(bt.WriterFile, csv=args.writercsv, rounding=2)
# cerebro.plot(style='candle')
class gold_cross_class(bt.Strategy):
#set parameters to define fast and slow
params = (('fast',40),('slow',150),('order_percentage',0.99),('ticker', "stock"))
#define constractors
def __init__(self):
print("position size:",self.position.size)
self.fast_moving_average=bt.indicators.EMA(
self.data.close, period=self.params.fast, plotname='40 day moving average'
)
self.slow_moving_average = bt.indicators.EMA(
self.data.close, period=self.params.slow, plotname='150 day moving average'
)
self.crossover = bt.indicators.CrossOver(self.fast_moving_average, self.slow_moving_average)
def next(self):
if self.position.size == 0:
if self.crossover >0:
amount_to_invest = (self.params.order_percentage *self.broker.cash)
self.size=math.floor(amount_to_invest/self.data.close)
print("Buy {} shares of {} at {} on {}".format(self.size,self.params.ticker, self.data.close[0],self.data.close[0]))
self.buy(size=self.size)
if self.position.size > 0:
if self.crossover<0:
print("Sell {} shares of {} at {}".format(self.size,self.params.ticker, self.data.close[0]))
self.sell(size=self.size)
'''