#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Resolve MACD convention vs 11/04 report + recheck 20d high."""
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
df['dif'],df['dea']=macd(df['close'])
df['hist_x1']=df['dif']-df['dea']; df['hist_x2']=(df['dif']-df['dea'])*2
for i in range(len(df)-4,len(df)):
    r=df.iloc[i]
    print(f"{r['date'].date()} close={r['close']:.0f} DIF={r['dif']:.2f} DEA={r['dea']:.2f} Hx1={r['hist_x1']:.2f} Hx2={r['hist_x2']:.2f}")
print("\n11/04 report claimed: DIF −97.24 DEA −81.53 Hist −15.71 (prev −17.60)")
print("=> 11/04 row Hx1 should equal −15.71 ->", f"{df[df['date']==pd.Timestamp('2026-11-04')]['hist_x1'].iloc[0]:.2f}")
print("   Hx2 =", f"{df[df['date']==pd.Timestamp('2026-11-04')]['hist_x2'].iloc[0]:.2f}")
print("   prev(11/03) Hx1 =", f"{df[df['date']==pd.Timestamp('2026-11-03')]['hist_x1'].iloc[0]:.2f}", "(report said −17.60)")

print("\n=== 20d intraday high/low (split-adjusted) ===")
t20=df.tail(20)
print("20d high =", t20['high'].max(), " on", t20.loc[t20['high'].idxmax(),'date'].date())
print("20d low  =", t20['low'].min(), " on", t20.loc[t20['low'].idxmin(),'date'].date())
print("last 21 rows high/low:")
print(df.tail(21)[['date','high','low','close']].to_string(index=False))
