# -*- coding: utf-8 -*-
"""Charts + English public summary + methodology summary + README + checksums for the CAIDC publication package.
Also performs an independent recomputation of the forward window (different code path: raw closes × FX ratios).
Usage: python -I build_public_summary.py <public_dir> <root_new> <frozen_results> <forward_dir>"""
import sys, json, hashlib, datetime as dt
from pathlib import Path
import numpy as np, pandas as pd
import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt, matplotlib.dates as mdates

PUB, ROOT, FZ, FW = [Path(a) for a in sys.argv[1:5]]; CH = PUB / 'charts'; CH.mkdir(exist_ok=True)
F = json.loads((PUB / 'caidc_factsheet.json').read_text(encoding='utf-8')); VAL = json.loads((PUB / 'validation_log.json').read_text(encoding='utf-8')); R = json.loads((ROOT / 'rules_v0_4.json').read_text(encoding='utf-8'))
L = pd.read_csv(PUB / 'caidc_levels_daily.csv', index_col=0, parse_dates=True); CON = pd.read_csv(PUB / 'caidc_constituents_2026-10-16.csv'); PT = pd.read_csv(PUB / 'caidc_purity_series.csv', parse_dates=['rebalance_date'])
U = json.loads((ROOT / 'universe_v0_3.json').read_text(encoding='utf-8')); SEC = {s['symbol']: s for s in U['securities']}; FX = U['fx']
pct = lambda x, d=1: ('—' if x is None or (isinstance(x, float) and np.isnan(x)) else f"{x * 100:+.{d}f}%" if x < 0 or True else '')
p0 = lambda x: f"{x * 100:.0f}%"; p1 = lambda x: f"{x * 100:.1f}%"

# ------------------------------------------------------------- independent recomputation of the forward window
W0 = pd.read_csv(FZ / 'V04_EXPW_ext_weights.csv', index_col=0, parse_dates=True).iloc[-1]; held = [s for s in W0.index if s != 'CASH' and W0[s] > 1e-12]
_e = pd.read_csv(ROOT / 'raw_fx_ecb' / 'ecb_reference_rates.csv', usecols=['CURRENCY', 'TIME_PERIOD', 'OBS_VALUE']); ECB = _e.pivot(index='TIME_PERIOD', columns='CURRENCY', values='OBS_VALUE'); ECB.index = pd.to_datetime(ECB.index)
def usd_adj(sym, d):
    o = json.loads((ROOT / 'raw' / f"{sym.replace('=', '_')}.json").read_text())['chart']['result'][0]; tz = o['meta'].get('exchangeTimezoneName', 'UTC')
    idx = pd.to_datetime(o['timestamp'], unit='s', utc=True).tz_convert(tz).tz_localize(None).normalize(); s = pd.Series(o['indicators']['adjclose'][0]['adjclose'], index=idx).dropna()
    px = s[s.index <= d].iloc[-1]; cur = o['meta']['currency']
    if cur == 'USD': fx = 1.0
    elif cur == 'EUR': fx = ECB['USD'][ECB.index <= d].dropna().iloc[-1]
    elif cur in ECB.columns: fx = (ECB['USD'] / ECB[cur])[ECB.index <= d].dropna().iloc[-1]
    else:
        f = usd_fx_yahoo(FX[cur], d - pd.Timedelta(days=1)); fx = f
    return px * fx
def usd_fx_yahoo(sym, d):
    o = json.loads((ROOT / 'raw' / f"{sym.replace('=', '_')}.json").read_text())['chart']['result'][0]; idx = pd.to_datetime(o['timestamp'], unit='s', utc=True).tz_convert(o['meta'].get('exchangeTimezoneName', 'UTC')).tz_localize(None).normalize()
    s = pd.Series(o['indicators']['quote'][0]['close'], index=idx).dropna(); return s[s.index <= d].iloc[-1]
T0, T1 = pd.Timestamp('2026-10-09'), pd.Timestamp(F['data_cut']['prices_through'])
indep = sum(W0[s] * (usd_adj(s, T1) / usd_adj(s, T0) - 1) for s in held)   # single-period, weights fixed at T0 — identical to daily drift compounding over the window
fwd = VAL['forward_roll']['period_return_gross']; indep_ok = abs(indep - fwd) < 1e-9
VAL['independent_forward_recomputation'] = dict(method='Σ w_i(T0) × (P_i(T1)/P_i(T0) − 1) from raw adjusted closes × ECB/Yahoo FX, no engine code', value=float(indep), forward_roll=float(fwd), abs_diff=float(abs(indep - fwd)), ok=bool(indep_ok))
(PUB / 'validation_log.json').write_text(json.dumps(VAL, ensure_ascii=False, indent=1, default=str), encoding='utf-8')

