"""Monthly XGBoost fund selection, walk-forward training and Tokoyo ledgers.

Run: python example_xgboost_value.py --data ./xgb-data --output ./xgb-result
An existing snapshot is reused. --offline forbids downloads.
"""
from argparse import ArgumentParser
from concurrent.futures import ThreadPoolExecutor
from hashlib import sha256
from importlib.metadata import version
import json
from pathlib import Path

import numpy as np
import pandas as pd
import requests
import xgboost as xgb
from tokoyo.market import daily_nav
from tokoyo.strategy import BacktestConfig, FundRules, Strategy, run_backtest

# The index is a valuation proxy for the fund's mandate, not its portfolio PE.
UNIVERSE = {
    '110020': ('易方达沪深300ETF联接A', '000300'),
    '110003': ('易方达上证50增强A', '000016'),
    '161017': ('富国中证500指数增强A', '000905'),
    '100032': ('富国中证红利指数增强A', '000922'),
    '000248': ('汇添富中证主要消费ETF联接A', '000932'),
    '001180': ('广发医药卫生联接A', '000991'),
    '001133': ('广发中证全指可选消费联接A', '000990'),
    '001064': ('广发中证环保ETF联接A', '000827'),
    '000968': ('广发养老指数A', '399812'),
    '161725': ('招商中证白酒指数A', '399997'),
    '001237': ('博时上证50ETF联接A', '000016'),
    '160119': ('南方中证500ETF联接A', '000905'),
    '270042': ('广发纳斯达克100ETF联接人民币A', 'overseas-us-growth'),
    '050025': ('博时标普500ETF联接A', 'overseas-us-broad'),
    '000614': ('华安德国DAX联接A', 'overseas-europe'),
    '000071': ('华夏恒生ETF联接A', 'overseas-hk'),
    '160717': ('嘉实H股指数', 'overseas-hk-china'),
    '164906': ('交银中证海外中国互联网指数A', 'overseas-china-internet'),
    '000216': ('华安黄金ETF联接A', 'gold-cn'),
    '000218': ('国泰黄金ETF联接A', 'gold-cn'),
    '160719': ('嘉实黄金', 'gold-global'),
    '160216': ('国泰大宗商品A', 'commodity-broad'),
    '162411': ('华宝标普油气A', 'commodity-oil-gas'),
    '160416': ('华安标普全球石油指数A', 'commodity-oil-equity'),
    '163208': ('诺安油气能源', 'commodity-energy'),
    '161815': ('银华抗通胀主题A', 'commodity-inflation'),
    '110017': ('易方达增强回报债券A', 'bond-enhanced'),
    '000147': ('易方达高等级信用债A', 'bond-credit'),
    '000015': ('华夏纯债A', 'bond-pure'),
    '160608': ('鹏华普天债券A', 'bond-mixed'),
}
PARAMS = dict(objective='reg:squarederror', max_depth=2, eta=.04,
              min_child_weight=10, subsample=.85, colsample_bytree=.85,
              reg_lambda=10, seed=42, nthread=2, tree_method='hist')
FEATURES = ['earnings_yield', 'pe_percentile', 'price_percentile_252', 'momentum_21', 'momentum_63',
            'momentum_126', 'momentum_252', 'reversal_5', 'zscore_63',
            'volatility_21', 'volatility_63', 'drawdown_126', 'trend_200']


