nx_fin_bs_gate.nx source
↩ module page · 52 lines · 2736 B
1// nx_fin_bs_gate.nx -- GATE for the fixed-point Black-Scholes suite. Approximations, so checked within a
2// tolerance against KNOWN values: exp/ln/normal-CDF spot values, the classic BS call (100,100,5%,20%,1y)=10.45,
3// and put-call parity (C - P == S - K e^{-rT}). Exits 0 iff all pass. license_tier: ORIGINAL
4import "nx_gate.nx"
5import "nx_fin_metrics.nx"
6import "nx_fin_bs.nx"
7
8func chk_near(name: *u8, got: i64, want: i64, tol: i64, st: *i64) -> i64 {
9 var d: i64 = got - want; if d < 0 { d = 0 - d }
10 if d <= tol { st[0] = st[0] + 1; gw(" PASS " as *u8); gw(name); gw(" (" as *u8); gn(got); gw(")\n" as *u8) }
11 else { st[1] = st[1] + 1; gw(" FAIL " as *u8); gw(name); gw(" got=" as *u8); gn(got); gw(" want~" as *u8); gn(want); gw("\n" as *u8) }
12 return 0
13}
14
15func main() -> i64 {
16 let st: *i64 = sys_mmap(16) as *i64
17 st[0] = 0; st[1] = 0
18
19 // exp
20 chk_near("exp(0) = 1.0" as *u8, exp_fp(0), 1000000, 100, st)
21 chk_near("exp(1) = 2.71828" as *u8, exp_fp(1000000), 2718282, 300, st)
22 chk_near("exp(-0.5) = 0.60653" as *u8, exp_fp(0 - 500000), 606531, 300, st)
23 // ln
24 chk_near("ln(1) = 0" as *u8, ln_fp(1000000), 0, 50, st)
25 chk_near("ln(e) = 1.0" as *u8, ln_fp(2718282), 1000000, 300, st)
26 chk_near("ln(2) = 0.69315" as *u8, ln_fp(2000000), 693147, 300, st)
27 // sqrt
28 chk_near("sqrt(0.25) = 0.5" as *u8, bs_sqrt_fp(250000), 500000, 100, st)
29 // normal CDF
30 chk_near("N(0) = 0.5" as *u8, bs_ncdf(0), 500000, 1500, st)
31 chk_near("N(1) = 0.84134" as *u8, bs_ncdf(1000000), 841345, 2000, st)
32 chk_near("N(-1) = 0.15866" as *u8, bs_ncdf(0 - 1000000), 158655, 2000, st)
33 chk_near("N(1.96) = 0.97500" as *u8, bs_ncdf(1960000), 975002, 2500, st)
34
35 // Black-Scholes: S=K=$100, r=5%, sigma=20%, T=1y -> call ~ $10.4506, put ~ $5.5735
36 let S: i64 = 100000000; let K: i64 = 100000000
37 let r: i64 = 50000; let sig: i64 = 200000; let T: i64 = 1000000
38 chk_near("BS call = $10.45" as *u8, bs_call(S, K, r, sig, T), 10450600, 40000, st)
39 chk_near("BS put = $5.57" as *u8, bs_put(S, K, r, sig, T), 5573500, 40000, st)
40 chk_near("call delta = N(d1) ~ 0.6368" as *u8, bs_delta_call(S, K, r, sig, T), 636800, 3000, st)
41
42 // put-call parity: C - P == S - K e^{-rT}
43 let disc: i64 = exp_fp(0 - (r * T / FP))
44 let lhs: i64 = bs_call(S, K, r, sig, T) - bs_put(S, K, r, sig, T)
45 let rhs: i64 = S - (K * disc / FP)
46 chk_near("put-call parity C-P == S-Ke^{-rT}" as *u8, lhs, rhs, 20000, st)
47
48 gw("nx_fin_bs_gate: PASS=" as *u8); gn(st[0]); gw(" FAIL=" as *u8); gn(st[1]); gw("\n" as *u8)
49 if st[1] == 0 { gw("nx_fin_bs: GREEN (fixed-point Black-Scholes verified to known values)\n" as *u8); return 0 }
50 gw("nx_fin_bs: RED\n" as *u8)
51 return 1
52}