51 lines
1.9 KiB
Python
Executable File
51 lines
1.9 KiB
Python
Executable File
"""Novel: regime-adaptive trend / mean-reversion hybrid.
|
|
|
|
Idea: trend rules bleed money in sideways markets and mean-reversion rules get run over
|
|
in trends. Kaufman's efficiency ratio measures which regime we're in, so use trend
|
|
following when price moves efficiently and buy oversold dips when it chops. A long SMA
|
|
filter keeps it out of bear markets entirely. Unproven: validate with the backtester.
|
|
"""
|
|
|
|
from . import indicators as ind
|
|
from .base import Context, Strategy, register
|
|
|
|
|
|
@register("adaptive_regime")
|
|
class AdaptiveRegime(Strategy):
|
|
default_params = {
|
|
"er_window": 20,
|
|
"er_trend": 0.3,
|
|
"trend_ema": 20,
|
|
"regime_sma": 100,
|
|
"z_window": 20,
|
|
"z_entry": 1.5,
|
|
"z_exit": 0.0,
|
|
"target_vol": 0.6,
|
|
"vol_window": 30,
|
|
}
|
|
|
|
def decide(self, ctx: Context) -> dict[str, float]:
|
|
p = self.params
|
|
need = max(p["regime_sma"], p["er_window"], p["z_window"], p["vol_window"]) + 1
|
|
slot = 1 / len(self.pairs)
|
|
targets = {}
|
|
for pair in self.pairs:
|
|
close = ctx.candles[pair]["close"]
|
|
if len(close) <= need:
|
|
continue
|
|
in_position = ctx.weights.get(pair, 0) > 0
|
|
|
|
if close.iloc[-1] < ind.sma(close, p["regime_sma"]):
|
|
want = False
|
|
elif ind.efficiency_ratio(close, p["er_window"]) >= p["er_trend"]:
|
|
want = close.iloc[-1] > ind.ema(close, p["trend_ema"])
|
|
else:
|
|
z = ind.zscore(close, p["z_window"])
|
|
want = z <= -p["z_entry"] or (in_position and z < p["z_exit"])
|
|
|
|
if want and not in_position:
|
|
targets[pair] = slot * ind.vol_scale(close, p["target_vol"], p["vol_window"], self.interval)
|
|
elif not want and in_position:
|
|
targets[pair] = 0.0
|
|
return targets
|