kernc / backtesting.py

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.
https://kernc.github.io/backtesting.py/
GNU Affero General Public License v3.0
5.39k stars 1.05k forks source link

optimization using linked parameters not working #920

Closed gypsyzz closed 1 year ago

gypsyzz commented 1 year ago

Expected Behavior

optimization using 1 parameter for a pair of parameters, such as RSI high and low, controlled by mid +- diff

Actual Behavior

parameter does not vary, showing the same results for optimization.

Have to code the pair of parameters as separate and use constraint.

Steps to Reproduce

class RSIStrategy(Strategy):

periods = 12
rsi_diff = 20
low_thresh = 50 - rsi_diff
high_thresh = 50 + rsi_diff

def init(self):
    self.rsi_high = self.I(RSI, self.data.High, self.periods)
    self.rsi_low = self.I(RSI, self.data.Low, self.periods)

def next(self):

    if self.rsi_low[-1] < self.low_thresh:
        self.buy(size=0.001)

    if self.rsi_high[-1] > self.high_thresh:
        self.sell(size=0.001)

optimize_result = bt.optimize(rsi_diff=list(np.arange(10,30,2)), maximize='Equity Final [$]', return_heatmap=True) optimize_result[1]

Additional info

The code block below works: optimize_result = bt.optimize(low_thresh=list(np.arange(10,40,2)), high_thresh=list(np.arange(10,40,2)), maximize='Equity Final [$]',constraint=lambda p: p.low_thresh == p.high_thresh, return_heatmap=True) optimize_result[1]

kernc commented 1 year ago

parameter does not vary, showing the same results for optimization.

What does that mean?

bt.optimize(rsi_diff=list(np.arange(10,30,2)) ...

rsi_diff is not used by the strategy (neither in init() nor next()), so, obviously, changing it will have no effect.

gypsyzz commented 1 year ago

rsi_diff is used by low_thresh and high_thresh, so you're saying that only variables used in init() or next() will change, and not the part before that.

kernc commented 1 year ago

Indeed, this is how Python works. Class variables are assigned values upon class declaration.

gypsyzz commented 1 year ago

okay something new about Python everyday