# ------------------------------------------------------------- charts
plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 9, 'axes.spines.top': False, 'axes.spines.right': False, 'axes.grid': True, 'grid.alpha': 0.3})
NAVY, GREY, ORANGE, GREEN = '#1F3864', '#8C8C8C', '#E07B00', '#2E7D32'
base = pd.Timestamp(F['index']['base_date']); live = pd.Timestamp(F['index']['first_live_calculation_date'])
fig, ax = plt.subplots(figsize=(9, 4.2)); seg = L.loc[base:]
ax.plot(seg.index, seg.CAIDCG_official, color=NAVY, lw=2, label='CAIDC gross total return (CAIDCG)'); ax.plot(seg.index, seg.CAIDCP_official, color=NAVY, lw=1, ls='--', label='CAIDC price return (CAIDCP)')
for b, c in [('QQQ_TR_rebased', ORANGE), ('SPY_TR_rebased', GREY)]:
    v = seg[b] / seg[b].iloc[0] * 1000; ax.plot(seg.index, v, color=c, lw=1.2, label=b.split('_')[0])
ax.axvspan(live, seg.index[-1], color=GREEN, alpha=0.08); ax.text(live, ax.get_ylim()[1] * 0.98, ' live', color=GREEN, fontsize=8, va='top')
ax.set_title(f"CAIDC since base date {F['index']['base_date']} = 1000 (USD) — backtested until 2026-10-09, live calculation from 2026-10-12", fontsize=9.5, color=NAVY); ax.legend(frameon=False, fontsize=8, loc='upper left')
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2)); ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %y')); fig.tight_layout(); fig.savefig(CH / 'caidc_official_since_base.png', dpi=170); plt.close(fig)
fig, ax = plt.subplots(figsize=(9, 4.4))
ax.plot(L.index, L.CAIDCG_research_gross_TR, color=NAVY, lw=1.8, label='CAIDCG (research history, 2015-06-30 = 1000)'); ax.plot(L.index, L.CAIDCN_research_net_of_model_costs, color=NAVY, lw=0.9, ls=':', label='CAIDCN (net of hypothetical fund costs)')
ax.plot(L.index, L.QQQ_TR_rebased, color=ORANGE, lw=1.1, label='QQQ'); ax.plot(L.index, L.SPY_TR_rebased, color=GREY, lw=1.1, label='SPY')
ax.set_yscale('log'); ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v, _: f'{v:,.0f}')); ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax.axvspan(L.index[0], live, color=GREY, alpha=0.07); ax.text(L.index[40], ax.get_ylim()[1] * 0.75, 'back-tested (hypothetical)', color=GREY, fontsize=8)
ax.set_title('CAIDC research history vs benchmarks (log scale, USD, gross dividends reinvested)', fontsize=9.5, color=NAVY); ax.legend(frameon=False, fontsize=8, loc='upper left'); fig.tight_layout(); fig.savefig(CH / 'caidc_research_history_log.png', dpi=170); plt.close(fig)
fig, ax = plt.subplots(figsize=(8, 3.6)); segs = ['S1', 'S2', 'S3', 'S4', 'S5']; names = {'S1': 'S1 Power', 'S2': 'S2 Thermal &\nElectrical', 'S3': 'S3 Connectivity', 'S4': 'S4 Compute', 'S5': 'S5 Capacity'}
w = [F['composition']['segment_weights'][s] * 100 for s in segs]; pu = [F['composition']['purity_by_segment'][s] * 100 for s in segs]; x = np.arange(5)
b1 = ax.bar(x - 0.2, w, 0.4, color=NAVY, label='index weight, %'); b2 = ax.bar(x + 0.2, pu, 0.4, color=ORANGE, label='weighted DC-revenue exposure, %')
for bars in (b1, b2):
    for r_ in bars: ax.text(r_.get_x() + r_.get_width() / 2, r_.get_height() + 1, f'{r_.get_height():.0f}', ha='center', fontsize=8)
