#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Verify every number cited in the 2026-11-05 report."""
import json, os
import pandas as pd, numpy as np
D=os.path.dirname(os.path.abspath(__file__))
def jload(p):
    with open(p,encoding='utf-8') as f: return json.load(f)
rows=[]
for m in ['20260701','20260801','20260901','20261001','20261101']:
    d=jload(os.path.join(D,f"6669_{m}.json"))
    if d.get('stat')!='OK': continue
    for r in d['data']:
        y,mo,dd=str(r[0]).strip().split('/')
        rows.append(dict(date=pd.Timestamp(int(y)+1911,int(mo),int(dd)),
            volume=float(str(r[1]).replace(',','')), open_=float(str(r[3]).replace(',','')),
            high=float(str(r[4]).replace(',','')), low=float(str(r[5]).replace(',','')),
            close=float(str(r[6]).replace(',',''))))
df=pd.DataFrame(rows).drop_duplicates(subset=['date']).sort_values('date').reset_index(drop=True)
df['adj']=df['date']<pd.Timestamp('2026-09-02')
for c in ('open_','high','low','close'): df.loc[df['adj'],c]/=3.0

def macd(c):
    dif=c.ewm(span=12,adjust=False).mean()-c.ewm(span=26,adjust=False).mean()
    dea=dif.ewm(span=9,adjust=False).mean(); return dif,dea,(dif-dea)*2
def kdj(h,l,c,smooth):
    ll=l.rolling(9).min(); hh=h.rolling(9).max()
    rsv=((c-ll)/(hh-ll).replace(0,np.nan))*100; rsv=rsv.fillna(50)
    if smooth=='ema':
        k=rsv.ewm(com=2,adjust=False).mean(); d=k.ewm(com=2,adjust=False).mean()
    else:
        k=rsv.rolling(3).mean(); d=k.rolling(3).mean()
    return k,d,3*k-2*d
def rsi(c,n=14,mode='wilder'):
    d=c.diff(); up=d.clip(lower=0); dn=-d.clip(upper=0)
    if mode=='wilder':
        au=up.ewm(alpha=1/n,adjust=False,min_periods=n).mean(); ad=dn.ewm(alpha=1/n,adjust=False,min_periods=n).mean()
    else:
        au=up.rolling(n).mean(); ad=dn.rolling(n).mean()
    v=100-100/(1+(au/ad.replace(0,np.nan)))
    return v.replace([np.inf,-np.inf],np.nan).fillna(50)

df['ma20']=df['close'].rolling(20).mean(); df['ma60']=df['close'].rolling(60).mean()
df['rw']=rsi(df['close']); df['rs']=rsi(df['close'],mode='sma')
df['dif'],df['dea'],df['hist']=macd(df['close'])
df['ke'],df['de'],df['je']=kdj(df['high'],df['low'],df['close'],'ema')
df['ks'],df['ds'],df['js']=kdj(df['high'],df['low'],df['close'],'sma')
r=df.iloc[-1]; p=df.iloc[-2]
v20=df['volume'].tail(20).mean()
print("=== 6669 11/05 ===")
print(f"close={r['close']:.2f} chg={r['close']-p['close']:.2f} ({(r['close']/p['close']-1)*100:.2f}%)")
print(f"O={r['open_']:.0f} H={r['high']:.0f} L={r['low']:.0f}")
print(f"MA20={r['ma20']:.2f} MA60={r['ma60']:.2f}")
print(f"RSI Wilder={r['rw']:.2f}  SMA={r['rs']:.2f}")
print(f"MACD DIF={r['dif']:.2f} DEA={r['dea']:.2f} Hist={r['hist']:.2f} (prev {p['hist']:.2f})")
print(f"KDJ EMA K={r['ke']:.2f} D={r['de']:.2f} J={r['je']:.2f}   gap={r['ke']-r['de']:.2f}")
print(f"KDJ SMA K={r['ks']:.2f} D={r['ds']:.2f} J={r['js']:.2f}")
print(f"vol={r['volume']:,.0f} v20={v20:,.0f} ratio={r['volume']/v20:.3f}x")
print(f"20d low(intraday)={df['low'].tail(20).min():.0f}  20d high={df['high'].tail(20).max():.0f}")
print(f"prev hist was {p['hist']:.2f}; MACD hist change {r['hist']-p['hist']:+.2f}")
print(f"cross checks: ema K>D={r['ke']>r['de']} fresh={r['ke']>r['de'] and p['ke']<=p['de']}")
print(f"  yesterday EMA K={p['ke']:.2f} D={p['de']:.2f} gap={p['ke']-p['de']:.2f}")

# 00412A
erows=[]
for m in ['20261001','20261101']:
    d=jload(os.path.join(D,f"00412A_{m}.json"))
    for rr in d['data']:
        y,mo,dd=str(rr[0]).strip().split('/')
        erows.append(dict(date=pd.Timestamp(int(y)+1911,int(mo),int(dd)),
            volume=float(str(rr[1]).replace(',','')), open_=float(str(rr[3]).replace(',','')),
            high=float(str(rr[4]).replace(',','')), low=float(str(rr[5]).replace(',','')),
            close=float(str(rr[6]).replace(',',''))))
e=pd.DataFrame(erows).drop_duplicates(subset=['date']).sort_values('date').reset_index(drop=True)
er=e.iloc[-1]; ep=e.iloc[-2]
print("\n=== 00412A 11/05 ===")
print(f"close={er['close']:.2f} chg={er['close']-ep['close']:.2f} ({(er['close']/ep['close']-1)*100:.2f}%) O={er['open_']} H={er['high']} L={er['low']}")
print(f"n_days={len(e)} first={e['date'].iloc[0].date()} last={e['date'].iloc[-1].date()}")
print(f"high={e['high'].max():.2f} low={e['low'].min():.2f} from_high={(er['close']-e['high'].max())/e['high'].max()*100:.2f}%")
print(f"vol={er['volume']:,.0f} v10={e['volume'].tail(10).mean():,.0f} ratio={er['volume']/e['volume'].tail(10).mean():.3f}x")
print(f"stop 8.00 breached: {er['close'] < 8.00}  (diff {(er['close']-8.0)/8.0*100:+.2f}%)")
print(f"hold zone 8.50-12.0: close {er['close']} below 8.50 -> {er['close'] < 8.50}")
print(f"tp1 12.0 distance {(12.0-er['close'])/er['close']*100:+.1f}%")

# T86 cumulative 00412A
t86=json.load(open(os.path.join(D,'t86_20261105.json'),encoding='utf-8'))
print("\n=== T86 6669 11/05 ===")
for r2 in t86['data']:
    if r2[0].strip()=='6669':
        print(f"foreign={r2[4]} trust={r2[10]} dealer={r2[11]} total={r2[18]}")
    if r2[0].strip()=='00412A':
        print(f"00412A foreign={r2[4]} trust={r2[10]} dealer={r2[11]} total={r2[18]}")
print("cum 00412A 4d = -8,979,789 + -14,035,098 + -15,665,290 + -12,887,234 =",
      -8979789-14035098-15665290-12887234)
