最近正在學習量化交易的使用,然而在Colab上使用backtrader時卻無法跑出任何交易結果
以下是代碼:
!pip install backtrader yfinance matplotlib
import backtrader as bt
import yfinance as yf
class SmaCrossStrategy(bt.Strategy):
params = dict(
sma_short_period=3, # 短期均線週期
sma_long_period=20, # 長期均線週期
)
def __init__(self):
self.sma_short = bt.ind.SMA(period=self.p.sma_short_period)
self.sma_long = bt.ind.SMA(period=self.p.sma_long_period)
self.crossover = bt.ind.CrossOver(self.sma_short, self.sma_long)
def next(self):
# 確保均線不是 NaN,這意味著我們有足夠的數據來計算均線
if not (self.sma_short[0] != self.sma_short[0] or self.sma_long[0] != self.sma_long[0]): # 檢查均線不是 NaN
# 打印均線值和交叉值
print(f"當前日期: {self.data.datetime.date(0)}, 短期均線: {self.sma_short[0]:.2f}, 長期均線: {self.sma_long[0]:.2f}, 交叉值: {self.crossover[0]}")
print(f"目前持倉狀態: {'持有多頭' if self.position else '無持倉'}")
if not self.position:
if self.crossover > 0:
self.buy(size=10) # 增加每次購買的股數
print(f"買入: {self.data.datetime.date(0)}, 價格: {self.data.close[0]:.2f}")
elif self.crossover < 0:
self.close()
print(f"賣出: {self.data.datetime.date(0)}, 價格: {self.data.close[0]:.2f}")
print("下載數據中...")
data = yf.download('AAPL', start='2017-01-01', end='2021-01-01')
data.dropna(inplace=True)
data.columns = [str(col).lower() for col in data.columns]
data_bt = bt.feeds.PandasData(dataname=data)
cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCrossStrategy)
cerebro.adddata(data_bt)
cerebro.broker.setcash(1000000.0) # 增加初始資金以確保有足夠資金購買
cerebro.broker.setcommission(commission=0.0001) # 降低佣金以減少交易成本的影響
print(f"初始資金: {cerebro.broker.getvalue():.2f}")
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe',
timeframe=bt.TimeFrame.Days, annualize=True, riskfreerate=0.01)
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='trade_analyzer')
results = cerebro.run()
sharpe = results[0].analyzers.sharpe.get_analysis()
drawdown = results[0].analyzers.drawdown.get_analysis()
trade_analyzer = results[0].analyzers.trade_analyzer.get_analysis()
print(f"最終資產淨值: {cerebro.broker.getvalue():.2f}")
if sharpe.get('sharperatio') is not None:
print(f"夏普比率: {sharpe['sharperatio']:.2f}")
else:
print("夏普比率無法計算,請檢查策略和數據。")
print(f"最大回撤: {drawdown.max.drawdown:.2f}%")
if 'total' in trade_analyzer and 'closed' in trade_analyzer.total:
total_closed_trades = trade_analyzer.total.closed
print(f"總交易次數: {total_closed_trades}")
else:
print("沒有已關閉的交易。")
cerebro.plot(iplot=False, volume=False)
有大部分是參考 @zivzhong 大所使用的 https://ithelp.ithome.com.tw/m/articles/10354933這篇文章
希望各位大神可以救救我