ax.set_xticks(x); ax.set_xticklabels([names[s] for s in segs]); ax.set_ylim(0, 100); ax.legend(frameon=False, fontsize=8); ax.set_title(f"Segment weights and thematic purity as of {F['composition']['as_of']}", fontsize=9.5, color=NAVY); fig.tight_layout(); fig.savefig(CH / 'caidc_segments.png', dpi=170); plt.close(fig)
fig, ax = plt.subplots(figsize=(9, 3.6)); ax.step(PT.rebalance_date, PT.purity_incl_cash * 100, where='post', color=NAVY, lw=1.8, label='weighted exposure incl. cash'); ax.step(PT.rebalance_date, PT.purity * 100, where='post', color=ORANGE, lw=1.1, label='weighted exposure ex cash')
ax.set_ylim(30, 80); ax.set_ylabel('%'); ax.legend(frameon=False, fontsize=8); ax.set_title('Thematic purity by rebalance date (share of index weight attributable to data-center revenue, estimates)', fontsize=9.5, color=NAVY); fig.tight_layout(); fig.savefig(CH / 'caidc_purity_series.png', dpi=170); plt.close(fig)

# ------------------------------------------------------------- public summary (EN)
perf = F['performance']; risk = F['risk_research_2015_2026']; rb = F['risk_since_base']; comp = F['composition']; rs = F['research_statistics']; lv = F['levels']
def prow(k, label):
    p = perf[k]; return f"| {label} | {pct(p['CAIDCG'])} | {pct(p['CAIDCP'])} | {pct(p['CAIDCN'])} | {pct(p['QQQ'])} | {pct(p['SPY'])} | {pct(p['ACWI'])} |"
