"""SEA02 — Day-of-week effect on 1d bars.

HYPOTHESIS: Some weekdays have systematically positive (or negative) next-bar returns.
We use an EXPANDING per-weekday expectancy (causal): at each bar i, we compute the
average return for bars that share the same day-of-week, using only data up to and
including bar i. If the expanding mean is positive -> long (+1). We vol-target the
position (TP01-style) to 20% annualized.

Variations tried (small grid, <=4 configs, <=6 total backtests):
  A) raw day-of-week: long if expanding mean > 0, else flat (no short)
  B) long-short: long if expanding mean > 0, short if < 0 (full L/S)

Both run on 1d only (the only sensible TF for a day-of-week effect). Two configs -> 2
study_weights calls x 2 assets each = 4 backtests total. Well within the 6-call limit.
"""

import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np
import pandas as pd


def _dow_expectancy(df: pd.DataFrame, long_only: bool = True) -> np.ndarray:
    """Compute expanding per-weekday expectancy and return a vol-targeted position array.

    For each bar i:
    1. Determine the day-of-week of bar i.
    2. Use the EXPANDING mean of returns of all PRIOR bars (j < i) with the SAME weekday.
       (We use j < i, not j <= i, to avoid any look-ahead — the return of bar i is not
       yet realized when we decide at close[i].)
    3. If expanding_mean[dow] > 0 -> direction = +1 (long)
       If expanding_mean[dow] < 0 -> direction = -1 (short) if not long_only, else 0
       If no prior same-weekday bar -> direction = 0 (flat, wait for history)
    4. Vol-target the direction to 20% ann vol, cap 2x.
    """
    c = df["close"].values.astype(float)
    r = al.simple_returns(c)
    dt = pd.to_datetime(df["datetime"], utc=True)
    dow = dt.dt.dayofweek.values  # Monday=0, Sunday=6

    direction = np.zeros(len(c), dtype=float)
    # Accumulate sum and count per weekday causally
    dow_sum = np.zeros(7, dtype=float)
    dow_cnt = np.zeros(7, dtype=int)

    for i in range(len(c)):
        d = dow[i]
        # Decide with history up to bar i-1 (returns of bar i not yet known)
        if dow_cnt[d] > 0:
            mean_ret = dow_sum[d] / dow_cnt[d]
            if mean_ret > 0:
                direction[i] = 1.0
            elif not long_only:
                direction[i] = -1.0
            # else: 0 (flat)
        # else: flat (no history for this weekday yet)

        # Now "observe" bar i's return for future decisions
        dow_sum[d] += r[i]
        dow_cnt[d] += 1

    return al.vol_target(direction, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)


def target_long_only(df: pd.DataFrame) -> np.ndarray:
    return _dow_expectancy(df, long_only=True)


def target_long_short(df: pd.DataFrame) -> np.ndarray:
    return _dow_expectancy(df, long_only=False)


if __name__ == "__main__":
    print("=== SEA02: Day-of-week effect ===\n")

    # Config A: long-only (long on positive-expectancy weekdays, flat otherwise)
    rep_a = al.study_weights(
        "SEA02-A-LongOnly",
        target_long_only,
        tfs=("1d",),
    )
    print(al.fmt(rep_a))
    print("JSON:", al.as_json(rep_a))
    print()

    # Config B: long-short (long on positive weekdays, short on negative weekdays)
    rep_b = al.study_weights(
        "SEA02-B-LongShort",
        target_long_short,
        tfs=("1d",),
    )
    print(al.fmt(rep_b))
    print("JSON:", al.as_json(rep_b))
    print()

    # Report best config
    best_a = rep_a["verdict"]["best_holdout_sharpe"] or -999
    best_b = rep_b["verdict"]["best_holdout_sharpe"] or -999
    if best_a >= best_b:
        best_rep = rep_a
        best_name = "A-LongOnly"
    else:
        best_rep = rep_b
        best_name = "B-LongShort"

    print(f"\n>>> BEST CONFIG: {best_name}")
    print(al.fmt(best_rep))
    print("JSON:", al.as_json(best_rep))
