#!/usr/bin/env python3
"""Refresh index prices every 5 minutes. Called by cron or loop."""
import yfinance as yf, json, datetime

tickers = [('^GSPC','S&P 500',6591.90),('^DJI','Dow Jones',46429.49),('^IXIC','NASDAQ',None),('^RUT','Russell 2000',None),('^VIX','VIX',None)]
indices = []
for ticker, name, exit_v in tickers:
    try:
        t = yf.Ticker(ticker)
        info = t.fast_info
        price = info.last_price
        prev = info.previous_close
        chg_pct = ((price - prev) / prev * 100) if prev else 0
        vs_exit = ((price - exit_v) / exit_v * 100) if exit_v else None
        indices.append({'name':name,'ticker':ticker,'price':round(price,2),'change_pct':round(chg_pct,2),'vs_exit':round(vs_exit,2) if vs_exit is not None else None})
    except: pass

with open('/Users/joemac/.openclaw/workspace/projects/investing/margin-of-safety-engine/indices-latest.json','w') as f:
    json.dump({'generated':datetime.datetime.now().isoformat(),'indices':indices},f,indent=2)
print(f'Refreshed {len(indices)} indices at {datetime.datetime.now().strftime("%H:%M:%S")}')
