Strategy with Signals
-
I read through "strategy with signals" section of the documentation. However, I don't really understand how to code using those signals.
Let say I would like to have a strategy that :
- goes into a long position if today's closing price is lower than yesterday's
- goes into a short position if today's closing price is higher than yesterday's
How do I use the signal? Do I still have to use self.sell and self.buy? Thankss :)
-
You are referring to: Docs - Strategy with Signals
No. You don't have to use
sell
orbuy
. The signals tell the system to execute operations.A
Signal
is basically anIndicator
. It simply has to deliver values which are0
,>= 1
or<= -1
depending on the intended usage (a singleSignal
delivering the three values can be used for long/short strategies). A signal of that type is for example a moving average cross overclass MySignal(bt.Signal): params = dict(p1=10, p2=30) def __init__(self): self.lines.signal = bt.ind.CrossOver(bt.ind.SMA(period=self.p.p1), bt.ind.SMA(period=self.p.p2))
And you only have to insert the signal in the system with:
cerebro.addsignal(bt.signal.SIGNAL_LONGSHORT, MySignal
If you want finer control you can override
bt.SignalStrategy
as is actually done in the example in the HomePagefrom datetime import datetime import backtrader as bt class SmaCross(bt.SignalStrategy): params = (('pfast', 10), ('pslow', 30),) def __init__(self): sma1, sma2 = bt.ind.SMA(period=self.p.pfast), bt.ind.SMA(period=self.p.pslow) self.signal_add(bt.SIGNAL_LONG, bt.ind.CrossOver(sma1, sma2)) cerebro = bt.Cerebro() data = bt.feeds.YahooFinanceData(dataname='YHOO', fromdate=datetime(2011, 1, 1), todate=datetime(2012, 12, 31)) cerebro.adddata(data) cerebro.addstrategy(SmaCross) cerebro.run() cerebro.plot()
You can add multiple signals for each possible condition (LONG, SHORT, EXITLONG) ... it's all about experimenting.
-
Thanks @backtrader
-
I don’t know how hard it is to write an essay, because if you need a reliable college essay writing service, look no further there is a college essay writing service, specialists will write essays on it