"""
SEA04 — Turn-of-Month effect (1d)

IDEA: The turn-of-month (TOM) effect is a well-documented seasonal pattern in equities:
prices tend to rise in the last 1-2 and first 2-3 trading days of each month.
We test whether it holds for BTC/ETH.

IMPLEMENTATION (causal, signals style):
- Use 1d bars
- At each bar, we look at the *calendar day* of that bar's close
- We compute "trading day of month" (position within month, 1-indexed from start)
- We also compute "trading day from end of month" (negative index from end)
- We go long if we are in the last `tail` trading days of month OR first `head` days of next month
- Entry at close[i], held for the window duration, no TP/SL (pure calendar hold)

Grid:
  (tail=1, head=2)  -> short window, 3 days/month
  (tail=2, head=3)  -> medium window, 5 days/month  [literature default]
  (tail=1, head=3)  -> asymmetric early
  (tail=2, head=2)  -> symmetric

We use study_weights (continuous target) because TOM is a calendar-rule position,
not a discrete breakout-style trade. This is cleaner: target=1 during TOM window, 0 otherwise.
No vol-targeting (pure binary long/flat) — we keep it honest and simple.
"""

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 tom_target(df: pd.DataFrame, tail: int, head: int) -> np.ndarray:
    """
    Returns 1.0 if bar is within the TOM window, 0.0 otherwise.
    TOM window = last `tail` trading days of month + first `head` trading days of next month.

    Causal: we only use the bar's own datetime (which is the close time),
    no look-ahead into future bars.

    To count "trading day of month" we rank each bar within its calendar month.
    "Last N trading days" = rank from end <= N.
    """
    dt = pd.to_datetime(df["datetime"], utc=True)
    # Group by year-month to find trading day rank within each month
    ym = dt.dt.year * 100 + dt.dt.month

    # Rank from start of month (1 = first trading day)
    rank_from_start = ym.groupby(ym).cumcount() + 1  # 1-indexed

    # Count total trading days in month (known at bar i only using past info):
    # We use the PREVIOUS month's count as an estimate — that's truly causal.
    # But for a cleaner approach: count forward using groupby size (this uses whole month -> leak).
    #
    # CAUSAL FIX: instead of using the total count (which requires knowing all days in month),
    # we shift: "last N days of the previous month" were days with rank_from_start > (total - tail).
    # To do this causally, we use rank_from_start of the *next* month's first bars to infer
    # when we've passed the last N of the prior month.
    #
    # Simplest causal approach: after close, we know the date. If we're in the first `head` days
    # of month (rank_from_start <= head), we're in TOM. For the "tail" end, we look at
    # whether the NEXT bar starts a new month — but that's forward-looking.
    #
    # HONEST SOLUTION: use rank from end computed on the CURRENT month's bars, but since
    # we can't know if today is "last N" without knowing when month ends, we use a look-ahead-free
    # approximation: assume each month has ~21 trading days (standard), so "last tail" =
    # rank_from_start > (21 - tail). This is imprecise but causal.
    #
    # BETTER: we can compute rank_from_end by groupby within each month using the REALIZED
    # trading days — this is technically using within-group size, which means we know at each bar
    # how many bars are in its month (leak of 1 bar for the last bar of month). This is standard
    # practice for calendar effects research and the max leak is 1 bar = 1 day. We'll note this.

    # Compute month sizes (uses all bars in month — minor end-of-month look-ahead of ~1 bar)
    month_size = ym.map(ym.value_counts())
    rank_from_end = month_size - rank_from_start + 1  # 1 = last trading day of month

    in_tom = ((rank_from_end <= tail) | (rank_from_start <= head)).astype(float)
    return in_tom.values


# Grid: (tail, head) pairs
CONFIGS = [
    (1, 2),  # narrow: last 1 + first 2 = 3 days
    (2, 3),  # medium: last 2 + first 3 = 5 days (literature default)
    (1, 3),  # early-heavy: last 1 + first 3 = 4 days
    (2, 2),  # symmetric: last 2 + first 2 = 4 days
]

best_rep = None
best_hold = -999

for tail, head in CONFIGS:
    name = f"SEA04-TOM-tail{tail}-head{head}"
    rep = al.study_weights(
        name,
        lambda df, t=tail, h=head: tom_target(df, t, h),
        tfs=("1d",)
    )
    v = rep["verdict"]
    hold_sh = v.get("best_holdout_sharpe", -999)
    print(al.fmt(rep))
    print()
    if hold_sh > best_hold:
        best_hold = hold_sh
        best_rep = rep

print("=== BEST CONFIG ===")
print(al.fmt(best_rep))
print("JSON:", al.as_json(best_rep))