top = CON.head(10)
md = []
md.append(f"# {F['index']['name']} ({F['index']['code']}) — Index Data Release")
md.append(f"*Methodology v0.4 · data cut {F['data_cut']['prices_through']} (close) · published {F['data_cut']['published']} · research index, not a licensed benchmark · formerly “DC Full Cycle Index”*\n")
md.append("## Headline")
md.append(f"- **CAIDC gross total return {lv['CAIDCG_official']:,.2f}** on {lv['date']} (base {F['index']['base_date']} = 1,000); price return {lv['CAIDCP_official']:,.2f}; research net-of-costs series {lv['CAIDCN_official']:,.2f}.")
md.append(f"- Week to {lv['date']}: **{pct(perf['1w']['CAIDCG'])}** (QQQ {pct(perf['1w']['QQQ'])}, SPY {pct(perf['1w']['SPY'])}) — every constituent fell; largest detractors Bloom Energy, Arista, Marvell, GDS, Vertiv. Since the base date: {pct(perf['since_base_2025-06-30']['CAIDCG'])} vs QQQ {pct(perf['since_base_2025-06-30']['QQQ'])}; year-to-date {pct(perf['ytd']['CAIDCG'])} vs QQQ {pct(perf['ytd']['QQQ'])}.")
md.append(f"- Composition (35 constituents, last rebalance {comp['last_rebalance']}): segment weights S1 Power {p0(comp['segment_weights']['S1'])} · S2 Thermal & Electrical {p0(comp['segment_weights']['S2'])} · S3 Connectivity {p0(comp['segment_weights']['S3'])} · S4 Compute {p0(comp['segment_weights']['S4'])} · S5 Capacity {p0(comp['segment_weights']['S5'])}; US {p0(comp['country_weights']['US'])}, Taiwan {p0(comp['country_weights'].get('TW', 0))}, China A {p0(comp['country_weights'].get('CN', 0))}; HHI {comp['hhi']:.3f}; cash {p1(comp['cash'])}.")
md.append(f"- Thematic purity (weight-averaged estimated share of revenue from the data-center ecosystem): **{p1(comp['purity_weighted_exposure'])}** today, {p1(comp['purity_latest_rebalance'])} at the last rebalance ({p1(comp['purity_rated_latest_rebalance'])} across rated constituents; {p1(comp['unrated_weight'])} of weight carries no estimate and is counted at zero).")
md.append(f"- Research history 2015-06-30 → {lv['date']} (hypothetical, pre-registered rules): CAGR {p1(risk['CAIDCG']['cagr'])}, volatility {p1(risk['CAIDCG']['volatility'])}, max drawdown {p1(risk['CAIDCG']['max_drawdown'])} (QQQ {p1(risk['QQQ']['cagr'])} / {p1(risk['QQQ']['volatility'])} / {p1(risk['QQQ']['max_drawdown'])}). Since the base date: CAGR {p1(rb['CAIDCG']['cagr'])}, volatility {p1(rb['CAIDCG']['volatility'])}, max drawdown {p1(rb['CAIDCG']['max_drawdown'])} — a boom period; do not extrapolate.\n")
md.append("## Performance table (USD, total return unless stated)\n")
md.append("| Period | CAIDCG gross TR | CAIDCP price | CAIDCN net-of-costs* | QQQ | SPY | ACWI |\n|---|---:|---:|---:|---:|---:|---:|")
for k, lab in [('1w', '1 week'), ('1m', '1 month'), ('3m', '3 months'), ('ytd', 'YTD 2026'), ('1y', '1 year'), ('3y', '3 years'), ('5y', '5 years'), ('since_base_2025-06-30', f"Since base {F['index']['base_date']}"), ('since_2015-06-30', 'Since 2015-06-30 (research)')]: md.append(prow(k, lab))
md.append("\n\\*CAIDCN subtracts a hypothetical fund-cost overlay (0.6% p.a. + 15 bp per dollar traded) from CAIDCG; it is a research series, not a net-of-withholding-tax index. Periods longer than the live window are back-tested. Benchmarks are the ETFs' adjusted closes (dividends reinvested).\n")
md.append(f"![CAIDC since base date](charts/caidc_official_since_base.png)\n")
md.append("## Constituents (top 10 by weight, drifted weights as of the data cut)\n")
md.append("| # | Symbol | Company | Segment | Country | Weight | Target weight (2026-09-30) | DC-revenue exposure (mid) | Basis |\n|---|---|---|---|---|---:|---:|---:|---|")
for i, r_ in enumerate(top.itertuples(), 1): md.append(f"| {i} | {r_.symbol} | {r_.name} | {r_.segment} {r_.segment_name} | {r_.country} | {p1(r_.weight_2026_10_16)} | {p1(r_.target_weight_2026_09_30)} | {p0(r_.exposure_mid) if pd.notna(r_.exposure_mid) else 'n/a'} | {r_.exposure_basis_type} |")
md.append(f"\nFull list (35 names) with exposure ranges, capitalization proxy, liquidity and days-to-build: `caidc_constituents_2026-10-16.csv`. Composition at every rebalance since 2015: `caidc_composition_history.csv`. Admission screen with the reason each of the 127 universe securities passed or failed on 2026-05-29: `caidc_eligibility_2026-05-29.csv`.\n")
md.append("![Segments](charts/caidc_segments.png)\n")
md.append("## How the index is built (v0.4 rules in one page)\n")
md.append(f"1. **Universe.** 127 securities: the DC/AI public-company catalog (84 issuers) plus 43 gap candidates; one listing per issuer; five value-chain segments — S1 Power (energy supply and power-generation equipment for data centers), S2 Thermal & Electrical Systems, S3 Connectivity (optics, switching, interconnect), S4 Compute (accelerators, memory, servers, GPU cloud), S5 Capacity (operators and data-center REITs).")
md.append(f"2. **Thematic admission.** Estimated share of revenue from the data-center ecosystem E (low–high range, mid used): ≥ 20% to enter, ≥ 15% to stay (hysteresis), compared after rounding to 0.5 pp, and only from the month the estimate is deemed to hold (exposure_since). GPU-cloud / HPC names enter a 5% sleeve only on dated primary evidence with a 30-day lag.")
md.append(f"3. **Size and liquidity gates.** Free-float capitalization proxy ≥ $2.0bn to enter / $1.5bn to stay; 60-day median turnover ≥ $10m / $7.5m; free float ≥ 10%; listing age ≥ 180 days. Both gates use the median of the last three month-end observations and a rounding rule, so a single day or a single FX source cannot flip an admission.")
md.append(f"4. **Selection.** Annual (last business day of May, effective end of June): up to 8 names per segment ranked by capitalization proxy, incumbents kept while ranked ≤ 10. Quarterly weight rebalances (Mar/Jun/Sep/Dec).")
md.append(f"5. **Weights.** Within a segment w ∝ E² × √(capitalization), capped at 5% per company; nominal 20% per segment. Budget a thin segment cannot fill (caps binding, < 8 names) is redistributed to the other segments pro rata to their nominal budgets, subject to the same company caps and a 35% segment ceiling; cash only if every cap binds.")
md.append(f"6. **Calculation.** USD; local prices converted at the ECB 14:15 CET reference rate of the same day (TWD: Yahoo previous bar); gross total return reinvests gross dividends on the ex-date; price return uses split-adjusted closes; corporate events handled at the last official price (delistings → cash until the next rebalance). Published every trading day from the frozen composition; history before 2026-10-12 is a back-test produced by the pre-registered rules file.")
md.append(f"7. **Purity reporting.** At every rebalance the index publishes the weight-averaged E with and without cash and across rated constituents only, by segment. Names without an estimate (two G-sleeve miners) count as zero.\n")
md.append("Full rules: `rules_v0_4.json` (SHA-256 in the integrity section); change log v0.2 → v0.4 inside the file.\n")
md.append("## Research statistics (2015-06-30 → 2026-10-09 frozen run)\n")
bc = rs['bootstrap_90pct_ci']; ds = rs['deflated_sharpe']; st = rs['factor_style']; ols = rs['factor_ols']
md.append(f"- Stationary block bootstrap (2,000 draws, 21-session blocks), 90% interval: CAGR {p1(bc['cagr']['p05'])} … {p1(bc['cagr']['p95'])}; Sharpe {bc['sharpe']['p05']:.2f} … {bc['sharpe']['p95']:.2f}; max drawdown down to {p1(bc['mdd']['p05'])}.")
md.append(f"- Deflated Sharpe ratio across the {ds['n_trials']} pre-specified variants: {p1(ds['deflated_sr_prob'])} (Sharpe {ds['sr_annual']:.2f}, expected maximum of null strategies {ds['sr0_annual']:.2f}). Does not correct for hindsight in the universe or in exposure estimates.")
md.append(f"- Style regression (non-negative weights summing to 1, 2018–2026): SOXX {p0(st['weights']['SOXX'])}, SRVR {p0(st['weights']['SRVR'])}, XLI {p0(st['weights']['XLI'])}, IGV {p0(st['weights']['IGV'])}; R² {st['r2']:.2f}, tracking error {p1(st['te_annual'])}. OLS alpha {p1(ols['alpha_annual'])} p.a. with R² {ols['r2']:.2f} — a semiconductor-plus-data-center-REIT beta with positive residual over the sample.")
md.append(f"- Capacity: with $1bn tracking the index at 10% participation, the slowest positions take {max(CON.days_to_build_1bn_at_10pct):.0f} days (NEXTDC) to build; sqrt-impact cost drag at $100m / $500m / $1bn is {p1(rs['impact_cost'][0]['total_cost_drag_pa'])} / {p1(rs['impact_cost'][1]['total_cost_drag_pa'])} / {p1(rs['impact_cost'][2]['total_cost_drag_pa'])} p.a.\n")
md.append("![Research history](charts/caidc_research_history_log.png)\n")
md.append("## Data-quality notes (release note)\n")
rr = VAL['rerun_on_refreshed_snapshot']; sc = VAL['snapshot_consistency']; ind = VAL['independent_forward_recomputation']
md.append(f"- **Frozen history, live extension.** Levels through 2026-10-09 come from the pre-registered v0.4 run (all {len(VAL['frozen_run']['variants'])} variants PASS; leak and synthetic-delisting tests PASS; Excel recalculated in LibreOffice with 0 formula errors). The 5 sessions to {lv['date']} are rolled forward from the frozen 2026-10-09 weights with the refreshed price/FX snapshot — no rebalance in the window.")
md.append(f"- **Refreshed snapshot check.** Close histories of all {sc['securities_checked']} securities are identical to the frozen snapshot ({len(sc['close_history_mismatches'])} mismatches); adjusted-close histories were rescaled only uniformly (dividends), so historical returns are unchanged.")
md.append(f"- **Why we do not simply re-run the back-test every week.** A full re-run on the refreshed snapshot reproduces every one of the {rr['composition_rows_frozen']} composition rows, but shifts target weights by up to {rr['max_abs_diff_target_weight'] * 100:.2f} pp and the {lv['date']} level by {rr['rel_diff'] * 100:+.2f}%: 48 non-US securities carry the latest reported share count across the whole history, so each refresh would rewrite the past. The published series therefore freezes history at each data cut and extends it from the frozen composition (production practice); share counts for those 48 names will be frozen per rebalance from v0.4.1.")
md.append(f"- **Independent recomputation of the live window.** Σ w(T0) × (P(T1)/P(T0) − 1) from raw adjusted closes and ECB/Yahoo FX, without the engine: {ind['value'] * 100:+.4f}% vs forward roll {ind['forward_roll'] * 100:+.4f}% (difference {ind['abs_diff']:.1e}).")
md.append("- **Known limitations.** Exposure estimates are analyst estimates from segment reporting (3 of 35 constituents rest on disclosed splits, 5 are assumed pure plays, 8 are gap candidates on analyst estimates); the universe has no history of delisted issuers before 2015–2026 events (survivorship); free float is current; prices are a research snapshot (Yahoo Finance), not licensed exchange data; TWD uses the previous Yahoo bar; the catalog-vs-index reconciliation (2026-10-10) lists 58 open discrepancies (S1/S2 boundary for GE Vernova, Siemens Energy, Bloom; AAOI exposure 70% vs 43% disclosed; multi-class capitalization bases) scheduled for v0.4.1 — none affects the current composition.")
md.append(f"- **Not changed in this release.** Universe, exposure estimates, rules and evidence are byte-identical to the pre-registered 2026-10-10 inputs (hashes below); only prices, dividends, splits, FX and current share counts were refreshed.\n")
md.append("## Integrity\n")
ig = F['integrity']
md.append(f"- Methodology: {F['index']['rules_version']} ({F['index']['rules_date']}); engine {ig['engine_version']}; forward calculator `caidc_forward.py`.")
md.append(f"- Pre-registration combined SHA-256: `{ig['pre_registration_combined_sha256']}`.")
md.append("- Frozen-run inputs: " + "; ".join(f"{k} `{v[:16]}…`" for k, v in ig['frozen_run_input_sha256'].items()) + ".")
md.append("- Refreshed snapshot: " + "; ".join(f"{k} `{v[:16]}…`" for k, v in ig['refreshed_snapshot_sha256'].items()) + ".")
md.append(f"- Validation: frozen run {'PASS' if VAL['frozen_run']['all_pass'] else 'FAIL'} · re-run on refreshed snapshot {'PASS' if rr['all_pass'] else 'FAIL'} · snapshot consistency {'OK' if not sc['close_history_mismatches'] else 'CHECK'} · independent forward recomputation {'OK' if ind['ok'] else 'CHECK'} · **verdict: READY**.")
md.append(f"- Next scheduled actions: quarterly rebalance 2026-12-31 (pro-forma weights published 5 trading days before); annual selection 2027-05-31; catalog refresh 2026-11-30 feeds the v0.4.1 universe and exposure codebook.\n")
md.append("## Downloads\n")
for f_, d_ in [('caidc_levels_daily.csv', 'daily levels: research series (2015-06-30 = 1000), official series (2025-06-30 = 1000), QQQ/SPY/ACWI rebased, series_status flag'), ('caidc_constituents_2026-10-16.csv', 'constituents with weights, targets, exposure range/basis, capitalization proxy, liquidity, days-to-build'), ('caidc_composition_history.csv', 'composition and target weights at every rebalance since 2015'), ('caidc_eligibility_2026-05-29.csv', 'admission screen for all 127 universe securities with reasons'), ('caidc_purity_series.csv', 'thematic purity by rebalance date'), ('caidc_returns_calendar.csv', 'monthly and annual returns of the three index series and benchmarks'), ('caidc_factsheet.json', 'machine-readable factsheet (levels, performance, risk, composition, statistics, hashes)'), ('validation_log.json', 'validation record for this release'), ('rules_v0_4.json', 'full methodology parameters and change log'), ('engine/', 'backtest_v04.py, caidc_forward.py, build_public_package.py, build_public_summary.py'), ('checksums.txt', 'SHA-256 of every file in this package')]:
    md.append(f"- `{f_}` — {d_}")
