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

38 lines
1.6 KiB
Python
Executable File

"""Time-series momentum (trend following) with volatility targeting.
Evidence: Moskowitz, Ooi & Pedersen (2012) "Time Series Momentum" (58 futures markets);
Hurst, Ooi & Pedersen (2017) "A Century of Evidence on Trend-Following Investing";
Liu & Tsyvinski (2021) "Risks and Returns of Cryptocurrency" find strong time-series
momentum in crypto; Moreira & Muir (2017) "Volatility-Managed Portfolios" for vol scaling.
"""
from . import indicators as ind
from .base import Context, Strategy, register
@register("time_series_momentum")
class TimeSeriesMomentum(Strategy):
"""Exposure per pair = fraction of lookbacks with a positive return, scaled down
when realized volatility exceeds the target. Long-only (spot can't short)."""
default_params = {
"lookbacks": [20, 60, 120],
"target_vol": 0.6,
"vol_window": 30,
"band": 0.25, # fraction of a pair's slot; smaller changes are skipped to save fees
}
def decide(self, ctx: Context) -> dict[str, float]:
p = self.params
need = max(max(p["lookbacks"]), 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
score = sum(ind.total_return(close, n) > 0 for n in p["lookbacks"]) / len(p["lookbacks"])
scale = ind.vol_scale(close, p["target_vol"], p["vol_window"], self.interval)
targets[pair] = slot * score * scale
return ind.banded(targets, ctx.weights, p["band"] * slot)