#!/usr/bin/env python3
# Copyright (c) 2026 fxtradingguide.com
# SPDX-License-Identifier: MIT

"""Moving-average crossover study.

Go long when the fast simple average crosses above the slow one, and short
on the opposite cross. The decision uses that observation's close. The fill
is the next observation. Nothing here is a forecast or a recommendation.
"""

from __future__ import annotations

import sys
from pathlib import Path

import pandas as pd
from backtesting import Backtest

ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "strategies" / "shared" / "python"))

from fxstudy.data import assert_sample, load_observations
from fxstudy.library import SignalStrategy
from fxstudy.report import (
    MARGIN,
    SPREAD_FRACTION,
    STARTING_CASH,
    assert_causal,
    write_report,
)

STUDY = "moving-average-crossover"
FAST = 10
SLOW = 30


def sma(values: list[float], period: int) -> list[float | None]:
    """Simple moving average. Index i uses values[i - period + 1 : i + 1] only."""
    if period <= 0:
        raise SystemExit("SMA period must be positive")
    out: list[float | None] = [None] * len(values)
    window = 0.0
    for index, price in enumerate(values):
        window += price
        if index >= period:
            window -= values[index - period]
        if index >= period - 1:
            out[index] = window / period
    return out


def signals(rates: list[float], fast: int = FAST, slow: int = SLOW) -> list[int | None]:
    """Desired position after each close: 1 long, -1 short, 0 flat, None while warming up."""
    if fast >= slow:
        raise SystemExit("the fast average must be shorter than the slow average")
    fast_average = sma(rates, fast)
    slow_average = sma(rates, slow)
    position = 0
    desired: list[int | None] = []
    for index in range(len(rates)):
        previous = index - 1
        ready = (
            previous >= 0
            and fast_average[index] is not None
            and slow_average[index] is not None
            and fast_average[previous] is not None
            and slow_average[previous] is not None
        )
        if not ready:
            desired.append(None)
            continue
        crossed_up = fast_average[previous] <= slow_average[previous] and fast_average[index] > slow_average[index]
        crossed_down = fast_average[previous] >= slow_average[previous] and fast_average[index] < slow_average[index]
        if crossed_up:
            position = 1
        elif crossed_down:
            position = -1
        desired.append(position)
    return desired


def _assert_sma() -> None:
    averages = sma([1, 2, 3, 4, 5], 3)
    if averages != [None, None, 2, 3, 4]:
        raise SystemExit(f"SMA fixture failed: {averages}")


def library_trade_count(dates: list[str], rates: list[float], desired: list[int | None]) -> int:
    """Run the signal through backtesting.py. The return column is not read."""
    frame = pd.DataFrame(
        {
            "Open": rates,
            "High": rates,
            "Low": rates,
            "Close": rates,
            "Signal": [float("nan") if value is None else float(value) for value in desired],
        },
        index=pd.to_datetime(dates),
    )
    backtest = Backtest(
        frame,
        SignalStrategy,
        cash=STARTING_CASH,
        spread=SPREAD_FRACTION,
        commission=0.0,
        margin=MARGIN,
        trade_on_close=False,
        hedging=False,
        exclusive_orders=True,
    )
    stats = backtest.run()
    return int(stats["# Trades"])


def main() -> None:
    _assert_sma()
    observations = load_observations()
    assert_sample(observations)
    rates = [item.rate for item in observations]
    assert_causal(len(rates), lambda end: signals(rates[:end]))
    desired = signals(rates)
    trades = library_trade_count([item.date for item in observations], rates, desired)
    write_report(STUDY, "python", observations, desired, str(trades))


if __name__ == "__main__":
    main()
