code wiki / (root) / nx_fin_optimizer_gate.nx

nx_fin_optimizer_gate.nx source

↩ module page · 53 lines · 2438 B

1// nx_fin_optimizer_gate.nx -- GATE for the analytic mean-variance optimizer, hand-computed. Exits 0 iff all pass. 2// license_tier: ORIGINAL 3import "nx_gate.nx" 4import "nx_fin_optimizer.nx" 5 6func chk(name: *u8, got: i64, want: i64, st: *i64) -> i64 { 7 if got == want { st[0] = st[0] + 1; gw(" PASS " as *u8); gw(name); gw("\n" as *u8) } 8 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) } 9 return 0 10} 11 12func main() -> i64 { 13 let st: *i64 = sys_mmap(16) as *i64 14 st[0] = 0; st[1] = 0 15 16 // inverse-variance: vars [100,400] -> weights [8000, 2000] bps 17 let varr: *i64 = sys_mmap(8*4) as *i64 18 varr[0]=100; varr[1]=400 19 let w: *i64 = sys_mmap(8*4) as *i64 20 op_inv_var_weight(varr, 2, w) 21 chk("inv-var w0 = 8000 bps" as *u8, w[0], 8000, st) 22 chk("inv-var w1 = 2000 bps" as *u8, w[1], 2000, st) 23 24 // diagonal max-Sharpe: mu [200,100], var [100,400] -> w0~8888, w1~1111 25 let mu: *i64 = sys_mmap(8*4) as *i64 26 mu[0]=200; mu[1]=100 27 op_max_sharpe_diag(mu, varr, 2, w) 28 chk("max-Sharpe w0 = 8888 bps" as *u8, w[0], 8888, st) 29 chk("max-Sharpe w1 = 1111 bps" as *u8, w[1], 1111, st) 30 // negative expected-return asset gets 0 (long-only) 31 mu[0]=200; mu[1]=0-50 32 op_max_sharpe_diag(mu, varr, 2, w) 33 chk("neg-mu asset -> 0 weight" as *u8, w[1], 0, st) 34 35 // 2-asset min-variance: uncorrelated (cov 0) matches inv-var (8000); positive corr shifts 36 chk("minvar 2-asset cov0 -> 8000" as *u8, op_minvar_2asset(100, 400, 0), 8000, st) 37 chk("minvar 2-asset cov50 -> 8750" as *u8, op_minvar_2asset(100, 400, 50), 8750, st) 38 39 // portfolio variance: 50/50 of vars [100,400], no corr -> 125 ; with cov 50 -> 150 40 let ew: *i64 = sys_mmap(8*4) as *i64 41 ew[0]=5000; ew[1]=5000 42 let cov0: *i64 = sys_mmap(8*8) as *i64 43 cov0[0]=100; cov0[1]=0; cov0[2]=0; cov0[3]=400 44 chk("port-var 50/50 no-corr = 125" as *u8, op_port_variance(ew, cov0, 2), 125, st) 45 let cov1: *i64 = sys_mmap(8*8) as *i64 46 cov1[0]=100; cov1[1]=50; cov1[2]=50; cov1[3]=400 47 chk("port-var 50/50 +corr = 150" as *u8, op_port_variance(ew, cov1, 2), 150, st) 48 49 gw("nx_fin_optimizer_gate: PASS=" as *u8); gn(st[0]); gw(" FAIL=" as *u8); gn(st[1]); gw("\n" as *u8) 50 if st[1] == 0 { gw("nx_fin_optimizer: GREEN (analytic mean-variance)\n" as *u8); return 0 } 51 gw("nx_fin_optimizer: RED\n" as *u8) 52 return 1 53}