Black-Scholes program for the HP-12C

This was a funny challenge: putting the Black-Scholes equation into HP-12C. It calculates the theoretical premium for calls and puts.

Usage

The option parameters are not changed during calculation, so you can fiddle with them and press R/S as many times as you want.

The program

Opcode #OperationRemarks
0.196854
STO 3N(x) 1st coefficient
0.115194
STO 4N(x) 2nd coefficient
0.000344
STO 5N(x) 3rd coefficient
0.019527
STO 6N(x) 4th coefficient
f P/RGoes into programming mode
f CLEAR PRGMClears programming memory
01RCL n t
02g √x √t
03RCL PMT 100.σ
04% √t.σ
05STO 2 Let mem2 = √t.σ
06RCL n t
07RCL i 100.r
08% r.t
09RCL 2 √t.σ
102
11Yxt.σ2
122
13÷ t.σ2/2
14+ (r + σ2/2).t
15RCL PV S
16RCL FV K
17÷ S/K
18g LN ln(S/K)
19+ ln(S/K) + (r + σ2/2).t
20RCL 2 √t.σ
21÷ d1
22STO 1 Let mem1 = d1
23STO 0 Let mem0 = d1
24RCL 2 √t.σ
25STO - 0 Let mem0 = d1 - √t.σ = d2
26RCL 0 swap mem0 and mem1
27RCL 1
28STO 0
29R↓
30STO 1 swap done
31RCL 0 Get d1 or d2 (whichever is at mem0) and
324 calculate cummulative normal distribution
33Yxd4
34RCL 6 c4
35x⇄y
36× c4.d4
37g LSTx d4
38g √x d2
39RCL 4 c2
40x⇄y
41× c2.d2
42g LSTx d2
43g √x d (guaranteed to be positive)
44RCL 3 c1
45× c1.d
46+ c1.d+c2.d2
47+ c1.d+c2.d2+c4.d4
48RCL 0 d
496
50Yxd6
51g √x d3 (guaranteed to be positive)
52RCL 5 c3
53× c3.d3
54+ c1.d+c2.d2+c3.d3+c4.d4
551
56+ 1+c1.d+c2.d2+c3.d3+c4.d4
574
58CHS
59Yx(1+c1.d+c2.d2+c3.d3+c4.d4)-4
602
61÷ (1+c1.d+c2.d2+c3.d3+c4.d4)-4/2
620 Current result is 1-N(abs(d))
63RCL 0
64g x≤y d < 0?
65GTO 72 d<0, N(d)=1-N(-d), we are done, jump ahead
66R↓ d>0, need to do 1-(1-(N(d))
67R↓ Restore 1-N(d) into register X
68CHS
691
70+ N(d) corrected, we are done
71GTO 74 Jump ahead
72R↓ Restore N(d) into register X
73R↓
74STO 0 Let mem0 = N(d)
75RCL 2 mem2 is √t.σ at 1st round, zero otherwise
76g x=0 mem2 is zero?
77GTO 81 Jump to calculate call and put
780
79STO 2 Let mem2 = 0
80GTO 26 Go back to 2nd round of N(d) calculation
81RCL PV S
82STO × 1 Let mem1 = S.N(d1)
83RCL n t
84RCL i r
85% r.t
86CHS -r.t
87g exe-r.t
88RCL FV K
89× K.e-rt
90STO × 0 Let mem0 = K.e-rt.N(d2)
91RCL PV S
92- K.e-rt - S
93RCL 1 S.N(d1)
94RCL 0 K.e-rt.N(d2)
95- S.N(d1) - K.e-rt.N(d2) = Call
96+ Call + K.e-rt - S = Put
97g LSTx Call at X, put at Y
f P/RBack to normal mode

Implementation remarks

It was difficult to make the equation to fit into HP-12C, since a program can have at most 99 steps, the "language" is poor, and using all 99 steps reduces the number of available memory positions, which in turn makes the program more complicated and forces usage of more opcodes.

The most complicated function is the cummulative normal distribution function, which we implement using a rational approximation with precision of 4 decimal digits. The coefficients of this function are entered as part of the program but they lie on memory positions instead of inside the program. A better, seven-coefficient function could not be used because of opcode and memory constraints.

Google