"""CatBoost 技術面＋籌碼面 AI 選股：照 /blog/ai-stock-selection-technical-chip-catboost 的文字條件重寫。

原文（2022-02）只有截圖，沒有附程式。這支程式照文中寫的做法重寫，差異列在文章「三項穩健性驗證」一節：
- 標的池：2013-01-05 以前就有價格資料的上市櫃股票與 ETF。原文另外扣掉「價格有缺失值」的標的，
  那一步要看到之後才知道的停牌與下市，這裡不做；當週沒有價格的標的不納入當週。
- 技術面特徵：TA-Lib 預設參數的重疊研究、動能、量能、波動、週期、K 線型態、統計、價格轉換與數學運算指標，
  加上一日對數報酬與 20 日年化波動，用還原開高低收計算，每週取最後一個交易日。
- 籌碼面特徵：個股外資、外資自營商、投信、自營商（自行買賣、避險）買賣超的全市場百分位排名，
  以及上市櫃三大法人買賣超（全市場合計）在各欄之間的排名。缺值一律補 0。
- 標籤：下一週報酬在全部標的中的百分位排名（0～1）。
- 模型：CatBoostRegressor 1000 回合，2014–2019 訓練、2020 驗證（取驗證集 RMSE 最低的回合），只訓練一次。
  驗證集最後一週的標籤會用到 2021 年第一週的報酬，所以拿掉，訓練與回測期不重疊。
- 交易：2021 年起每週買模型分數最高的 TOP_N 檔、等權，持有一週；sim() 預設手續費 0.1425% 與證交稅 0.3%。

統計口徑：日夏普 = 日報酬平均 / 標準差 × √252，不扣無風險利率；
0050 含息 = etl:adj_close 還原價買進持有，與策略同一段期間。

    pip install finlab catboost ta-lib
    python strategy.py

執行後在目前目錄輸出 predictions.csv（2021 年起每週的模型分數）。訓練在一般筆電約需 10～20 分鐘。
finlab 需要資料時會自動引導登入，不需要在程式裡填 token。
"""

import numpy as np
import pandas as pd
import talib
from catboost import CatBoostRegressor
from talib import abstract

import finlab
from finlab import data
from finlab.backtest import sim

LISTED_BY = "2013-01-04"
FEATURE_START = "2012-01-01"
TRAIN = ("2014-01-01", "2019-12-31")
VALID = ("2020-01-01", "2020-12-31")
TEST_START = "2021-01-01"
TOP_N = 4

CHIP_TABLES = [
    "外陸資買賣超股數(不含外資自營商)",
    "外資自營商買賣超股數",
    "投信買賣超股數",
    "自營商買賣超股數(自行買賣)",
    "自營商買賣超股數(避險)",
]
TA_FUNCS = [
    f
    for group, funcs in talib.get_function_groups().items()
    if group != "Math Transform"  # 對股價取三角函數之類的轉換不算技術指標
    for f in funcs
    if f != "MAVP"  # 需要另外給每天的週期
]


def technical_features(o, h, l, c, v):
    """單一標的的技術面特徵（日頻），只用有成交的日子計算。"""
    prices = pd.DataFrame({"open": o, "high": h, "low": l, "close": c, "volume": v}).dropna()
    inputs = {k: prices[k].to_numpy(float) for k in prices}
    cols = {}
    for name in TA_FUNCS:
        fn = abstract.Function(name)
        out = fn(inputs)
        if isinstance(out, list):
            for oname, arr in zip(fn.output_names, out):
                cols[f"{name}_{oname}"] = arr
        else:
            cols[name] = out
    logret = np.log(prices["close"]).diff()
    cols["log_return"] = logret.to_numpy()
    cols["volatility_20d"] = (logret.rolling(20).std() * np.sqrt(252)).to_numpy()
    return pd.DataFrame(cols, index=prices.index, dtype="float32")


def curve_stats(curve: pd.Series) -> dict:
    curve = curve / curve.iloc[0]
    daily = curve.pct_change().dropna()
    years = (curve.index[-1] - curve.index[0]).days / 365.25
    return {
        "cagr": curve.iloc[-1] ** (1 / years) - 1,
        "daily_sharpe": daily.mean() / daily.std() * 252 ** 0.5,
        "max_drawdown": (curve / curve.cummax() - 1).min(),
    }