def load_data(folder, offline=False):
    folder.mkdir(parents=True, exist_ok=True)
    def nav_task(code):
        file = folder / f'nav-{code}.csv'
        if not file.exists():
            if offline:
                raise FileNotFoundError(file)
            frame = daily_nav(code, start='2014-01-01', end='2025-12-31')
            frame.to_csv(file, index=False)
        frame = pd.read_csv(file, parse_dates=['date'])
        if frame.empty or frame.date.duplicated().any() or not frame.nav.gt(0).all():
            raise ValueError(f'Invalid NAV: {code}')
        if frame.daily_return.iloc[1:].isna().any():
            raise ValueError(f'Missing total-return observations: {code}')
        return code, frame
    # The upstream NAV parser embeds V8; initialize it on the main thread.
    history = {}
    for code in UNIVERSE:
        history.update([nav_task(code)])
        print(f'NAV ready: {code}', flush=True)
    def valuation_task(code):
        file = folder / f'valuation-{code}.csv'
        if not file.exists():
            if offline:
                raise FileNotFoundError(file)
            response = requests.get('https://www.csindex.com.cn/csindex-home/perf/index-perf',
                params={'indexCode': code, 'startDate': '20140101', 'endDate': '20251231'}, timeout=45)
            response.raise_for_status()
            raw = pd.DataFrame(response.json()['data'])
            if raw.empty:
                raise ValueError(f'No index valuation: {code}')
            frame = raw[['tradeDate', 'peg']].rename(columns={'tradeDate':'date', 'peg':'pe'})
            frame['date'] = pd.to_datetime(frame.date, format='%Y%m%d')
            frame.to_csv(file, index=False)
        frame = pd.read_csv(file, parse_dates=['date']).sort_values('date')
        frame['pe'] = pd.to_numeric(frame.pe, errors='coerce')
        return code, frame.drop_duplicates('date').set_index('date').pe.where(lambda s:s > 0)
    with ThreadPoolExecutor(max_workers=3) as pool:
        valuations = dict(pool.map(valuation_task, sorted({v[1] for v in UNIVERSE.values() if v[1].isdigit()})))
    return history, valuations


def make_samples(history, valuations):
    # Common observations: never fill a missing fund return with zero.
    common = None
    for frame in history.values():
        dates = pd.DatetimeIndex(frame.date)
        common = dates if common is None else common.intersection(dates)
    common = common.sort_values()
    if len(common[common < '2021-01-01']) < 800:
        raise ValueError('Need sufficient pre-2021 observations for warmup and training')
    prices, aligned, samples = {}, {}, []
    cutoffs = pd.Series(common, index=common).groupby(common.to_period('M')).last()
    # Three NAV sessions of publication lag before the month-end decision.
    cutoffs = [common[common.get_loc(day)-3] for day in cutoffs if common.get_loc(day) >= 255]
    for code, raw in history.items():
        raw = raw.set_index('date').sort_index()
        returns = raw.daily_return.copy(); returns.iloc[0] = 0.
        price = (1 + returns).cumprod().reindex(common)
        prices[code] = price
        aligned[code] = pd.DataFrame({'date':common, 'nav':raw.nav.reindex(common).to_numpy(),
            'daily_return':price.pct_change(fill_method=None).fillna(0).to_numpy()})
        r = price.pct_change(fill_method=None)
        proxy = UNIVERSE[code][1]
        pe = valuations[proxy].reindex(common, method='ffill') if proxy in valuations else pd.Series(np.nan,index=common)
        data = pd.DataFrame(index=common)
        data['earnings_yield'] = 1 / pe
        data['pe_percentile'] = pe.rolling(252, min_periods=200).rank(pct=True)
        data['price_percentile_252'] = price.rolling(252).rank(pct=True)
        for n in (21, 63, 126, 252):
            data[f'momentum_{n}'] = price.pct_change(n, fill_method=None)
        data['reversal_5'] = -price.pct_change(5, fill_method=None)
        data['zscore_63'] = (price / price.rolling(63).mean() - 1) / r.rolling(63).std()
        for n in (21, 63):
            data[f'volatility_{n}'] = r.rolling(n).std() * np.sqrt(242)
        data['drawdown_126'] = price / price.rolling(126).max() - 1
        data['trend_200'] = price / price.rolling(200).mean() - 1
        data['label'] = price.shift(-21) / price - 1
        data['label_end'] = pd.Series(common, index=common).shift(-21)
        data = data.loc[cutoffs].copy()
        data['symbol'] = code; data.index.name = 'date'
        samples.append(data.reset_index())
    panel = pd.concat(samples, ignore_index=True).sort_values(['date','symbol'])
    # Cross-sectional ranks use that date only; tree inputs need no fitted scaler.
    for feature in FEATURES:
        panel[feature] = panel.groupby('date')[feature].rank(pct=True)
    panel['label'] -= panel.groupby('date').label.transform('mean')
    return aligned, pd.DataFrame(prices), panel