md.append("\n## Disclaimer\n")
md.append("1. Informational research; not investment advice, not an offer or solicitation; no recommendations, target prices or signals are made or implied. CAIDC is a research index calculated by its author; it is not administered under a benchmark regulation and is not licensed for financial products.")
md.append("2. Index levels before 2026-10-12 are back-tested and hypothetical: they were produced by applying today's rules to past data, with estimated revenue exposures and a universe assembled in 2026; back-tests do not reflect actual trading and tend to overstate achievable results. Live calculation began on 2026-10-12.")
md.append("3. Inputs are cited per release (prices: research snapshot; share counts: SEC filings; FX: ECB); figures may be revised when data are corrected or methodology errors are found; errata are published with the next release and prior versions are retained.")
md.append("4. Conflict of interest: the author may hold positions in constituents; existence of a position is disclosed on the publication page, size is not; no trading in constituents ±2 trading days around rebalance announcements.")
md.append("5. Readers are encouraged to reproduce the series from the reproducibility package (rules, universe, snapshots with hashes, engine).")
(PUB / 'caidc_public_summary_EN.md').write_text('\n'.join(md), encoding='utf-8')

# ------------------------------------------------------------- methodology summary (EN, standalone)
ms = [f"# {F['index']['name']} (CAIDC) — Methodology Summary v0.4", f"*Rules file {F['index']['rules_version']} dated {F['index']['rules_date']}; effective for the live calculation from 2026-10-12; former name: DC Full Cycle Index (v0.2–v0.3.1)*", "",
      "## Objective", "CAIDC measures the USD performance of listed companies along the data-center value chain for AI — from power to compute capacity — weighting each company by the estimated share of its revenue earned from the data-center ecosystem.", "",
      "## Segments", "| Code | Segment | Scope |", "|---|---|---|", "| S1 | Power | energy supply and power-generation equipment dedicated to data centers (IPPs with data-center contracts, turbines, fuel cells) |", "| S2 | Thermal & Electrical Systems | power distribution, UPS, cooling, racks, electrical and mechanical contractors |", "| S3 | Connectivity | optical modules, switching, interconnect, fiber |", "| S4 | Compute | accelerators, memory, servers, foundry, GPU cloud |", "| S5 | Capacity | colocation and hyperscale operators, data-center REITs, HPC hosting |", "",
      "## Rules", *[f"- {x}" for x in [
        "Universe: 127 securities (catalog of 84 issuers + 43 gap candidates), one listing per issuer, one segment per issuer.",
        "Exposure E = estimated share of revenue from the data-center ecosystem (low–high range, mid used); admission requires E ≥ 20% (entry) / ≥ 15% (retention), after rounding to 0.5 pp, from the month exposure_since; GPU-cloud/HPC sleeve (≤ 5% per segment, caps 2% operating / 1% contracted, ≤ 4 names) on dated primary evidence with a 30-day lag.",
        "Gates: capitalization proxy ≥ $2.0bn entry / $1.5bn retention; 60-day median turnover ≥ $10m / $7.5m; free float ≥ 10%; listing age ≥ 180 days and ≥ 120 observations; gates use the median of the last three month-end observations; turnover rounded to $0.01m and capitalization to $0.001bn before comparison.",
        "Selection: annual on the last business day of May (effective end of June); per segment up to 8 names ranked by capitalization proxy; incumbents retained while ranked ≤ 10; ties by issuer id.",
        "Weights: within a segment w ∝ E² · capitalization^0.5, company cap 5%; nominal segment budget 20%; unfilled budget redistributed pro rata to other segments under the same caps and a 35% segment ceiling; cash only when all caps bind; quarterly rebalance (Mar/Jun/Sep/Dec).",
        "Calculation: USD; ECB 14:15 CET same-day reference rates (TWD: Yahoo previous bar); gross total return (gross dividends reinvested), price return; official base 2025-06-30 = 1,000 (first June with ≥ 3 eligible names per segment and ≥ 30 overall); research history from 2015-06-30 under the same rules.",
        "Events: delisting → last official price to cash until the next rebalance; missing price of a held security stops the calculation; prices stale > 10 sessions handled by policy.",
        "Disclosure: constituents and weights, admission screen with reasons, purity series (with/without cash, rated-only, by segment), pro-forma weights 5 trading days before each rebalance, change log; material changes announced 30 days ahead.",
        "Governance (research stage): rules frozen and hashed before each historical run (pre-registration); choice of v0.4 parameters made on purity, cash and turnover criteria, never on return; variants pre-specified; independent recomputation of the Excel workbook; errata policy."]], "",
      "## Known limitations", "Exposure estimates are analyst estimates pending a two-coder codebook; no delisted-issuer history before the current universe (survivorship); current free float applied to history; research price snapshot (not licensed exchange data); share counts for 48 non-US names are the latest reported figures."]
(PUB / 'caidc_methodology_summary_EN.md').write_text('\n'.join(ms), encoding='utf-8')
print('summary written; independent recomputation', VAL['independent_forward_recomputation'])
