"""Backtest example - trend-following strategy that buys on upward momentum."""

import horizon as hz


# Track recent prices to compute momentum
_prices: list[float] = []


def signal(ctx: hz.Context) -> float:
    """Compute a fair value with momentum bias.

    Looks at recent price changes and biases the fair value
    slightly in the direction of the trend. This creates
    aggressive quotes that cross the market and generate fills.
    """
    feed = ctx.feeds.get("default")
    price = feed.price if feed and feed.price > 0 else 0.50

    _prices.append(price)

    # Need at least 5 data points for momentum
    if len(_prices) < 5:
        return price

    # Simple momentum: average of last 5 changes
    changes = [_prices[-i] - _prices[-i - 1] for i in range(1, min(6, len(_prices)))]
    momentum = sum(changes) / len(changes)

    # Bias fair value in the direction of momentum
    # This makes us buy when price is trending up (bid crosses market)
    return price + momentum * 10


def quoter(ctx: hz.Context, fair: float) -> list[hz.Quote]:
    """Quote with a tight spread around the momentum-biased fair value."""
    fair = max(0.01, min(0.99, fair))  # Clamp to valid range
    return hz.quotes(fair, spread=0.04, size=5)


# Simulated price data: market drifts from 0.40 to 0.60 and back
data = []
for i in range(200):
    t = float(i)
    if i < 100:
        price = 0.40 + 0.002 * i  # Drift up
    else:
        price = 0.60 - 0.002 * (i - 100)  # Drift down
    data.append({"timestamp": t, "price": round(price, 4)})


result = hz.backtest(
    name="momentum_backtest",
    markets=["test-market"],
    data=data,
    pipeline=[signal, quoter],
    risk=hz.Risk(max_position=50, max_drawdown_pct=10),
    initial_capital=1000.0,
)

print(result.summary())
print(f"\n{len(result.trades)} trades executed across {len(result.equity_curve)} ticks.")

# Export equity curve
result.to_csv("backtest_equity.csv", what="equity")
result.to_csv("backtest_trades.csv", what="trades")
print(f"Exported to backtest_equity.csv and backtest_trades.csv")
