import backtrader as bt class MyStrategy(bt.Strategy): def init(self): self.lastclose =…
- User
import backtrader as bt
class MyStrategy(bt.Strategy): def init(self): self.last_close = 0 # 上一根k线的收盘价
codedef next(self): if self.last_close != 0: # 获取上一根k线和当前k线收盘价 close1 = self.last_close close2 = self.data.close[0] # 使用plt.plot()方法连接两个收盘价 plt.plot([self.data.datetime.datetime(0), self.data.datetime.datetime(0, 0, 1)], [close1, close2]) # 在主图中绘制连线 self.plot( subplot=False ) self.last_close = self.data.close[0]cerebro = bt.Cerebro()
data = bt.feeds.YahooFinanceData(dataname=‘AAPL’, fromdate=datetime.datetime(2020, 1, 1), todate=datetime.datetime(2020, 12, 31))
cerebro.adddata(data) cerebro.addstrategy(MyStrategy)
绘制主图
cerebro.plot() 请将此代码改为连接任意两根K线的收盘价,时间截是毫秒
- Assistant
import backtrader as bt import matplotlib.pyplot as plt # 添加此行代码 import numpy as np # 添加此行代码
class MyStrategy(bt.Strategy): def init(self): self.last_close = 0 # 上一根k线的收盘价 self.line1 = [] # 存储连接的收盘价1 self.line2 = [] # 存储连接的收盘价2
code - User
太复杂,能否简化一下?
- Assistant
当然可以!以下是一个简化版的代码,它只使用了matplotlib中的plot方法来绘制连接收盘价的线段。在每一根k线结束时,绘制从上一根k线的收盘价到当前k线的收盘价的连接线。无需使用np.interp()和np.arange()等方法。
codeimport backtrader as bt import matplotlib.pyplot as plt class MyStrategy(bt.Strategy): def init(self): self.last_close = 0 # 上一根k线的收盘价 self.line = [] # 存储连接的收盘价 def next(self): if self.last_close != 0: # 获取上一根k线和当前k线收盘价 close1 = self.last_close close2 = self.data.close[0] # 使用plt.plot()方法绘制连接线段 plt.plot([self.data.datetime.datetime(-1), self.data.datetime.datetime(0)], [close1, close2]) # 在主图中绘制连接线段 self.plot( subplot=False ) self.last_close = self.data.close[0] cerebro = bt.Cerebro() data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime.datetime(2020, 1, 1), todate=datetime.datetime(2020, 12, 31)) cerebro.adddata(data) cerebro.addstrategy(MyStrategy) # 绘制主图 cerebro.plot()