def main() -> None:
    finlab.login()

    adj_close = data.get("etl:adj_close")
    o = data.get("etl:adj_open").loc[FEATURE_START:]
    h = data.get("etl:adj_high").loc[FEATURE_START:]
    l = data.get("etl:adj_low").loc[FEATURE_START:]
    c = adj_close.loc[FEATURE_START:]
    v = data.get("price:成交股數").reindex(index=c.index)

    listed = adj_close.loc[:LISTED_BY].notna().any()
    # 2012 年就下市的幾檔沒有足夠資料算指標
    stocks = [s for s in listed[listed].index if s in v.columns and c[s].notna().sum() >= 60]

    # 每週最後一個交易日
    days = c.index
    week_end = pd.DatetimeIndex(days.to_series().groupby(days.to_period("W-FRI")).max().values)

    # 籌碼面：個股買賣超的全市場百分位排名、三大法人全市場合計在各欄之間的排名，缺值補 0
    chips = {}
    for t in CHIP_TABLES:
        df = data.get(f"institutional_investors_trading_summary:{t}")
        chips[t] = df.reindex(index=week_end, columns=stocks).rank(axis=1, pct=True).fillna(0)
    market = data.get("institutional_investors_trading_all_market_summary:買賣超")
    market = market.rank(axis=1, pct=True).reindex(days).ffill(limit=4).reindex(week_end).fillna(0)

    # 標籤：下一週報酬的百分位排名
    wclose = c[stocks].reindex(week_end)
    next_ret = wclose.shift(-1) / wclose - 1
    label = next_ret.rank(axis=1, pct=True)

    # 逐檔算技術面、取週末那天（當天沒成交就用同一週前幾天的值，缺值補 0），
    # 接上籌碼面組成 (週, 標的) 的長表；當週沒有收盤價的標的不納入
    rows = []
    for sid in stocks:
        part = technical_features(o[sid], h[sid], l[sid], c[sid], v[sid])
        part = part.reindex(days).ffill(limit=4).reindex(week_end)
        part = part.replace([np.inf, -np.inf], np.nan).fillna(0)
        for t in CHIP_TABLES:
            part[f"chip_{t}"] = chips[t][sid].values
        for col in market.columns:
            part[f"market_{col}"] = market[col].values
        part["label"] = label[sid].values
        part["close"] = wclose[sid].values
        part["stock_id"] = sid
        rows.append(part[part["close"].notna()])
    panel = pd.concat(rows).sort_index(kind="stable")
    del rows  # 逐檔的小表已經併進 panel，訓練前先釋放記憶體
    panel.index.name = "date"
    features = [col for col in panel.columns if col not in ("label", "close", "stock_id")]
    n_tech = len(features) - len(CHIP_TABLES) - len(market.columns)
    print(f"標的 {len(stocks)} 檔、特徵 {len(features)} 個（技術面 {n_tech}）、樣本 {len(panel)} 筆")

    train = panel.loc[TRAIN[0]:TRAIN[1]].dropna(subset=["label"])
    valid = panel.loc[VALID[0]:VALID[1]].dropna(subset=["label"])
    valid = valid[valid.index < valid.index.max()]  # 最後一週的標籤落在 2021 年，拿掉
    test = panel.loc[TEST_START:]

    model = CatBoostRegressor(iterations=1000, random_seed=0, verbose=100, allow_writing_files=False)
    model.fit(train[features], train["label"], eval_set=(valid[features], valid["label"]),
              use_best_model=True)
    print(f"驗證集 RMSE 最低在第 {model.get_best_iteration() + 1} 回合")

    pred = pd.Series(model.predict(test[features]), index=[test.index, test["stock_id"]])
    score = pred.unstack()
    score.round(6).to_csv("predictions.csv")

    top = score.rank(axis=1, ascending=False, method="first") <= TOP_N
    position = top.astype(float).div(top.sum(axis=1), axis=0)
    report = sim(position, upload=False, name=f"CatBoost 前 {TOP_N} 名")

    creturn = report.creturn.dropna()
    creturn = creturn.loc[position.index[0]:]
    bench = adj_close["0050"].dropna().loc[creturn.index[0]:creturn.index[-1]]
    print(f"期間 {creturn.index[0].date()} 至 {creturn.index[-1].date()}")
    for name, curve in (("策略", creturn), ("0050 含息", bench)):
        s = curve_stats(curve)
        print(f"{name}：年化 {s['cagr']:.2%}，日夏普 {s['daily_sharpe']:.2f}，最大回撤 {s['max_drawdown']:.2%}")


if __name__ == "__main__":
    main()
