#!/usr/bin/env python3
"""Check: does the Yahoo volume=0 phantom bar (2026-10-23) inflate RSI?
Compare RSI with vs without the phantom bar, on the 10/29 and 10/30 data points."""
import numpy as np
import pandas as pd
import yfinance as yf

h = yf.Ticker("6669.TW").history(period="6mo", auto_adjust=False)
c_all = h["Close"].dropna()

def rsi(series, n=14):
    d = series.diff()
    up = d.clip(lower=0); dn = -d.clip(upper=0)
    rs = (up.rolling(n).mean() / dn.rolling(n).mean()).replace([np.inf, -np.inf], np.nan).fillna(50)
    return 100 - 100 / (1 + rs)

r_all = rsi(c_all)
# drop phantom: volume == 0 rows
mask = h["Volume"].fillna(0) > 0
c_clean = h.loc[mask, "Close"].dropna()
r_clean = rsi(c_clean)

print("=== RSI WITH phantom bar (Yahoo default) ===")
print(r_all.tail(6).round(3).to_string())
print("\n=== RSI WITHOUT phantom bar (volume>0 filter) ===")
print(r_clean.tail(6).round(3).to_string())
print("\n=== compare on 10/29 and 10/30 ===")
for d in ["2026-10-29", "2026-10-30"]:
    da = r_all.get(pd.Timestamp(d, tz=h.index.tz))
    dc = r_clean.get(pd.Timestamp(d, tz=h.index.tz))
    print(f"{d}: with_phantom={da if da is None else round(da,3)}  clean={dc if dc is None else round(dc,3)}")