def build_plans(panel, prices, output):
    plans, audits, predictions, importances = {}, [], [], []
    previous = []
    valid = panel.dropna(subset=[f for f in FEATURES if f not in {'earnings_yield','pe_percentile'}])
    for day, test in valid.groupby('date', sort=True):
        if day.year < 2020 or day.year > 2025:
            continue
        execution_month = day.to_period('M') + 1
        if execution_month.year < 2021 or execution_month.year > 2025:
            continue
        train = valid.loc[(valid.date >= day - pd.DateOffset(years=5)) &
                          (valid.label_end < day) & valid.label.notna()]
        if train.date.nunique() < 24 or len(test) != len(UNIVERSE):
            raise ValueError(f'Incomplete train/test cross-section: {day}')
        model = xgb.train(PARAMS, xgb.DMatrix(train[FEATURES], label=train.label), num_boost_round=120)
        test = test.copy(); test['prediction'] = model.predict(xgb.DMatrix(test[FEATURES]))
        history = prices.loc[:day]
        cheap = -(history.iloc[-1] / history.iloc[-757] - 1)
        test['cheap_rank'] = cheap.rank(pct=True).reindex(test.symbol).to_numpy()
        test['model_rank'] = test.prediction.rank(pct=True)
        test['score'] = .81 * test.cheap_rank + .09 * test.earnings_yield.fillna(.5) + .10 * test.model_rank
        scores = pd.Series(test.score.to_numpy(),index=test.symbol)
        order = scores.sort_values(ascending=False).index.tolist()
        chosen = [code for code in previous if order.index(code) < 10]
        for code in order:
            if len(chosen) >= 2:
                break
            if code not in chosen:
                chosen.append(code)
        previous = chosen
        trend = float((history[chosen].iloc[-1] / history[chosen].tail(200).mean() - 1).mean())
        basket = history[chosen].pct_change(fill_method=None).tail(63).mean(axis=1)
        vol = float(basket.std() * np.sqrt(242))
        exposure = 1.
        plan = {code:exposure/len(chosen) for code in chosen}
        plans[str(execution_month)] = plan
        audits.append({'month':str(execution_month),'feature_date':str(day.date()),
            'latest_training_label_end':str(train.label_end.max().date()),
            'training_cross_sections':int(train.date.nunique()),'training_rows':len(train),
            'exposure':exposure,'volatility':vol,'benchmark_trend':trend,
            **{code:plan.get(code,0.) for code in UNIVERSE}})
        predictions.append(test[['date','symbol','prediction','model_rank','cheap_rank','earnings_yield','score','label','label_end']])
        importances.append(model.get_score(importance_type='gain'))
        if str(execution_month) == '2025-12':
            model.save_model(output / 'model-2025-12.ubj')
    if len(plans) != 60:
        raise ValueError(f'Expected 60 OOS months, got {len(plans)}')
    audit = pd.DataFrame(audits)
    if not (pd.to_datetime(audit.latest_training_label_end) < pd.to_datetime(audit.feature_date)).all():
        raise AssertionError('A training label overlaps prediction time')
    audit.to_csv(output / 'monthly-targets.csv', index=False)
    pd.concat(predictions).to_csv(output / 'predictions.csv', index=False)
    pd.DataFrame(importances).fillna(0).mean().sort_values(ascending=False).to_csv(output/'feature-gain.csv')
    return plans


class MonthlyPlan:
    def __init__(self, plans):
        self.plans, self.month = plans, None
        self.remaining = 0
    def __call__(self, ctx):
        month = str(pd.Period(ctx.date, freq='M'))
        if month != self.month:
            self.month, self.remaining = month, 12
        if self.remaining:
            step = 12 - self.remaining
            self.remaining -= 1
            if step not in (0, 10):
                return None
            plan = self.plans.get(month)
            if plan is None:
                return None
            weights = {}
            for code in UNIVERSE:
                current = ctx.positions.get(code,0.) * ctx.prices[code] / ctx.equity
                target = plan.get(code,0.)
                weights[code] = current if abs(target-current) < .01 else target
            total = sum(weights.values())
            return {code:weight/max(1.,total) for code,weight in weights.items()}
        return None


