PinecScript到Python的转换
我正在尝试将这个策略从pinescript转换为python,但是当我对它进行回溯测试时,我得到了巨大的输出值,有人可以发现是否有错误?谢谢你PinecScript到Python的转换,python,pine-script,trading,backtrader,Python,Pine Script,Trading,Backtrader,我正在尝试将这个策略从pinescript转换为python,但是当我对它进行回溯测试时,我得到了巨大的输出值,有人可以发现是否有错误?谢谢你 class WaveTrendStrategy(bt.Strategy): def __init__(self) : n1 = 21 n2 = 14 obLevel1 = 60 obLevel1 = 60 obLevel2 = 53 osLe
class WaveTrendStrategy(bt.Strategy):
def __init__(self) :
n1 = 21
n2 = 14
obLevel1 = 60
obLevel1 = 60
obLevel2 = 53
osLevel1 = -60
osLevel2 = -53
hlc3 = (self.data.high+self.data.low+self.data.close)/3
ap = hlc3
esa = bt.ind.EMA(ap,period=n1)
d = bt.ind.EMA(abs(ap - esa), period=n1)
ci = (ap - esa) / (0.015 * d)
tci = bt.ind.EMA(ci, period=n2)
wt1 = tci
wt2 = bt.ind.SMA(wt1,period=4)
self.longCondition = bt.ind.CrossUp(wt2,osLevel2)
self.shortCondition = bt.ind.CrossDown(wt2,obLevel2)
def next(self):
if self.longCondition:
self.buy()
elif self.shortCondition:
self.sell()
我不知道你为什么会有问题。我复制了你的代码,它运行良好。也许你的数据源有问题 我加进去的唯一一件事是假设你想做多做空。您当前的代码要么由长变平,要么由短变平。我在短线/长线交易之前加入了一个收盘交易
if self.getposition().size != 0:
self.close()
这是刚刚添加到我的shell中的代码。看一看,然后运行这个。它在yfinance中起作用,因此将绕过任何数据问题。如果您还有问题,请告诉我们
import datetime
import backtrader as bt
class WaveTrendStrategy(bt.Strategy):
def log(self, txt, dt=None):
""" Logging function fot this strategy"""
dt = dt or self.data.datetime[0]
if isinstance(dt, float):
dt = bt.num2date(dt)
print("%s, %s" % (dt.date(), txt))
def print_signal(self):
self.log(
f"o {self.datas[0].open[0]:7.2f} "
f"h {self.datas[0].high[0]:7.2f} "
f"l {self.datas[0].low[0]:7.2f} "
f"c {self.datas[0].close[0]:7.2f} "
f"v {self.datas[0].volume[0]:7.0f} "
# f"rsi {self.rsi[0]:5.0f}"
)
def notify_order(self, order):
""" Triggered upon changes to orders. """
# Suppress notification if it is just a submitted order.
if order.status == order.Submitted:
return
# Print out the date, security name, order number and status.
dt, dn = self.datetime.date(), order.data._name
type = "Buy" if order.isbuy() else "Sell"
self.log(
f"{order.data._name:<6} Order: {order.ref:3d}\tType: {type:<5}\tStatus"
f" {order.getstatusname():<8} \t"
f"Size: {order.created.size:9.4f} Price: {order.created.price:9.4f} "
f"Position: {self.getposition(order.data).size}"
)
if order.status == order.Margin:
return
# Check if an order has been completed
if order.status in [order.Completed]:
self.log(
f"{order.data._name:<6} {('BUY' if order.isbuy() else 'SELL'):<5} "
# f"EXECUTED for: {dn} "
f"Price: {order.executed.price:6.2f} "
f"Cost: {order.executed.value:6.2f} "
f"Comm: {order.executed.comm:4.2f} "
f"Size: {order.created.size:9.4f} "
)
def notify_trade(self, trade):
"""Provides notification of closed trades."""
if trade.isclosed:
self.log(
"{} Closed: PnL Gross {}, Net {},".format(
trade.data._name,
round(trade.pnl, 2),
round(trade.pnlcomm, 1),
)
)
def __init__(self):
n1 = 21
n2 = 14
obLevel1 = 60
obLevel1 = 60
obLevel2 = 53
osLevel1 = -60
osLevel2 = -53
hlc3 = (self.data.high + self.data.low + self.data.close) / 3
ap = hlc3
esa = bt.ind.EMA(ap, period=n1)
d = bt.ind.EMA(abs(ap - esa), period=n1)
ci = (ap - esa) / (0.015 * d)
tci = bt.ind.EMA(ci, period=n2)
wt1 = tci
wt2 = bt.ind.SMA(wt1, period=4)
self.longCondition = bt.ind.CrossUp(wt2, osLevel2)
self.shortCondition = bt.ind.CrossDown(wt2, obLevel2)
def next(self):
# Print OHLCV
self.print_signal()
if self.longCondition:
if self.getposition().size != 0:
self.close()
self.buy()
elif self.shortCondition:
if self.getposition().size != 0:
self.close()
self.sell()
if __name__ == "__main__":
cerebro = bt.Cerebro()
data = bt.feeds.YahooFinanceData(
dataname="FB",
timeframe=bt.TimeFrame.Days,
fromdate=datetime.datetime(2018, 1, 1),
todate=datetime.datetime(2021, 4, 1),
reverse=False,
)
cerebro.adddata(data, name="FB")
cerebro.addstrategy(WaveTrendStrategy)
# Execute
cerebro.run()
print(f"Final Value: {cerebro.broker.getvalue():5.2f}")
cerebro.plot()
导入日期时间
作为bt的进口反向交易者
班级战略(bt.Strategy):
def日志(self,txt,dt=None):
“”“此策略的日志记录功能”“”
dt=dt或self.data.datetime[0]
如果是持续(dt,浮动):
dt=bt.num2日期(dt)
打印(“%s,%s”%(dt.date(),txt))
def打印_信号(自身):
self.log(
f“o{self.datas[0].打开[0]:7.2f}”
f“h{self.datas[0].高[0]:7.2f}”
f“l{self.datas[0].low[0]:7.2f}”
f“c{self.datas[0].关闭[0]:7.2f}”
f“v{self.datas[0].卷[0]:7.0f}”
#f“rsi{self.rsi[0]:5.0f}”
)
def通知单(自身、订单):
“”“在更改订单时触发。”“”
#如果只是提交的订单,则禁止通知。
如果order.status==order.Submitted:
返回
#打印日期、安全名称、订单号和状态。
dt,dn=self.datetime.date(),order.data.\u name
type=“Buy”如果订单为。isbuy()否则为“销售”
self.log(
f{order.data.\u name:尝试本文中的一些方法?顺便说一句,我们无法调试代码,因为我们不知道bt.Strategy
中有什么,我们也不知道pine脚本策略中有什么。实际上,self.data
应该给出一个错误(在这一点上没有定义),除非程序的其他部分做了一些事情来定义它。backtrader代码至少在程序上看起来很好。给出预期的值,以及你得到的,否则人们很难提供帮助。此外,它主要取决于输入数据集,可能有一个真正巨大的未平仓,导致大量的未平仓