"""融資維持率擇時 0050：大盤融資維持率 10 日均線跌破 1.42 或向上穿越 60 日均線時買進，
漲破 1.84 或跌破 60 日均線時賣出。

與 https://finlab.finance/blog/margin-maintenance-ratio-0050-timing 同一份程式。
個股融資餘額從 2009 年起，回測從 2009 年 1 月到最新資料。

執行前先安裝 finlab，需要資料時 finlab 會自動引導登入：

    pip install finlab
    python strategy.py
"""
import pandas as pd
from finlab import data
from finlab.backtest import sim

BASE_RATIO = 1.67   # 融資成數 6 成時的初始維持率（1 ÷ 0.6）
ENTRY = 0.85        # 短均線跌破 1.67 × 0.85 ≈ 1.42 買進
EXIT = 1.10         # 短均線漲破 1.67 × 1.10 ≈ 1.84 賣出
SHORT = 10          # 短均線天數
LONG = 60           # 長均線天數

margin_total = data.get("margin_balance:融資券總餘額")
margin_shares = data.get("margin_transactions:融資今日餘額")
close = data.get("price:收盤價")

# 1. 大盤融資維持率 = 融資股票的市值 ÷ 融資金額
#    融資今日餘額的單位是張，乘上收盤價與 1000 股就是市值；分母是上市加上櫃的融資餘額（元）
loan = margin_total["上市融資交易金額"] + margin_total["上櫃融資交易金額"]
market_value = (margin_shares * close.reindex_like(margin_shares) * 1000).sum(axis=1, min_count=1)
ratio = (market_value / loan.reindex(market_value.index)).dropna()
ratio_ma = ratio.rolling(SHORT).mean()
ratio_long = ratio.rolling(LONG).mean()
above = (ratio_ma > ratio_long)[ratio_long.notna()]
cross_up = above & ~above.shift(1, fill_value=True)
cross_down = ~above & above.shift(1, fill_value=False)

# 2. 進場：短均線跌破進場線，或向上穿越長均線；出場：漲破出場線，或跌破長均線
#    同一天兩邊都成立時以進場為準，其餘時間維持前一天的狀態
buy = (ratio_ma < BASE_RATIO * ENTRY).reindex(above.index) | cross_up
sell = (ratio_ma > BASE_RATIO * EXIT).reindex(above.index) | cross_down
state = pd.Series(float("nan"), index=above.index)
state[sell] = 0.0
state[buy] = 1.0
hold = state.ffill().fillna(0).astype(bool)

# 3. 只持有 0050；融資資料當天晚上公布，sim 在隔天收盤成交，手續費與證交稅用 sim 預設
days = close.loc["2009-01-01":].index
position = pd.DataFrame({"0050": hold.reindex(days).ffill().fillna(False).astype(bool)})
report = sim(position, upload=False, name="融資維持率擇時 0050")
print(report.get_stats())