def metrics(result):
    equity = result.equity_curve.set_index('date').equity
    r = equity.pct_change(fill_method=None); r.iloc[0] = equity.iloc[0] / 100000 - 1
    years = (pd.Timestamp('2025-12-31')-pd.Timestamp('2021-01-01')).days / 365.25
    frequency = len(r) / years
    peaks = np.maximum.accumulate(np.r_[100000.,equity.to_numpy()])[1:]
    return dict(annual_return=float((equity.iloc[-1]/100000)**(1/years)-1),
        annual_volatility=float(r.std()*np.sqrt(frequency)),
        max_drawdown=float((1-equity.to_numpy()/peaks).max()),
        sharpe_rf0=float(r.mean()/r.std()*np.sqrt(frequency)),
        final_equity=float(equity.iloc[-1]),observations=len(r),
        fees=result.summary['fees'],impact_cost=result.summary['impact_cost'])


def plot(results, output):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    from matplotlib.ticker import PercentFormatter
    plt.rcParams.update({'font.family':'Microsoft YaHei','font.size':11,'axes.spines.top':False,
        'axes.spines.right':False,'axes.spines.left':False,'axes.edgecolor':'#dce3de',
        'svg.fonttype':'none','figure.facecolor':'white','axes.facecolor':'white'})
    colors = {'XGBoost':'#24553d','等权基金池':'#a3825f','沪深300联接':'#8398aa'}
    fig = plt.figure(figsize=(13,8.8),layout='constrained')
    grid = fig.add_gridspec(3,1,height_ratios=[.32,2,1])
    title = fig.add_subplot(grid[0]); title.axis('off')
    title.text(0,1,'常世量化  /  Tokoyo SDK',fontsize=12,color='#5f6e64',va='top')
    title.text(0,.2,'XGBoost 多因子价值选基',fontsize=23,color='#20392b',weight='medium')
    ax = fig.add_subplot(grid[1]); dd = fig.add_subplot(grid[2],sharex=ax)
    for name, result in results.items():
        curve = result.equity_curve.set_index('date').equity / 100000
        peak = np.maximum.accumulate(np.r_[1.,curve.to_numpy()])[1:]
        ax.plot(curve.index,curve,color=colors[name],lw=2.1 if name=='XGBoost' else 1.3,label=name)
        d = curve.to_numpy()/peak-1
        dd.plot(curve.index,d,color=colors[name],lw=1.3)
        if name == 'XGBoost':
            dd.fill_between(curve.index,d,0,color=colors[name],alpha=.09)
    ax.set_ylabel('累计净值'); dd.set_ylabel('回撤'); dd.yaxis.set_major_formatter(PercentFormatter(1))
    ax.legend(loc='upper left',frameon=False,ncol=3)
    for axis in (ax,dd):
        axis.grid(axis='y',color='#e7ece8',lw=.7); axis.set_axisbelow(True)
        axis.tick_params(axis='both',length=0,pad=9)
    dd.xaxis.set_major_locator(mdates.YearLocator()); dd.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    dd.set_xlabel('2021.01—2025.12  |  月度选基，事件驱动执行，含费用与冲击，rf = 0',labelpad=16,color='#5f6e64')
    ax.tick_params(labelbottom=False)
    for ext in ('png','svg'):
        fig.savefig(output/f'performance.{ext}',dpi=180,bbox_inches='tight')
    plt.close(fig)
    annual = {}
    for name,result in results.items():
        e = result.equity_curve.set_index('date').equity.resample('YE').last()
        r = e.pct_change(); r.iloc[0] = e.iloc[0]/100000-1; annual[name] = r
    table = pd.DataFrame(annual); table.index = table.index.year
    table.to_csv(output/'annual-returns.csv')
    fig,ax=plt.subplots(figsize=(13,4.4),layout='constrained')
    table.plot.bar(ax=ax,color=[colors[n] for n in table],width=.68,rot=0)
    ax.axhline(0,color='#9ca99f',lw=.8); ax.yaxis.set_major_formatter(PercentFormatter(1))
    ax.set_title('每年赚了多少',loc='left',fontsize=18,pad=20,color='#20392b')
    ax.set_xlabel(''); ax.set_ylabel('年度收益');ax.legend(frameon=False,ncol=3)
    ax.grid(axis='y',color='#e7ece8',lw=.7);ax.set_axisbelow(True)
    for ext in ('png','svg'):
        fig.savefig(output/f'annual.{ext}',dpi=180,bbox_inches='tight')
    plt.close(fig)


