#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "tiportfolio==1.4.1",
#   "pandas>=2.3",
# ]
# ///
"""Value (VTV) vs Growth (VUG) buy-and-hold comparison (reference backtest for
the value-vs-growth knowledge concept).

Two single-sleeve buy-and-hold portfolios run together so summary() shows them
side by side — the value-premium claim predicts value >= growth on risk-adjusted
return over a full cycle. This is a crude ETF proxy for the Fama-French HML
factor, not the academic long/short factor. See value-vs-growth.md for caveats.
"""
import sys
from pathlib import Path

import pandas as pd
import tiportfolio as ti

# fetch_ohlcv writes CSVs to a global cache (~/.ti/data) and prints that directory.
# Pass it as the first script argument; read the CSVs from there rather than
# hardcoding a path. Falls back to the current directory.
DATA_DIR = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".")

tickers = ["VTV", "VUG"]
frames = {}
for t in tickers:
    df = pd.read_csv(DATA_DIR / f"{t}.csv", index_col="date", parse_dates=True)
    df["close"] = df["adj_close"]  # adjusted prices only (see backtesting skill)
    frames[t] = df
common = None
for df in frames.values():
    common = df.index if common is None else common.intersection(df.index)
data = {t: df.loc[common] for t, df in frames.items()}

value = ti.Portfolio(
    "value_hold",
    [ti.Signal.Once(), ti.Select.All(), ti.Weigh.Equally(), ti.Action.Rebalance()],
    ["VTV"],
)
growth = ti.Portfolio(
    "growth_hold",
    [ti.Signal.Once(), ti.Select.All(), ti.Weigh.Equally(), ti.Action.Rebalance()],
    ["VUG"],
)

result = ti.run(ti.Backtest(value, data), ti.Backtest(growth, data))
print(result.summary())
print("TI_STATS_JSON=" + result.summary().to_json())
