"""Compare next-open fills on synthetic candles in three Python engines."""

from dataclasses import dataclass
from math import isclose

import backtesting
import backtrader as bt
import pandas as pd
import vectorbt as vbt


CASH = 1000.0
FEE = 0.001
PERIOD = 3


@dataclass(frozen=True)
class Result:
    equity: float
    fills: list[tuple[str, float]]


def candles():
    open_ = pd.Series([100, 101, 103, 105, 107, 100, 97, 100, 106, 109, 102, 96])
    close = pd.Series([100, 102, 104, 106, 101, 98, 99, 105, 108, 103, 97, 96])
    data = pd.DataFrame({
        "Open": open_,
        "High": pd.concat([open_, close], axis=1).max(axis=1) + 1,
        "Low": pd.concat([open_, close], axis=1).min(axis=1) - 1,
        "Close": close,
    })
    data.index = pd.date_range("2025-01-01", periods=len(data), freq="D")
    return data


class BacktraderStrategy(bt.Strategy):
    def __init__(self):
        self.fills = []

    def next(self):
        if len(self.data) < PERIOD:
            return
        window = self.data.close.get(size=PERIOD)
        want_long = window[-1] > sum(window) / PERIOD
        if want_long and not self.position:
            self.buy(size=1)
        elif self.position and not want_long:
            self.close()

    def notify_order(self, order):
        if order.status == order.Completed:
            self.fills.append(("buy" if order.isbuy() else "sell", order.executed.price))


def run_backtrader(data):
    engine = bt.Cerebro(stdstats=False)
    engine.broker.setcash(CASH)
    engine.broker.setcommission(commission=FEE)
    engine.adddata(bt.feeds.PandasData(dataname=data))
    engine.addstrategy(BacktraderStrategy)
    [strategy] = engine.run()
    return Result(engine.broker.getvalue(), strategy.fills)


class BacktestingStrategy(backtesting.Strategy):
    def init(self):
        pass

    def next(self):
        if len(self.data.Close) < PERIOD:
            return
        window = self.data.Close[-PERIOD:]
        want_long = window[-1] > window.mean()
        if want_long and not self.position:
            self.buy(size=1)
        elif self.position and not want_long:
            self.position.close()


def run_backtesting(data):
    engine = backtesting.Backtest(
        data, BacktestingStrategy, cash=CASH, commission=FEE, trade_on_close=False
    )
    stats = engine.run()
    fills = [
        fill
        for trade in stats["_trades"].itertuples()
        for fill in (("buy", trade.EntryPrice), ("sell", trade.ExitPrice))
    ]
    return Result(float(stats["Equity Final [$]"]), fills)


def run_vectorbt(data):
    close = data["Close"]
    signal = close.gt(close.rolling(PERIOD).mean())
    holding = signal.shift(1, fill_value=False)
    previously_holding = holding.shift(1, fill_value=False)
    portfolio = vbt.Portfolio.from_signals(
        close, entries=holding & ~previously_holding, exits=~holding & previously_holding,
        price=data["Open"], size=1, init_cash=CASH, fees=FEE, freq="1D",
    )
    fills = [(row.Side.lower(), row.Price) for row in portfolio.orders.records_readable.itertuples()]
    return Result(float(portfolio.value().iloc[-1]), fills)


def main():
    data = candles()
    expected = [("buy", 105), ("sell", 100), ("buy", 106), ("sell", 102)]
    for name, run in (
        ("Backtrader", run_backtrader),
        ("Backtesting.py", run_backtesting),
        ("vectorbt", run_vectorbt),
    ):
        result = run(data)
        if result.fills != expected or not isclose(result.equity, 990.587, abs_tol=0.000001):
            raise AssertionError(f"{name} produced unexpected fills or equity: {result}")
        print(f"{name:16} equity={result.equity:.3f}  fills={result.fills}")


if __name__ == "__main__":
    main()
