The bundle includes the standard-library Python engine, validation checks, configuration, all 18,000 terminal P&Ls, example path ledgers, stress-grid results and this report. No API key or paid data subscription is needed to reproduce it.
Read the complete Python implementation
"""Edge Quant: European straddle and discrete delta hedge research lab.
MODEL SIMULATION ONLY. No historical options quotes or calibrated forecasts.
Python standard library. Run: python simulation.py --out results --paths 1500
USD. Synthetic non-dividend-paying underlying; European cash-settled options.
Black-Scholes marks use flat 20% IV; realized path volatility is scenario input.
"""
import argparse,csv,json,math,random,statistics
from pathlib import Path
CONFIG={'spot':100.,'strike':100.,'days':45,'steps_per_year':252,'iv':.20,'rate':.03,'borrow_spread':.02,'stock_borrow':.02,'contracts_per_leg':10,'multiplier':100,'initial_cash':100000.,'option_commission':.65,'option_half_spread':.02,'hedge_bps':2.,'seed':1729}
SCENARIOS=[{'id':'quiet','name':'Quiet market','realized_vol':.12,'jump':0.}, {'id':'matched','name':'Volatility matches pricing','realized_vol':.20,'jump':0.}, {'id':'active','name':'High realized volatility','realized_vol':.32,'jump':0.}, {'id':'gap','name':'Downward gap stress','realized_vol':.20,'jump':-.15}]
def normal(x):return .5*(1+math.erf(x/math.sqrt(2)))
def bs(s,k,t,r,v):
if t<=0:
call=max(s-k,0.);put=max(k-s,0.);dc=1. if s>k else (0. if s<k else .5)
return {'call':call,'put':put,'delta':2*dc-1,'gamma':0.,'vega_pp':0.,'theta_day':0.}
root=math.sqrt(t);d1=(math.log(s/k)+(r+.5*v*v)*t)/(v*root);d2=d1-v*root;disc=math.exp(-r*t);pdf=math.exp(-.5*d1*d1)/math.sqrt(2*math.pi)
call=s*normal(d1)-k*disc*normal(d2);put=k*disc*normal(-d2)-s*normal(-d1)
theta=-s*pdf*v/root-r*k*disc*normal(d2)+r*k*disc*normal(-d2)
return {'call':call,'put':put,'delta':2*normal(d1)-1,'gamma':2*pdf/(s*v*root),'vega_pp':2*s*pdf*root*.01,'theta_day':theta/252}
def portfolio(s,t,iv,c=CONFIG):
g=bs(s,c['strike'],t,c['rate'],iv);units=c['contracts_per_leg']*c['multiplier']
return {'value':(g['call']+g['put'])*units,**{k:g[k]*units for k in ['delta','gamma','vega_pp','theta_day']}}
def path_from(shocks,scenario,c=CONFIG):
dt=1/c['steps_per_year'];s=c['spot'];path=[s];v=scenario['realized_vol']
for i,z in enumerate(shocks,1):
# Fixed illustrative drift 3%, equal to the cash rate; not a forecast.
s*=math.exp((c['rate']-.5*v*v)*dt+v*math.sqrt(dt)*z)
if scenario['jump'] and i==20:s*=1+scenario['jump']
path.append(s)
return path
def simulate(path,cadence,c=CONFIG,keep=False):
dt=1/c['steps_per_year'];units=c['contracts_per_leg']*c['multiplier'];start=portfolio(path[0],c['days']*dt,c['iv'],c)
premium=start['value'];option_cost=2*c['contracts_per_leg']*c['option_commission']+2*units*c['option_half_spread']
cash=c['initial_cash']-premium-option_cost;shares=0.;hedge_cost=0.;borrow=0.;interest=0.;orders=0;rows=[]
for i,s in enumerate(path):
if i:
rate=c['rate'] if cash>=0 else c['rate']+c['borrow_spread'];accrual=cash*math.expm1(rate*dt);cash+=accrual;interest+=accrual
fee=max(-shares,0)*path[i-1]*c['stock_borrow']*dt;cash-=fee;borrow+=fee
t=(c['days']-i)*dt;g=portfolio(s,t,c['iv'],c)
if i==c['days']:
cash+=g['value'];opt_value=0.;target=0.
else:
opt_value=g['value'];target=-g['delta'] if cadence and i%cadence==0 else shares
traded=target-shares
fee=abs(traded)*s*c['hedge_bps']/10000
if abs(traded)>1e-10:orders+=1
cash-=traded*s+fee;hedge_cost+=fee;shares=target
equity=cash+shares*s+opt_value
benchmark=c['initial_cash']*math.exp(c['rate']*i*dt)
if keep:rows.append({'day':i,'spot':s,'option_value':opt_value,'hedge_shares':shares,'net_delta':shares+g['delta'] if t>0 else 0.,'cash':cash,'equity':equity,'excess_pnl':equity-benchmark,'option_pnl':g['value']-premium,'hedge_cost':hedge_cost,'stock_borrow_cost':borrow,'cash_interest':interest})
return {'pnl':equity-c['initial_cash']*math.exp(c['rate']*c['days']*dt),'equity':equity,'hedge_cost':hedge_cost,'stock_borrow_cost':borrow,'option_cost':option_cost,'orders':orders,'rows':rows}
def quantile(xs,p):
a=sorted(xs);at=(len(a)-1)*p;lo=int(at);hi=min(lo+1,len(a)-1);return a[lo]+(a[hi]-a[lo])*(at-lo)
def stats(values):
n=len(values);mean=statistics.mean(values);se=statistics.stdev(values)/math.sqrt(n);bottom=sorted(values)[:max(1,math.ceil(n*.05))]
return {'mean':mean,'median':statistics.median(values),'q05':quantile(values,.05),'q95':quantile(values,.95),'tail_mean_05':statistics.mean(bottom),'profit_fraction':sum(x>0 for x in values)/n,'mean_ci95':[mean-1.96*se,mean+1.96*se],'min':min(values),'max':max(values)}
def write_csv(path,rows):
with path.open('w',newline='') as f:
w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
def run(out,n=1500):
out=Path(out);out.mkdir(parents=True,exist_ok=True);rng=random.Random(CONFIG['seed']);shocks=[[rng.gauss(0,1) for _ in range(CONFIG['days'])] for _ in range(n)]
result={'config':CONFIG,'paths_per_case':n,'scenarios':SCENARIOS,'initial_greeks':portfolio(100,45/252,.20),'cases':{}}
all_pnl=[]
for scenario in SCENARIOS:
paths=[path_from(z,scenario) for z in shocks]
for name,cadence in [('daily',1),('weekly',5),('unhedged',0)]:
runs=[simulate(path,cadence) for path in paths];values=[x['pnl'] for x in runs];key=scenario['id']+'_'+name
example=simulate(paths[0],cadence,keep=True);write_csv(out/(key+'_path.csv'),example['rows'])
result['cases'][key]={'summary':stats(values),'mean_hedge_cost':statistics.mean(x['hedge_cost'] for x in runs),'mean_stock_borrow_cost':statistics.mean(x['stock_borrow_cost'] for x in runs),'mean_orders':statistics.mean(x['orders'] for x in runs),'values':values,'example_path':example['rows']}
all_pnl.extend({'scenario':scenario['id'],'hedge':name,'path_index':i,'excess_pnl_usd':x['pnl'],'hedge_cost_usd':x['hedge_cost'],'borrow_cost_usd':x['stock_borrow_cost'],'equity_usd':x['equity']} for i,x in enumerate(runs))
write_csv(out/'all_paths_pnl.csv',all_pnl)
g0=result['initial_greeks'];initial_hedge=-g0['delta'];stress=[]
for shift in [-.10,0.,.10,.20]:
for spot_move in [-.20,-.10,0.,.10,.20]:
g=portfolio(100*(1+spot_move),30/252,.20+shift)
stress.append({'spot_move':spot_move,'iv_shift':shift,'iv':.20+shift,'elapsed_days':15,'option_plus_initial_hedge_mtm':g['value']-g0['value']+initial_hedge*100*spot_move})
result['stress']=stress
(out/'summary.json').write_text(json.dumps(result,separators=(',',':')))
(out/'config.json').write_text(json.dumps(CONFIG,indent=2));write_csv(out/'stress_grid.csv',stress)
return result
if __name__=='__main__':
a=argparse.ArgumentParser();a.add_argument('--out',default='results');a.add_argument('--paths',type=int,default=1500);args=a.parse_args()
if args.paths<2:a.error('--paths must be at least 2')
r=run(args.out,args.paths)
print(json.dumps({k:{'mean':round(v['summary']['mean'],2),'p05':round(v['summary']['q05'],2),'profit_pct':round(v['summary']['profit_fraction']*100,2)} for k,v in r['cases'].items()},indent=2))