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

"""Bollinger Band mean-reversion study.

The middle band is a simple average. The width is a multiple of the population
standard deviation of that same window (divide by N, not N - 1). A close
outside a band arms the rule and is not itself an order. The order is the
later close that comes back inside. A long is left on a later close at or
through the middle band, and a short is the mirror. The entry bar is not
exited on the same 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 = "bollinger-mean-reversion"
PERIOD = 20
WIDTH = 2.0


def bands(
    close: list[float], period: int, width: float
) -> tuple[list[float | None], list[float | None], list[float | None]]:
    if period <= 1 or width <= 0:
        raise SystemExit("band period and width must be positive")
    middle: list[float | None] = [None] * len(close)
    upper: list[float | None] = [None] * len(close)
    lower: list[float | None] = [None] * len(close)
    for index in range(period - 1, len(close)):
        window = close[index - period + 1 : index + 1]
        mean = sum(window) / period
        variance = sum((price - mean) ** 2 for price in window) / period
        deviation = variance**0.5
        middle[index] = mean
        upper[index] = mean + width * deviation
        lower[index] = mean - width * deviation
    return middle, upper, lower


def signals(close: list[float], period: int = PERIOD, width: float = WIDTH) -> list[int | None]:
    middle, upper, lower = bands(close, period, width)
    position = 0
    armed_long = False
    armed_short = False
    desired: list[int | None] = []
    for index, price in enumerate(close):
        if middle[index] is None or upper[index] is None or lower[index] is None:
            desired.append(None)
            continue
        outside_lower = price < lower[index]
        outside_upper = price > upper[index]
        entered_this_bar = False
        if position == 0 and armed_long and not outside_lower:
            position = 1
            entered_this_bar = True
            armed_long = False
        elif position == 0 and armed_short and not outside_upper:
            position = -1
            entered_this_bar = True
            armed_short = False
        if not entered_this_bar and position == 1 and price >= middle[index]:
            position = 0
        elif not entered_this_bar and position == -1 and price <= middle[index]:
            position = 0
        if outside_lower:
            armed_long = True
            armed_short = False
        elif outside_upper:
            armed_short = True
            armed_long = False
        desired.append(position)
    return desired


def _assert_population_deviation() -> None:
    # Mean of 1, 2, 3 is 2. Population variance is 2/3. Upper band at 2 widths
    # is 2 + 2 * sqrt(2/3). The sample divisor (N - 1) would be wider.
    _, upper, _ = bands([1, 2, 3], 3, 2)
    expected = 2.0 + 2.0 * ((2.0 / 3.0) ** 0.5)
    if upper[2] is None or abs(upper[2] - expected) > 1e-12:
        raise SystemExit(f"population deviation fixture failed: {upper[2]}")
    flat = signals([1.0] * 30, period=5, width=2)
    if any(value not in (None, 0) for value in flat) or flat[-1] != 0:
        raise SystemExit("a flat series should not arm a band trade")


def library_trade_count(dates: list[str], rates: list[float], desired: list[int | None]) -> int:
    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,
    )
    return int(backtest.run()["# Trades"])


def main() -> None:
    _assert_population_deviation()
    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()
