"""HYPOTHETICAL BACKTEST, exported as plain Python. Not investment advice.

%%RULE_SUMMARY%%

What this file is
-----------------
Backtest Configurator %%PACKAGE_VERSION%% (export format %%EXPORT_FORMAT%%) wrote this file from a
validated strategy spec. Run on a price file and membership file that the configurator accepts, it
reproduces the configurator engine's decisions, trades, equity curve and metrics. It does not repeat
every refusal the configurator makes, so run the configurator on your files first.
It needs pandas and NumPy (and pyarrow for Parquet files) plus the Python standard library, and it
does not import the configurator.

Every number it writes is a hypothetical, simulated result on your own data, made with hindsight.

%%DISCLOSURES%%

No live signal
--------------
The simulation stops at the last decision whose trades fill inside your data: it does not evaluate
a decision whose fill falls after the last real bar (the last session with a close) in your file.
Rows with no price at all are refused, and --run-date cannot be later than today. It writes no
holdings "as of today". This is a rule about the data in your file: anyone who adds a fabricated bar
with prices for a future session defeats it.

Spec hashes (the run receipt names the same values)
---------------------------------------------------
spec_sha256:        %%SPEC_SHA256%%
spec_behavior_hash: %%SPEC_BEHAVIOR_HASH%%
calendar:           %%CALENDAR_VERSION%% (sha256 %%CALENDAR_SHA256%%)

The receipt also records this file's own SHA-256. If you edit the file, the receipt no longer
describes it.

Usage
-----
    python strategy.py [--prices PATH] [--membership PATH] [--out DIR] [--run-date YYYY-MM-DD]

It writes results.json, equity.csv and trades.csv to --out (default: strategy_results).
"""

from __future__ import annotations

import argparse
import bisect
import csv
import json
import math
import re
from dataclasses import dataclass, field
from datetime import date, timedelta
from decimal import Decimal
from fractions import Fraction
from pathlib import Path

import numpy as np
import pandas as pd


# =====================================================================================================
# 1. The strategy, as written in the spec. Each value names the spec field it comes from.
# =====================================================================================================

SPEC_SHA256 = %%SPEC_SHA256_REPR%%
SPEC_BEHAVIOR_HASH = %%SPEC_BEHAVIOR_HASH_REPR%%
EXPORT_FORMAT = %%EXPORT_FORMAT_REPR%%

%%SPEC_CONSTANTS%%

HYPOTHETICAL = ("Hypothetical backtest: simulated with hindsight on your own data, not real trading. "
                "Not investment advice.")


# =====================================================================================================
# 2. The pinned NYSE calendar (the same table the configurator ships). Sessions are weekdays minus the
#    exchange's scheduled holidays, minus unscheduled closures. Schedules use scheduled sessions; a
#    scheduled session closed by an unscheduled closure moves to the next open session, so no
#    schedule depends on information from after the decision.
# =====================================================================================================

CALENDAR_FIRST = date(%%CAL_FIRST%%)
CALENDAR_LAST = date(%%CAL_LAST%%)
SCHEDULED_HOLIDAYS = """
%%CAL_HOLIDAYS%%
"""
UNSCHEDULED_CLOSURES = """
%%CAL_CLOSURES%%
"""


def build_calendar() -> tuple[list[date], list[date], set[date]]:
    """Scheduled sessions, open sessions and unscheduled closures, from the tables above."""
    holidays = {date.fromisoformat(x) for x in SCHEDULED_HOLIDAYS.split()}
    closures = {date.fromisoformat(x) for x in UNSCHEDULED_CLOSURES.split()}
    scheduled = []
    day = CALENDAR_FIRST
    while day <= CALENDAR_LAST:
        if day.weekday() < 5 and day not in holidays:
            scheduled.append(day)
        day += timedelta(days=1)
    open_sessions = [x for x in scheduled if x not in closures]
    return scheduled, open_sessions, closures