def main():
    parser=ArgumentParser(description=__doc__)
    parser.add_argument('--data',type=Path,default=Path('xgb-data'))
    parser.add_argument('--output',type=Path,default=Path('xgb-result'))
    parser.add_argument('--offline',action='store_true')
    args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
    history,valuations=load_data(args.data,args.offline)
    aligned,prices,panel=make_samples(history,valuations)
    panel.to_csv(args.output/'samples.csv',index=False)
    plans=build_plans(panel,prices,args.output)
    config=BacktestConfig(subscription_fee=.001,redemption_fee=.001,
        fund_rules={s:FundRules(buy_valuation_lag=1,sell_valuation_lag=1,
            buy_confirmation_lag=2 if UNIVERSE[s][1].startswith(('overseas','commodity','gold-global')) else 1,
            sell_confirmation_lag=2 if UNIVERSE[s][1].startswith(('overseas','commodity','gold-global')) else 1,
            buy_share_lag=1,sell_settlement_lag=5 if UNIVERSE[s][1].startswith(('overseas','commodity','gold-global')) else 3,
            short_hold_days=7,short_hold_fee=.015) for s in UNIVERSE})
    baseline={m:{s:1./len(UNIVERSE) for s in UNIVERSE} for m in plans}
    benchmark={m:{'110020':1.} for m in plans}
    results={}
    for name,monthly in [('XGBoost',plans),('等权基金池',baseline),('沪深300联接',benchmark)]:
        print(f'Backtesting {name}',flush=True)
        results[name]=run_backtest(Strategy(tuple(UNIVERSE),MonthlyPlan(monthly),period='day',warmup_days=120),
            100000,'2021-01-01','2025-12-31',history=aligned,config=config)
    summary={name:metrics(result) for name,result in results.items()}
    (args.output/'metrics.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf-8')
    for name,result in results.items():
        key={'XGBoost':'xgboost','等权基金池':'equal-weight','沪深300联接':'benchmark'}[name]
        for field in ('equity_curve','trades','events','cash_ledger','position_ledger'):
            getattr(result,field).to_csv(args.output/f'{key}-{field}.csv',index=False)
    plot(results,args.output)
    manifest={'period':['2021-01-01','2025-12-31'],'training':'rolling 5 years; labels matured before features',
        'parameter_selection':'Selected after comparison over the 2021-2025 research interval',
        'score_weights':{'cheap_756_rank':.81,'earnings_yield_rank':.09,'xgboost_prediction_rank':.10},
        'top_n':2,'rank_buffer':8,'rebalance_frequency':'monthly',
        'feature_count':len(FEATURES),'fund_count':len(UNIVERSE),'months':len(plans),'seed':42,
        'boost_rounds':120,'parameters':PARAMS,'rf':0,'universe':UNIVERSE,
        'source_scope':'Fixed present-day fund list; historical NAV returns; historical index PE proxy',
        'publication_lag_observations':3,'data_sha256':{p.name:sha256(p.read_bytes()).hexdigest()
            for p in sorted(args.data.glob('*.csv'))
            if p.name in ({f'nav-{s}.csv' for s in UNIVERSE} |
                          {f'valuation-{proxy}.csv' for _,proxy in UNIVERSE.values() if proxy.isdigit()})},
        'versions':{p:version(p) for p in ('tokoyo-sdk','xgboost','pandas','numpy','matplotlib')}}
    (args.output/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8')
    print(json.dumps(summary,ensure_ascii=False,indent=2),flush=True)


if __name__=='__main__':
    main()
