Files
2026-10-21 20:47:59 -04:00

38 lines
1.8 KiB
Python
Executable File

"""Tactical asset allocation: moving-average trend filter + inverse-volatility weights.
Evidence: Faber (2007) "A Quantitative Approach to Tactical Asset Allocation" (hold an
asset only above its ~10-month SMA; cut drawdowns roughly in half with similar returns);
risk-parity weighting per Maillard, Roncalli & Teiletche (2010). The 200-day SMA filter
has been one of the most robust bitcoin rules since 2013.
"""
from . import indicators as ind
from .base import Context, Strategy, register
@register("trend_risk_parity")
class TrendRiskParity(Strategy):
"""Each pair gets an inverse-volatility slot of capital, held only while its
close is above its long SMA; otherwise that slot sits in cash."""
default_params = {"sma": 200, "vol_window": 30, "rebalance_every": 7, "band": 0.05}
def decide(self, ctx: Context) -> dict[str, float]:
p = self.params
ready = {pair: ctx.candles[pair]["close"] for pair in self.pairs
if len(ctx.candles[pair]) > max(p["sma"], p["vol_window"]) + 1}
if not ready:
return {}
trend_up = {pair: c.iloc[-1] > ind.sma(c, p["sma"]) for pair, c in ready.items()}
rebalance = ind.is_rebalance_candle(ctx.candles[self.pairs[0]], self.interval, p["rebalance_every"])
flips = any(trend_up[pair] != (ctx.weights.get(pair, 0) > 0) for pair in ready)
if not (rebalance or flips):
return {}
inv_vol = {pair: 1 / max(ind.realized_vol(c, p["vol_window"], self.interval), 1e-9)
for pair, c in ready.items()}
total = sum(inv_vol.values())
targets = {pair: (inv_vol[pair] / total if trend_up[pair] else 0.0) for pair in ready}
return ind.banded(targets, ctx.weights, p["band"])