"""Time-series momentum (trend following) — a persistent, structurally-justified premium.

Rationale: trend has a real economic basis (slow information diffusion + flow/herding) and is
positively skewed crisis-alpha. Long when price is above its `window`-day moving average; flat
(or short, if long_short) otherwise. Position set at close[t] applies to return[t+1] — no lookahead.
"""
from __future__ import annotations

import numpy as np

from fxhnt.domain.models import PriceSeries
from fxhnt.domain.strategies.base import register, rolling_mean


class TrendFollowing:
    kind = "trend"
    rationale = "time-series momentum: persistent premium from slow info diffusion + flow; crisis-alpha"

    def positions(self, prices: PriceSeries, params: dict[str, float]) -> np.ndarray:
        window = int(params.get("window", 200))
        flat_value = -1.0 if params.get("long_short", 0.0) else 0.0
        c = prices.close
        ma = rolling_mean(c, window)
        signal = np.where(c > ma, 1.0, flat_value)
        signal[:window] = 0.0  # warmup: no position until the MA is meaningful
        pos = np.zeros(len(c))
        pos[1:] = signal[:-1]  # shift: decision at t-1 drives return at t (no lookahead)
        return pos


register(TrendFollowing())
