For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
How to pass data to Stra
-
How to pass data to strategy parameters?
My code:
class MyStrategy(bt.Strategy): def __init__(self,sell_profit, stop_loss): self.sell_profit = sell_profit self.stop_loss = stop_loss def next(self): if self.position: pnl_pct = (self.data.close[0] / self.position.price) - 1.0 if pnl_pct >= self.sell_level: self.sell() elif pnl_pct <= -self.stop_loss_level: self.close() else: if self.data.td_seq==9: self.buy(size=1)
arr = [1.01,1.02,1.03,1.04,1.05,1.06,1.07,1.08,1.09,1.10] initial_balance = cerebro.broker.setcash(25000.0) best_profit = 0 for sell_profit in arr: for stop_loss in arr: cerebro.addstrategy(MyStrategy, sell_profit=sell_profit, stop_loss=stop_loss) cerebro.addsizer(bt.sizers.FixedSize, stake=3) result = cerebro.run() final_balance = cerebro.broker.getvalue() total_profit = final_balance - initial_balance if total_profit > best_profit: best_profit = total_profit best_sell_profit= sell_profit best_stop_loss = stop_loss
-
@Mohsin-Shabbir, you need to define strategy parameters as parameters.
params = dict(stoploss=1.0, sell=1.0)
Then you can access these parameters in the strategy with self.p.stoploss and self.p.sell.
Backtrader wraps the strategy class in a meta class, so some things are a little different from what you know if you haven’t worked with meta classes before. It confused me a lot in the beginning, but now I appreciate the flexibility.
I recommend that you reread some of the documentation and follow the examples in there. It really helps, because some concepts are a little counter-intuitive. (Probably more a problem with my intuition, as I found again and again that the author of BT is much smarter than me.)