def schedule_sessions(frequency: str, on: str, first: date, last: date) -> list[date]:
    """Decision sessions in [first, last]: the first or last scheduled session of each week, month or
    quarter, moved to the next open session if an unscheduled closure shut it."""
    scheduled, open_sessions, closures = build_calendar()
    if not (CALENDAR_FIRST <= first <= CALENDAR_LAST and CALENDAR_FIRST <= last <= CALENDAR_LAST):
        raise ValueError("dates outside the pinned calendar's range")
    groups: dict[tuple[int, int], list[date]] = {}
    for day in scheduled:
        if frequency == "weekly":
            iso = day.isocalendar()
            period_key = (iso.year, iso.week)
        elif frequency == "monthly":
            period_key = (day.year, day.month)
        else:  # quarterly
            period_key = (day.year, (day.month - 1) // 3)
        groups.setdefault(period_key, []).append(day)
    out: list[date] = []
    for period_key in sorted(groups):
        days = groups[period_key]
        chosen = days[-1] if on == "last_session" else days[0]
        if chosen in closures:
            chosen = open_sessions[bisect.bisect_right(open_sessions, chosen)]
        if first <= chosen <= last and (not out or out[-1] != chosen):
            out.append(chosen)
    return out


# =====================================================================================================
# 3. Reading your files. Prices are proportionally back-adjusted (total-return) open, high, low and
#    close; raw_close and raw_volume, if present, feed only the price and liquidity filters. A column
#    named volume is never read. Invalid rows stop the run (no value is guessed).
# =====================================================================================================

PRICE_COLUMNS = ("open", "high", "low", "close")
FILTER_COLUMNS = ("raw_close", "raw_volume")
DATE_RE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
TICKER_RE = re.compile(r"^[A-Z0-9][A-Z0-9.\-]{0,14}$")
EMPTY = ("", "nan", "NaN", "NA", "null", "None")


def read_table(path: str, fmt: str) -> pd.DataFrame:
    """A CSV (leading '#' comment lines skipped) or Parquet file, values as text or numbers."""
    if fmt == "parquet":
        table = pd.read_parquet(path)
    else:
        skip = 0
        with open(path, "r", encoding="utf-8-sig") as handle:
            for line in handle:
                if not line.startswith("#"):
                    break
                skip += 1
        table = pd.read_csv(path, dtype=str, keep_default_na=False, skiprows=skip, encoding="utf-8-sig")
    table.columns = [str(c).strip() for c in table.columns]
    return table


def parse_dates(column: pd.Series) -> np.ndarray:
    if pd.api.types.is_datetime64_any_dtype(column):
        stamps = pd.to_datetime(column)
        if getattr(stamps.dt, "tz", None) is not None:
            stamps = stamps.dt.tz_localize(None)
        if (stamps.isna() | (stamps != stamps.dt.normalize())).any():
            raise ValueError("a date is missing or has a time of day")
        return stamps.dt.normalize().to_numpy(dtype="datetime64[D]")
    text = column.astype(str).str.strip()
    ok = text.str.match(DATE_RE.pattern).to_numpy()
    parsed = pd.to_datetime(text.where(ok, None), format="%Y-%m-%d", errors="coerce")
    if (~ok | parsed.isna().to_numpy()).any():
        raise ValueError("a date is not in YYYY-MM-DD form")
    return parsed.to_numpy(dtype="datetime64[D]")


def parse_numbers(column: pd.Series) -> np.ndarray:
    if pd.api.types.is_numeric_dtype(column):
        values = column.to_numpy(dtype=np.float64, na_value=np.nan).copy()
    else:
        text = column.astype(str).str.strip()
        empty = text.isin(EMPTY).to_numpy()
        values = pd.to_numeric(text.where(~empty, None), errors="coerce").to_numpy(dtype=np.float64).copy()
        if (np.isnan(values) & ~empty).any():
            raise ValueError(f"column {column.name} has a value that is not a number")
    values[np.isinf(values)] = np.nan
    return values


def read_prices(path: str, fmt: str, run_date: date, open_sessions: list[date]) -> pd.DataFrame:
    """The long price table. It repeats the configurator's file checks only in part: run the configurator first."""
    raw = read_table(path, fmt)
    missing = [c for c in ("date", "ticker") + PRICE_COLUMNS + REQUIRED_FILTER_COLUMNS if c not in raw.columns]
    if missing:
        raise ValueError("the price file is missing column(s): " + ", ".join(missing))
    days = parse_dates(raw["date"])
    tickers = raw["ticker"].astype(str).str.strip().to_numpy()
    if not all(TICKER_RE.match(t) for t in tickers):
        raise ValueError("a ticker is not valid (capital letters, digits, '.' or '-')")
    cols = {c: parse_numbers(raw[c]) for c in PRICE_COLUMNS + FILTER_COLUMNS if c in raw.columns}
    o, h, lo, c = cols["open"], cols["high"], cols["low"], cols["close"]
    with np.errstate(invalid="ignore"):
        bad = (o <= 0) | (h <= 0) | (lo <= 0) | (c <= 0) | (h < lo) | (c < lo) | (c > h) | (o < lo) | (o > h)
        if "raw_close" in cols:
            bad |= cols["raw_close"] <= 0
        if "raw_volume" in cols:
            bad |= cols["raw_volume"] < 0
    if bad.any():
        raise ValueError(f"{int(bad.sum())} rows have impossible prices (non-positive, or outside [low, high])")
    if (np.isnan(o) & np.isnan(h) & np.isnan(lo) & np.isnan(c)).any():
        raise ValueError("a row has no price at all (open, high, low and close empty): a placeholder, not a bar")
    if (days > np.datetime64(run_date, "D")).any():
        raise ValueError("the price file has bars dated after the run date (bars from the future are refused)")
    calendar = np.array(open_sessions, dtype="datetime64[D]")
    pos = np.clip(np.searchsorted(calendar, days), 0, len(calendar) - 1)
    if (calendar[pos] != days).any():
        raise ValueError("the price file has a date that is not a session of the pinned NYSE calendar")
    pairs = pd.Series(tickers).astype(str) + "|" + pd.Series(days.astype(str))
    if pairs.duplicated().any():
        raise ValueError("the price file has a duplicate date and ticker")
    long = pd.DataFrame({"date": days, "ticker": tickers, **cols})
    return long.sort_values(["date", "ticker"], kind="mergesort").reset_index(drop=True)


def read_membership(path: str, fmt: str) -> dict[str, list[tuple[date, date | None]]]:
    """Membership intervals: a ticker is a member at session d when start <= d < end (empty end: still
    a member). Several intervals per ticker are allowed."""
    raw = read_table(path, fmt)
    starts = parse_dates(raw["start"])
    if "end" in raw.columns and not pd.api.types.is_datetime64_any_dtype(raw["end"]):
        end_text = raw["end"].astype(str).str.strip().replace({"nan": "", "None": "", "NaT": ""})
        ends = np.full(len(raw), np.datetime64("NaT", "D"), dtype="datetime64[D]")
        given = (end_text != "").to_numpy()
        if given.any():
            ends[given] = parse_dates(end_text[given])
    elif "end" in raw.columns:
        ends = raw["end"].to_numpy(dtype="datetime64[D]")
    else:
        ends = np.full(len(raw), np.datetime64("NaT", "D"), dtype="datetime64[D]")
    intervals: dict[str, list[tuple[date, date | None]]] = {}
    for t, s, e in zip(raw["ticker"].astype(str).str.strip(), starts.tolist(), ends.tolist()):
        intervals.setdefault(t, []).append((s, e))
    return {t: sorted(v, key=lambda x: x[0]) for t, v in sorted(intervals.items())}


@dataclass
class Market:
    """Prices on the calendar's session axis: one row per open session, one column per ticker, NaN
    where your file has no value. Row i holds what was known at the close of session i."""
    sessions: list[date]
    tickers: list[str]
    open: np.ndarray
    high: np.ndarray
    low: np.ndarray
    close: np.ndarray
    raw_close: np.ndarray
    raw_volume: np.ndarray
    column: dict[str, int] = field(default_factory=dict)

    def __post_init__(self) -> None:
        self.column = {t: j for j, t in enumerate(self.tickers)}


def to_market(long: pd.DataFrame, open_sessions: list[date], period_start: date) -> Market:
    """The session axis runs from the earlier of your first bar and the first session of the period
    to your last bar."""
    tickers = sorted(long["ticker"].unique().tolist())
    days = long["date"].to_numpy(dtype="datetime64[D]")
    axis_first = open_sessions[bisect.bisect_left(open_sessions, period_start)]
    first = min(axis_first, days.min().astype(object))
    real = np.isfinite(long["close"].to_numpy(dtype=np.float64))
    last = (days[real] if real.any() else days).max().astype(object)   # the last real bar (a close)
    keep = (days >= np.datetime64(first, "D")) & (days <= np.datetime64(last, "D"))
    long, days = long.loc[keep], days[keep]
    sessions = [d for d in open_sessions if first <= d <= last]
    rows = np.searchsorted(np.array(sessions, dtype="datetime64[D]"), days)
    position = {t: j for j, t in enumerate(tickers)}
    cols = np.array([position[t] for t in long["ticker"].tolist()], dtype=np.int64)
    grids = {}
    for name in PRICE_COLUMNS + FILTER_COLUMNS:
        grid = np.full((len(sessions), len(tickers)), np.nan)
        if name in long.columns:
            grid[rows, cols] = long[name].to_numpy(dtype=np.float64)
        grids[name] = grid
    return Market(sessions, tickers, **grids)


# =====================================================================================================
# 4. Signals. Each value at session t is computed from a fixed window of sessions at or before t,
#    from the values in that window only, summed left to right (no running sums), so a value never
#    depends on anything outside its window. A window with a missing row or value gives NaN
#    ("unknown"); nothing is filled in. lag(x, k) is x as it was k sessions earlier: shift(k) with
#    k >= 0 only.
# =====================================================================================================

def lag(frame: pd.DataFrame, k: int) -> pd.DataFrame:
    """The value k sessions before each session (k >= 0: past only)."""
    if k < 0:
        raise ValueError("lag() reads the past only: a negative lag would read future sessions")
    return frame.shift(k)


def known(value: pd.DataFrame, reads: list[tuple[pd.DataFrame, range]]) -> pd.DataFrame:
    """Keep a value only where every session it reads has a value, and the result is finite."""
    complete = np.isfinite(value.to_numpy())
    for frame, lags in reads:
        for k in lags:
            complete &= lag(frame, k).notna().to_numpy()
    return value.where(complete)


def window_sum(frame: pd.DataFrame, oldest_lag: int, newest_lag: int) -> pd.DataFrame:
    """Sum of frame over lags oldest_lag down to newest_lag, added oldest first."""
    total = lag(frame, oldest_lag)
    for k in range(oldest_lag - 1, newest_lag - 1, -1):
        total = total + lag(frame, k)
    return total


%%SIGNAL_FUNCTIONS%%

def compute_signals(market: Market) -> dict[str, np.ndarray]:
    """Every signal the rule uses, for every session and ticker (row i: known at the close of i)."""
    frames = {name: pd.DataFrame(getattr(market, name), columns=market.tickers)
              for name in PRICE_COLUMNS + FILTER_COLUMNS}
    out = {}
%%SIGNAL_CALLS%%
    return out


# =====================================================================================================
# 5. The decision grid and the eligibility rule. Every value is rounded to whole units of 1e-9 before
#    any comparison, ranking or weighting; thresholds are decimals with at most 9 places, converted
#    exactly. A value within 5e-10 of a threshold therefore counts as equal to it, and values that
#    round to the same unit tie and are ordered by ticker.
# =====================================================================================================

UNIT = 10 ** 9


def on_grid(x: float) -> int | None:
    """x in units of 1e-9 (round half to even); None if unknown."""
    if x is None or not math.isfinite(x):
        return None
    return int(np.rint(np.float64(x) * 1e9))


def row_on_grid(values: np.ndarray) -> list[int | None]:
    scaled = np.rint(np.asarray(values, dtype=np.float64) * 1e9)
    return [None if not math.isfinite(x) else int(x) for x in scaled.tolist()]


def decimal_units(text: str) -> int:
    """A decimal string, exactly, in units of 1e-9."""
    return int(Decimal(text) * UNIT)


def compare(a: int | None, op: str, b: int | None) -> bool | None:
    """A comparison on the grid; unknown if either side is unknown."""
    if a is None or b is None:
        return None
    return {">": a > b, ">=": a >= b, "<": a < b, "<=": a <= b}[op]


@dataclass(frozen=True)
class Compare:
    """signal op threshold (a decimal) or signal op other_signal."""
    left: str
    op: str
    right: str
    right_is_signal: bool = False

    def value(self, grid: dict[str, int | None]) -> bool | None:
        other = grid.get(self.right) if self.right_is_signal else decimal_units(self.right)
        return compare(grid.get(self.left), self.op, other)


@dataclass(frozen=True)
class All:
    """False if any part is false; otherwise unknown if any part is unknown; otherwise true."""
    parts: tuple

    def value(self, grid: dict[str, int | None]) -> bool | None:
        vals = [p.value(grid) for p in self.parts]
        if any(v is False for v in vals):
            return False
        return None if any(v is None for v in vals) else True


@dataclass(frozen=True)
class Any_:
    """True if any part is true; otherwise unknown if any part is unknown; otherwise false."""
    parts: tuple

    def value(self, grid: dict[str, int | None]) -> bool | None:
        vals = [p.value(grid) for p in self.parts]
        if any(v is True for v in vals):
            return True
        return None if any(v is None for v in vals) else False


@dataclass(frozen=True)
class Not:
    """The opposite; not unknown is unknown."""
    part: object

    def value(self, grid: dict[str, int | None]) -> bool | None:
        v = self.part.value(grid)
        return None if v is None else not v


%%ELIGIBLE_RULE%%


# =====================================================================================================
# 6. The event loop. For each session d, in this order:
#    1. open of d: orders due at the open fill at the adjusted open, sells first, then buys (scaled
#       down pro rata if cash is short; no leverage);
#    2. close of d: orders due at the close fill the same way;
#    3. stale positions: a held asset with no bar for 10 sessions is booked as closed at its last
#       close minus normal sell costs;
#    4. mark every position at its last close;
#    5. on a decision session: eligibility, ranks and target weights from data at or before d, and
#       orders for the difference to the current weights, filled FILL_OFFSET sessions later.
#    An order with no price at its fill time is cancelled: no fallback price, no retry.
# =====================================================================================================

STALE_SESSIONS = 10
DUST = 1e-9


@dataclass
class Order:
    j: int
    ticker: str
    side: str
    decision_row: int
    decision_session: date
    target: int
    current: int
    full_exit: bool
    fraction: float
    notional: float
    wait: int
    at: str


@dataclass
class Trade:
    decision_session: date
    fill_session: date
    fill_time: str
    ticker: str
    side: str
    weight_before: int
    weight_after: int
    status: str
    reason: str = ""
    units: float = 0.0
    price_adjusted: float = math.nan
    fill_price_adjusted: float = math.nan
    notional: float = 0.0
    commission: float = 0.0
    fees: float = 0.0
    slippage_cost: float = 0.0
    buy_scale: float = 1.0


@dataclass
class Rules:
    """What the loop needs to know about the rule (the strategy, or the equal-weight benchmark)."""
    frequency: str
    on: str
    eligible: object
    rank_by: str | None
    descending: bool
    top_n: int | None
    all_eligible: bool
    weighting: str
    weighting_signal: str | None
    max_weight: str | None
    fixed_weights: tuple
    hold: str
    hold_as_of: date | None


STRATEGY = Rules(FREQUENCY, ON, ELIGIBLE, RANK_BY, ORDER == "descending", TOP_N, ALL_ELIGIBLE, WEIGHTING,
                 WEIGHTING_SIGNAL, MAX_WEIGHT, FIXED_WEIGHTS, UNFILLED_SLOTS, HOLD_AS_OF)


def equal_weight_universe(frequency: str) -> Rules:
    """Every eligible universe member (membership, as_of, a bar at t and the universe filters, not the
    strategy's own condition), equal weight, the strategy's timing and costs, cash for none."""
    return Rules(frequency, ON, None, None, False, None, True, "equal", None, None, (), "cash", None)


def membership_grid(market: Market, members: dict | None) -> np.ndarray:
    """member[i, j]: ticker j is in the universe at session i."""
    grid = np.zeros((len(market.sessions), len(market.tickers)), dtype=bool)
    days = np.array(market.sessions, dtype="datetime64[D]")
    if STATIC_MEMBERS is not None:
        for t, as_of in STATIC_MEMBERS.items():
            j = market.column.get(t)
            if j is not None:
                grid[:, j] = True if as_of is None else days >= np.datetime64(as_of, "D")
    elif members is not None:
        for t, spans in members.items():
            j = market.column.get(t)
            if j is None:
                continue
            for s, e in spans:
                a = np.searchsorted(days, np.datetime64(s, "D"), side="left")
                b = len(days) if e is None else np.searchsorted(days, np.datetime64(e, "D"), side="left")
                grid[a:b, j] = True
    return grid


def target_weights(rules: Rules, market: Market, values: dict[str, np.ndarray], row: int, member: np.ndarray,
                   bars_so_far: np.ndarray, dollar_volume: np.ndarray) -> tuple[dict[int, int], str, int, int, int]:
    """Targets in units of 1e-9 at the close of session `row`, from data at or before it only."""
    grid = {sid: row_on_grid(v[row]) for sid, v in values.items()}
    has_bar = np.isfinite(market.close[row])
    min_price = decimal_units(MIN_PRICE_RAW) if MIN_PRICE_RAW is not None else None
    min_dv = decimal_units(MIN_DOLLAR_VOLUME) if MIN_DOLLAR_VOLUME is not None else None
    eligible = []
    for j in range(len(market.tickers)):
        if not member[j] or not has_bar[j]:
            continue
        if MIN_HISTORY_BARS is not None and not bars_so_far[j] >= MIN_HISTORY_BARS:
            continue
        if min_price is not None and compare(on_grid(market.raw_close[row, j]), ">=", min_price) is not True:
            continue
        if min_dv is not None and compare(on_grid(dollar_volume[row, j]), ">=", min_dv) is not True:
            continue
        if rules.eligible is not None:
            if rules.eligible.value({sid: grid[sid][j] for sid in grid}) is not True:
                continue   # false or unknown: not eligible
        eligible.append(j)

    if rules.all_eligible:
        chosen = list(eligible)
        slots = len(chosen)
    else:
        ranked = []
        for j in eligible:
            v = grid[rules.rank_by][j]
            if v is not None:
                ranked.append((-v if rules.descending else v, market.tickers[j], j))
        ranked.sort()   # ties: ticker ascending
        chosen = [j for _, _, j in ranked[: rules.top_n]]
        slots = rules.top_n

    targets: dict[int, int] = {}
    if rules.weighting == "equal":
        if slots:
            for j in chosen:
                targets[j] = UNIT // slots
    elif rules.weighting == "fixed":
        for t, w in rules.fixed_weights:
            j = market.column.get(t)
            if j is not None and j in set(eligible):
                targets[j] = decimal_units(w)
    else:  # inverse volatility, from volatilities on the grid; unknown or zero volatility: no weight
        vols = {j: grid[rules.weighting_signal][j] for j in chosen}
        vols = {j: v for j, v in vols.items() if v is not None and v > 0}
        if vols and slots:
            inverse = {j: Fraction(1, v) for j, v in vols.items()}
            total = sum(inverse.values())
            share = Fraction(len(vols), slots)
            for j, x in inverse.items():
                targets[j] = math.floor(UNIT * x / total * share)
            cap = decimal_units(rules.max_weight) if rules.max_weight is not None else UNIT
            for j in list(targets):
                targets[j] = min(targets[j], cap)

    unfilled = UNIT - sum(targets.values())
    unfilled_to = "cash"
    if rules.hold != "cash" and unfilled > 0:
        h = market.column.get(rules.hold)
        session = market.sessions[row]
        if h is not None and has_bar[h] and (rules.hold_as_of is None or session >= rules.hold_as_of):
            targets[h] = targets.get(h, 0) + unfilled
            unfilled_to = rules.hold
    targets = {j: w for j, w in targets.items() if w > 0}
    return targets, unfilled_to, unfilled, len(eligible), len(chosen)


def cash_scale(notionals: list[float], cash: float) -> float:
    """Pro-rata scale for the buys so that notionals plus commissions fit in the cash."""
    if cash <= 0:
        return 0.0
    binding: set[int] = set()
    s = 0.0
    for _ in range(len(notionals) + 2):
        fixed = sum(MIN_COMMISSION for k in binding)
        var = sum(notionals[k] for k in binding) + sum(
            notionals[k] * (1.0 + COMMISSION) for k in range(len(notionals)) if k not in binding)
        s = max(0.0, (cash - fixed) / var) if var > 0 else 0.0
        s = min(s, 1.0)
        now_binding = {k for k in range(len(notionals)) if COMMISSION * notionals[k] * s < MIN_COMMISSION}
        if now_binding == binding:
            break
        binding = now_binding
    while s > 0 and sum(g * s + max(COMMISSION * g * s, MIN_COMMISSION) for g in notionals) > cash:
        s *= 1.0 - 1e-12
    return s


@dataclass
class Simulation:
    sessions: list[date]
    equity: np.ndarray
    cash: np.ndarray
    invested: np.ndarray
    decisions: list[dict]
    trades: list[Trade]
    closed_stale: list[dict]
    stale_at_end: list[tuple[str, date, float]]


def simulate(rules: Rules, market: Market, values: dict[str, np.ndarray], members: dict | None,
             haircut: float = 0.0) -> Simulation:
    """Run the rule over the data. `haircut` is only for the stress lines (section 8)."""
    sessions, tickers = market.sessions, market.tickers
    n_rows, n_tickers = len(sessions), len(tickers)
    last_row = int(np.searchsorted(np.array(sessions, dtype="datetime64[D]"), np.datetime64(PERIOD_END, "D"),
                                   side="right")) - 1
    if last_row < 0:
        raise ValueError("the data starts after the period ends")
    schedule = schedule_sessions(rules.frequency, rules.on, PERIOD_START, sessions[last_row]) \
        if sessions[last_row] >= PERIOD_START else []
    row_of = {d: i for i, d in enumerate(sessions)}
    decision_rows = [row_of[d] for d in schedule if d in row_of]
    # A decision is evaluated only if its fill falls inside the data. Later ones (at most the last
    # few) only cancel unfilled orders, as a new decision would; their targets are never computed.
    evaluated = {r for r in decision_rows if r + FILL_OFFSET <= last_row}
    first_row = decision_rows[0] if decision_rows else last_row + 1

    member = membership_grid(market, members)
    bars_so_far = np.cumsum(np.isfinite(market.close), axis=0)
    dollar_volume = values.get("_dollar_volume", np.full((n_rows, n_tickers), np.nan))
    fill_price = market.open if FILL == "next_open" else market.close
    at = "open" if FILL == "next_open" else "close"

    start_capital = float(INITIAL_CAPITAL)
    dust = DUST * start_capital
    cash = start_capital
    units = np.zeros(n_tickers)
    bought_row = np.full(n_tickers, -1, dtype=np.int64)
    last_close = np.full(n_tickers, np.nan)
    last_bar_row = np.full(n_tickers, -1, dtype=np.int64)
    first_fill_price = np.full(n_tickers, np.nan)
    pending: list[Order] = []
    decisions: list[dict] = []
    trades: list[Trade] = []
    closed_stale: list[dict] = []
    equity_s = np.full(n_rows, np.nan)
    cash_s = np.full(n_rows, np.nan)
    invested_s = np.full(n_rows, np.nan)

    def execute(batch: list[Order], i: int, kind: str) -> None:
        nonlocal cash
        day = sessions[i]
        priced = []
        for o in sorted(batch, key=lambda o: (o.side != "sell", o.ticker)):
            assert i > o.decision_row, "a fill must come after its decision"
            p = float(fill_price[i, o.j])
            if not math.isfinite(p):
                trades.append(Trade(o.decision_session, day, kind, o.ticker, o.side, o.current, o.target,
                                    "cancelled", f"no valid {kind} price at the fill session"))
                continue
            priced.append((o, p))
        for o, p in [x for x in priced if x[0].side == "sell"]:
            u = units[o.j] if o.full_exit else units[o.j] * o.fraction
            if u <= 0:
                trades.append(Trade(o.decision_session, day, kind, o.ticker, o.side, o.current, o.target,
                                    "cancelled", "nothing held at the fill session"))
                continue
            fp = p * (1.0 - SLIPPAGE)
            notional = u * fp
            commission = max(COMMISSION * notional, MIN_COMMISSION)
            fee = SELL_FEES * notional
            cash += notional - commission - fee
            units[o.j] = 0.0 if o.full_exit else units[o.j] - u
            if units[o.j] <= 0:
                units[o.j] = 0.0
                bought_row[o.j] = -1
            trades.append(Trade(o.decision_session, day, kind, o.ticker, o.side, o.current, o.target, "filled", "",
                                u, p, fp, notional, commission, fee, u * p * SLIPPAGE, 1.0))
        buys = [x for x in priced if x[0].side == "buy"]
        if not buys:
            return
        need = [(o.notional, max(COMMISSION * o.notional, MIN_COMMISSION)) for o, _ in buys]
        scale = 1.0
        if sum(g + c for g, c in need) > cash:
            scale = cash_scale([o.notional for o, _ in buys], cash) if cash > dust else 0.0
        for o, p in buys:
            g = o.notional * scale
            if g <= dust:
                trades.append(Trade(o.decision_session, day, kind, o.ticker, o.side, o.current, o.target,
                                    "cancelled", "no cash for the buy"))
                continue
            commission = max(COMMISSION * g, MIN_COMMISSION)
            fp = p * (1.0 + SLIPPAGE)
            u = g / fp
            cash -= g + commission
            if units[o.j] <= 0:
                bought_row[o.j] = i
            units[o.j] += u
            first_fill_price[o.j] = p
            trades.append(Trade(o.decision_session, day, kind, o.ticker, o.side, o.current, o.target, "filled", "",
                                u, p, fp, g, commission, 0.0, u * p * SLIPPAGE, scale))

    # One pass over the sessions up to the end of the period, in date order. (Written as enumerate():
    # the Backtest Auditor's LA11 check reads `for i in range(last_row + 1)` as a parameter sweep, a
    # false alarm on this loop; see the configurator README, "M2: export form and the Auditor".)
    for i, day in enumerate(sessions[: last_row + 1]):
        # 1-2. fills due today
        due_open, due_close, waiting = [], [], []
        for o in pending:
            o.wait -= 1
            if o.wait == 0:
                (due_open if o.at == "open" else due_close).append(o)
            else:
                waiting.append(o)
        pending = waiting
        if due_open:
            execute(due_open, i, "open")
        if due_close:
            execute(due_close, i, "close")
        # 3. stale positions, from rows dated at or before today only
        has_bar = np.isfinite(market.close[i])
        last_close[has_bar] = market.close[i, has_bar]
        last_bar_row[has_bar] = i
        for j in np.flatnonzero(units > 0).tolist():
            if i - max(int(last_bar_row[j]), int(bought_row[j])) >= STALE_SESSIONS:
                k = int(last_bar_row[j])
                price = float(last_close[j]) if k >= 0 else float(first_fill_price[j])
                value = units[j] * price * (1.0 - haircut)
                fp_value = value * (1.0 - SLIPPAGE)
                commission = max(COMMISSION * fp_value, MIN_COMMISSION) if fp_value > 0 else 0.0
                proceeds = fp_value - commission - SELL_FEES * fp_value
                cash += proceeds
                closed_stale.append({"ticker": tickers[j], "last_bar": sessions[k] if k >= 0 else day,
                                     "recognised": day, "units": float(units[j]), "last_close": price,
                                     "proceeds": proceeds, "costs": value - proceeds})
                units[j] = 0.0
                bought_row[j] = -1
        # 4. mark at the last close
        mark = np.where(last_bar_row >= 0, last_close, first_fill_price)
        held = units > 0
        invested = float(np.sum(units[held] * mark[held])) if held.any() else 0.0
        equity = cash + invested
        equity_s[i], cash_s[i], invested_s[i] = equity, cash, invested
        # 5. decide
        if i in decision_rows and i not in evaluated:
            for o in pending:   # a new decision replaces unfilled orders; this one is not evaluated
                trades.append(Trade(o.decision_session, day, o.at, o.ticker, o.side, o.current, o.target,
                                    "superseded", f"replaced by the decision at the close of {day}"))
            pending = []
            continue
        if i not in evaluated:
            continue
        targets, unfilled_to, unfilled, n_eligible, n_chosen = target_weights(
            rules, market, values, i, member[i], bars_so_far[i], dollar_volume)
        for o in pending:
            trades.append(Trade(o.decision_session, day, o.at, o.ticker, o.side, o.current, o.target,
                                "superseded", f"replaced by the decision at the close of {day}"))
        pending = []
        orders: list[Order] = []
        for j in sorted(set(np.flatnonzero(units > 0).tolist()) | set(targets), key=lambda j: tickers[j]):
            current = on_grid(units[j] * mark[j] / equity) if equity > 0 else 0
            target = targets.get(j, 0)
            if units[j] > 0 and target == 0:   # full exits always trade
                orders.append(Order(j, tickers[j], "sell", i, day, target, current, True, 1.0, 0.0,
                                    FILL_OFFSET, at))
                continue
            diff = target - current
            if diff == 0 or abs(diff) < decimal_units(MIN_TRADE_WEIGHT) or equity <= 0:
                continue
            if diff > 0:
                orders.append(Order(j, tickers[j], "buy", i, day, target, current, False, 0.0,
                                    diff / UNIT * equity, FILL_OFFSET, at))
            else:
                orders.append(Order(j, tickers[j], "sell", i, day, target, current, False,
                                    float((current - target) / current if current else 1.0), 0.0, FILL_OFFSET, at))
        decisions.append({"session": day, "targets": [(tickers[j], w) for j, w in
                                                      sorted(targets.items(), key=lambda x: tickers[x[0]])],
                          "orders": [(o.ticker, o.side, o.target) for o in orders], "unfilled_to": unfilled_to,
                          "unfilled_weight": unfilled, "eligible": n_eligible, "selected": n_chosen,
                          "equity": equity})
        pending.extend(orders)

    stale_at_end = []
    for j in np.flatnonzero(units > 0).tolist():
        k = int(last_bar_row[j])
        if k < last_row:
            value = float(units[j] * (last_close[j] if k >= 0 else first_fill_price[j]))
            stale_at_end.append((tickers[j], sessions[k] if k >= 0 else sessions[last_row], value))
    a, b = first_row, last_row + 1
    return Simulation(sessions[a:b], equity_s[a:b], cash_s[a:b], invested_s[a:b], decisions, trades,
                      closed_stale, stale_at_end)


# =====================================================================================================
# 7. Benchmarks: buy and hold of a ticker from the strategy's first fill session (same fill time, one
#    buy's costs), and the equal-weight universe through the same loop.
# =====================================================================================================

def buy_and_hold(market: Market, strategy: Simulation, ticker: str) -> tuple[np.ndarray, int, int]:
    j = market.column[ticker]
    row_of = {d: i for i, d in enumerate(market.sessions)}
    equity = np.full(len(strategy.sessions), float(INITIAL_CAPITAL))
    if not strategy.sessions:
        return equity, 0, 0
    first_fill_row = row_of[strategy.sessions[0]] + FILL_OFFSET
    price = (market.open if FILL == "next_open" else market.close)[:, j]
    close = market.close[:, j]
    capital = float(INITIAL_CAPITAL)
    held, bought, mark, missing, waiting = 0.0, False, math.nan, 0, 0
    for k, day in enumerate(strategy.sessions):
        i = row_of[day]
        if not bought and i >= first_fill_row and math.isfinite(price[i]):
            if COMMISSION * capital / (1.0 + COMMISSION) >= MIN_COMMISSION:
                spend = capital / (1.0 + COMMISSION)
            else:
                spend = capital - MIN_COMMISSION
            held = max(spend, 0.0) / (price[i] * (1.0 + SLIPPAGE))
            mark = price[i]
            bought = True
        if math.isfinite(close[i]):
            mark = close[i]
        elif bought:
            missing += 1
        if bought:
            equity[k] = held * mark
        elif i >= first_fill_row:
            waiting += 1    # held as cash: no valid price to buy at yet
    return equity, missing, waiting


def aligned(other: Simulation, strategy: Simulation) -> np.ndarray:
    where = {d: k for k, d in enumerate(other.sessions)}
    out = np.full(len(strategy.sessions), np.nan)
    for k, day in enumerate(strategy.sessions):
        if day in where:
            out[k] = other.equity[where[day]]
    return out


# =====================================================================================================
# 8. Metrics (hypothetical; net of the stated costs; cash earns 0%) and the stress lines.
# =====================================================================================================

PERIODS_PER_YEAR = 252


def series_metrics(curve: np.ndarray) -> dict:
    eq = np.asarray(curve, dtype=np.float64)
    eq = eq[np.isfinite(eq)]
    out: dict = {"sessions": int(len(eq))}
    if len(eq) < 2 or eq[0] <= 0:
        out.update(total_return=None, cagr=None, annualized_volatility=None, sharpe_ratio=None,
                   max_drawdown=None)
        return out
    daily = eq[1:] / eq[:-1] - 1.0
    years = len(daily) / PERIODS_PER_YEAR
    sd = float(np.std(daily, ddof=1)) if len(daily) > 1 else float("nan")
    out["total_return"] = float(eq[-1] / eq[0] - 1.0)
    out["cagr"] = float((eq[-1] / eq[0]) ** (1.0 / years) - 1.0) if eq[-1] > 0 and years > 0 else None
    out["annualized_volatility"] = sd * math.sqrt(PERIODS_PER_YEAR) if math.isfinite(sd) else None
    out["sharpe_ratio"] = (float(np.mean(daily)) / sd * math.sqrt(PERIODS_PER_YEAR)
                           if math.isfinite(sd) and sd > 0 else None)
    out["max_drawdown"] = float(np.min(eq / np.maximum.accumulate(eq) - 1.0))
    return out


def strategy_metrics(sim: Simulation) -> dict:
    m = series_metrics(sim.equity)
    filled = [t for t in sim.trades if t.status == "filled"]
    traded = sum(t.notional for t in filled)
    costs = sum(t.commission + t.fees + t.slippage_cost for t in filled)
    costs += sum(c["costs"] for c in sim.closed_stale)
    eq = sim.equity[np.isfinite(sim.equity)]
    avg_eq = float(np.mean(eq)) if len(eq) else float("nan")
    years = max(len(eq) - 1, 1) / PERIODS_PER_YEAR
    m.update({
        "fills": len(filled),
        "orders_cancelled": sum(1 for t in sim.trades if t.status == "cancelled"),
        "orders_superseded": sum(1 for t in sim.trades if t.status == "superseded"),
        "total_costs": float(costs),
        "annual_turnover": float(traded / avg_eq / years) if avg_eq > 0 else None,
        "average_invested_share": float(np.nanmean(sim.invested / sim.equity)) if len(sim.equity) else None,
        "terminations_booked": len(sim.closed_stale),
        "positions_stale_at_end": len(sim.stale_at_end),
        "initial_capital": float(INITIAL_CAPITAL),
        "final_equity": float(eq[-1]) if len(eq) else None,
    })
    return m


def comparison(strategy_curve: np.ndarray, bench_curve: np.ndarray) -> dict:
    """Both series on the sessions where both exist."""
    ok = np.isfinite(strategy_curve) & np.isfinite(bench_curve)
    out = {"sessions_compared": int(ok.sum()), "sessions_dropped": int((~ok).sum())}
    ms, mb = series_metrics(strategy_curve[ok]), series_metrics(bench_curve[ok])
    out["benchmark"] = mb
    if ms["total_return"] is not None and mb["total_return"] is not None:
        out["total_return_difference"] = ms["total_return"] - mb["total_return"]
    return out


def stress_lines(base_total: float | None, market: Market, values: dict, members: dict | None) -> dict:
    """Total return if every booked closure and every position stale at the end had returned -30% and
    -100% at its last close (stress values, not estimates)."""
    out: dict = {"note": "Stress values, not estimates: every booked termination and every position stale at "
                         "the end is assumed to have returned the stated amount at its last close."}
    for name, cut in (("minus_30_percent", 0.30), ("minus_100_percent", 1.0)):
        alt = simulate(STRATEGY, market, values, members, haircut=cut)
        stale_value = sum(v for _, _, v in alt.stale_at_end) * cut
        if base_total is None:
            out[name] = None
            continue
        total = (float(alt.equity[-1]) - stale_value) / float(INITIAL_CAPITAL) - 1.0
        out[name] = {"total_return": total, "change_in_total_return": total - base_total}
    return out


# =====================================================================================================
# 9. Output files. Weights are written as decimals with 9 places; other numbers exactly (repr).
# =====================================================================================================

def weight_text(units_1e9: int) -> str:
    sign = "-" if units_1e9 < 0 else ""
    q = abs(units_1e9)
    return f"{sign}{q // UNIT}.{q % UNIT:09d}"


def number_text(x: float | None) -> str:
    return "" if x is None or x != x else repr(float(x))


def plain(v):
    """JSON-ready: no NaN or infinity, dates as text."""
    if isinstance(v, (float, np.floating)):
        return float(v) if math.isfinite(v) else None
    if isinstance(v, np.integer):
        return int(v)
    if isinstance(v, date):
        return v.isoformat()
    if isinstance(v, dict):
        return {k: plain(x) for k, x in v.items()}
    if isinstance(v, (list, tuple)):
        return [plain(x) for x in v]
    return v


def write_csv(path: Path, columns: list[str], rows: list[list]) -> None:
    with open(path, "w", encoding="utf-8", newline="") as handle:
        handle.write(f"# {HYPOTHETICAL}\n# spec_sha256 {SPEC_SHA256}\n")
        out = csv.writer(handle, lineterminator="\n")
        out.writerow(columns)
        out.writerows(rows)


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description="Hypothetical backtest exported by Backtest Configurator.")
    parser.add_argument("--prices", default=PRICES_PATH)
    parser.add_argument("--membership", default=MEMBERSHIP_PATH)
    parser.add_argument("--out", default="strategy_results")
    parser.add_argument("--run-date", default=None, help="bars after this date are refused (default: today)")
    args = parser.parse_args(argv)
    run_date = date.fromisoformat(args.run_date) if args.run_date else date.today()
    if run_date > date.today():
        raise SystemExit("--run-date cannot be later than today")

    _, open_sessions, _ = build_calendar()
    long = read_prices(args.prices, PRICES_FORMAT, run_date, open_sessions)
    members = read_membership(args.membership, MEMBERSHIP_FORMAT) if UNIVERSE_KIND == "membership_file" else None
    market = to_market(long, open_sessions, PERIOD_START)
    values = compute_signals(market)

    sim = simulate(STRATEGY, market, values, members)
    metrics = strategy_metrics(sim)
    curves: dict[str, np.ndarray] = {}
    bench_metrics: dict = {}
    for kind, ticker, rebalance in BENCHMARKS:
        if kind == "ticker":
            if ticker not in market.column:
                continue
            curve, missing, waiting = buy_and_hold(market, sim, ticker)
            name, info = f"buy_and_hold_{ticker}", {"sessions_without_benchmark_bar": missing,
                                                    "sessions_in_cash_before_first_buy": waiting}
        else:
            curve = aligned(simulate(equal_weight_universe(rebalance or FREQUENCY), market, values, members), sim)
            name, info = "equal_weight_universe", {"note": "Inherits the universe's labels, including any "
                                                           "hindsight label."}
        curves[name] = curve
        bench_metrics[name] = {**comparison(sim.equity, curve), **info}
    stress = None
    if sim.closed_stale or sim.stale_at_end:
        stress = stress_lines(metrics.get("total_return"), market, values, members)

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    results = {
        "hypothetical": HYPOTHETICAL,
        "strategy": STRATEGY_NAME,
        "spec_sha256": SPEC_SHA256,
        "period": {"first_decision": sim.sessions[0].isoformat() if sim.sessions else None,
                   "results_end": sim.sessions[-1].isoformat() if sim.sessions else None},
        "metrics": {"strategy": metrics, "benchmarks": bench_metrics, "sensitivity": stress},
        "decisions": [{"session": d["session"].isoformat(), "unfilled_to": d["unfilled_to"],
                       "unfilled_weight": weight_text(d["unfilled_weight"]),
                       "targets": {t: weight_text(w) for t, w in d["targets"]},
                       "orders": [[t, side, weight_text(w)] for t, side, w in d["orders"]],
                       "eligible": d["eligible"], "selected": d["selected"], "equity": d["equity"]}
                      for d in sim.decisions],
        "terminations": sim.closed_stale,
        "stale_at_end": [{"ticker": t, "last_bar": d.isoformat(), "value_at_last_close": v}
                         for t, d, v in sim.stale_at_end],
    }
    (out / "results.json").write_text(json.dumps(plain(results), indent=2) + "\n", encoding="utf-8")
    names = sorted(curves)
    write_csv(out / "equity.csv", ["session", "equity_hypothetical", "cash", "invested"]
              + [f"benchmark_{n}" for n in names],
              [[d.isoformat(), number_text(sim.equity[k]), number_text(sim.cash[k]), number_text(sim.invested[k])]
               + [number_text(curves[n][k]) for n in names] for k, d in enumerate(sim.sessions)])
    write_csv(out / "trades.csv", ["decision_session", "fill_session", "fill_time", "ticker", "side", "status",
                                   "reason", "weight_before", "weight_after", "units", "price_adjusted",
                                   "fill_price_adjusted", "notional", "commission", "fees", "slippage_cost",
                                   "buy_scale"],
              [[t.decision_session.isoformat(), t.fill_session.isoformat(), t.fill_time, t.ticker, t.side,
                t.status, t.reason, weight_text(t.weight_before), weight_text(t.weight_after),
                number_text(t.units), number_text(t.price_adjusted), number_text(t.fill_price_adjusted),
                number_text(t.notional), number_text(t.commission), number_text(t.fees),
                number_text(t.slippage_cost), number_text(t.buy_scale)] for t in sim.trades])
    print(f"{HYPOTHETICAL} Wrote results.json, equity.csv and trades.csv to {out}.")


if __name__ == "__main__":
    main()
