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
buy. The signals tell the system to execute operations.
Signalis basically an
Indicator. It simply has to deliver values which are
<= -1depending on the intended usage (a single
Signaldelivering the three values can be used for long/short strategies). A signal of that type is for example a moving average cross over
class 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:
If you want finer control you can override
bt.SignalStrategyas is actually done in the example in the HomePage
from 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.