42 lines
4.0 KiB
Python
42 lines
4.0 KiB
Python
import json, math, datetime, csv, xml.etree.ElementTree as ET
|
||
from pathlib import Path
|
||
p = Path(__file__).resolve().parent
|
||
x=json.load(open(p/'yahoo-iren.json'))['chart']['result'][0]; q=x['indicators']['quote'][0]
|
||
rows=[dict(date=str(datetime.datetime.fromtimestamp(t,datetime.UTC).date()),**{k:q[k][i] for k in ('open','high','low','close','volume')}) for i,t in enumerate(x['timestamp']) if all(q[k][i] is not None for k in ('high','low','close','volume'))][-60:]
|
||
price=rows[-1]['close']; edges=list(range(16,74,2)); raw=[0.]*(len(edges)-1); recent=raw.copy()
|
||
for age,r in enumerate(reversed(rows)):
|
||
lo,hi=r['low'],r['high']; assert hi>=lo and r['volume']>=0
|
||
for j,(a,b) in enumerate(zip(edges,edges[1:])):
|
||
share=max(0,min(hi,b)-max(lo,a))/(hi-lo) if hi>lo else float(a<=lo<b)
|
||
raw[j]+=r['volume']*share
|
||
recent[j]+=r['volume']*share*2**(-age/20)
|
||
assert abs(sum(raw)-sum(r['volume'] for r in rows))<1
|
||
# This is a volume-at-price proxy, not observed intraday trades or live holdings.
|
||
with open(p/'profile.csv','w') as f:
|
||
w=csv.writer(f);w.writerow(['price_low_usd','price_high_usd','historical_volume_shares','time_decayed_volume_20_session_half_life'])
|
||
for a,b,v,d in zip(edges,edges[1:],raw,recent):w.writerow([a,b,round(v),round(d)])
|
||
with open(p/'daily.csv','w') as f:
|
||
w=csv.DictWriter(f,fieldnames=rows[0].keys());w.writeheader();w.writerows(rows)
|
||
above=sum(v*max(0,b-max(a,price))/(b-a) for a,b,v in zip(edges,edges[1:],raw))
|
||
res=[]
|
||
for target in [24,26,28,30,35,40,50,60]:
|
||
v=sum(v*max(0,min(b,target)-max(a,price))/(b-a) for a,b,v in zip(edges,edges[1:],raw))
|
||
res.append({'target':target,'cumulative_historical_volume_m':round(v/1e6,1),'share_of_above_price_volume_pct':round(v/above*100,1)})
|
||
s={'start':rows[0]['date'],'end':rows[-1]['date'],'close':round(price,2),'sessions':len(rows),'average_20d_volume_m':sum(r['volume'] for r in rows[-20:])/20/1e6,'targets':res,'top_zones':sorted([(f'{a}-{b}',round(v/1e6,1)) for a,b,v in zip(edges,edges[1:],raw) if b>price],key=lambda z:-z[1])[:5]}
|
||
json.dump(s,open(p/'summary.json','w'),indent=2)
|
||
W,H=1000,730
|
||
parts=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="IREN estimated historical volume by price, not actual holdings">','<rect width="1000" height="730" fill="#faf9f6"/>','<g font-family="Arial,sans-serif" fill="#20282f">','<text x="38" y="40" font-size="24">IREN | Where did recent trading concentrate?</text>',f'<text x="38" y="66" font-size="14">{rows[0]["date"]} to {rows[-1]["date"]} · 60 sessions · latest close ${price:.2f}</text>']
|
||
# Two independently scaled percentage distributions, same price scale.
|
||
for cx,values,title,color in [(95,raw,'Historical volume share','#557a9b'),(550,recent,'Recent-weighted share (20-session half-life)','#ac7258')]:
|
||
total=sum(values);maxpct=max(values)/total*100
|
||
parts.append(f'<text x="{cx}" y="105" font-size="16">{title}</text>')
|
||
for j,(a,b,v) in enumerate(zip(edges,edges[1:],values)):
|
||
y=125+j*17; width=v/total*100/25*310
|
||
parts.append(f'<text x="{cx-12}" y="{y+10}" text-anchor="end" font-size="11">{a}–{b}</text><rect x="{cx}" y="{y}" width="{width:.2f}" height="12" fill="{color}"/><text x="{cx+width+5:.2f}" y="{y+10}" font-size="11">{v/total*100:.1f}%</text>')
|
||
for tick in [0,5,10,15,20,25]:
|
||
xx=cx+tick/25*310
|
||
parts.append(f'<text x="{xx}" y="615" text-anchor="middle" font-size="11">{tick}%</text>')
|
||
parts+=['<text x="38" y="648" font-size="13">Price bands: USD 2. Each daily volume is distributed uniformly between that day’s low and high.</text>','<text x="38" y="673" font-size="13">Repeated turnover is counted. Percentages describe traded volume, not shareholders or selling probability.</text>','<text x="38" y="698" font-size="13">Source: Yahoo Finance daily OHLCV. Time decay is an illustrative assumption, not a holdings estimate.</text>','</g></svg>']
|
||
(p/'iren-profile.svg').write_text('\n'.join(parts));ET.parse(p/'iren-profile.svg')
|
||
print(json.dumps(s));print('Checks passed: 60 valid sessions; volume conserved; SVG parses. No build or compilation run.')
|