##// END OF EJS Templates
Improved Monte-Carlo options pricing example.
Brian Granger -
Show More
@@ -1,71 +1,148 b''
1 1 #!/usr/bin/env python
2 2 """Run a Monte-Carlo options pricer in parallel."""
3 3
4 #-----------------------------------------------------------------------------
5 # Imports
6 #-----------------------------------------------------------------------------
7
8 import sys
9 import time
4 10 from IPython.kernel import client
5 11 import numpy as np
6 12 from mcpricer import price_options
13 from matplotlib import pyplot as plt
14
15 #-----------------------------------------------------------------------------
16 # Setup parameters for the run
17 #-----------------------------------------------------------------------------
18
19 def ask_question(text, the_type, default):
20 s = '%s [%r]: ' % (text, the_type(default))
21 result = raw_input(s)
22 if result:
23 return the_type(result)
24 else:
25 return the_type(default)
26
27 cluster_profile = ask_question("Cluster profile", str, "default")
28 price = ask_question("Initial price", float, 100.0)
29 rate = ask_question("Interest rate", float, 0.05)
30 days = ask_question("Days to expiration", int, 260)
31 paths = ask_question("Number of MC paths", int, 10000)
32 n_strikes = ask_question("Number of strike values", int, 5)
33 min_strike = ask_question("Min strike price", float, 90.0)
34 max_strike = ask_question("Max strike price", float, 110.0)
35 n_sigmas = ask_question("Number of volatility values", int, 5)
36 min_sigma = ask_question("Min volatility", float, 0.1)
37 max_sigma = ask_question("Max volatility", float, 0.4)
38
39 strike_vals = np.linspace(min_strike, max_strike, n_strikes)
40 sigma_vals = np.linspace(min_sigma, max_sigma, n_sigmas)
41
42 #-----------------------------------------------------------------------------
43 # Setup for parallel calculation
44 #-----------------------------------------------------------------------------
7 45
8 46 # The MultiEngineClient is used to setup the calculation and works with all
9 47 # engine.
10 mec = client.MultiEngineClient(profile='mycluster')
48 mec = client.MultiEngineClient(profile=cluster_profile)
11 49
12 50 # The TaskClient is an interface to the engines that provides dynamic load
13 51 # balancing at the expense of not knowing which engine will execute the code.
14 tc = client.TaskClient(profile='mycluster')
52 tc = client.TaskClient(profile=cluster_profile)
15 53
16 54 # Initialize the common code on the engines. This Python module has the
17 55 # price_options function that prices the options.
18 56 mec.run('mcpricer.py')
19 57
20 # Define the function that will make up our tasks. We basically want to
21 # call the price_options function with all but two arguments (K, sigma)
22 # fixed.
23 def my_prices(K, sigma):
24 S = 100.0
25 r = 0.05
26 days = 260
27 paths = 100000
28 return price_options(S, K, sigma, r, days, paths)
29
30 # Create arrays of strike prices and volatilities
31 nK = 10
32 nsigma = 10
33 K_vals = np.linspace(90.0, 100.0, nK)
34 sigma_vals = np.linspace(0.1, 0.4, nsigma)
35
36 # Submit tasks to the TaskClient for each (K, sigma) pair as a MapTask.
37 # The MapTask simply applies a function (my_prices) to the arguments:
38 # my_prices(K, sigma) and returns the result.
58 #-----------------------------------------------------------------------------
59 # Perform parallel calculation
60 #-----------------------------------------------------------------------------
61
62 print "Running parallel calculation over strike prices and volatilities..."
63 print "Strike prices: ", strike_vals
64 print "Volatilities: ", sigma_vals
65 sys.stdout.flush()
66
67 # Submit tasks to the TaskClient for each (strike, sigma) pair as a MapTask.
68 t1 = time.time()
39 69 taskids = []
40 for K in K_vals:
70 for strike in strike_vals:
41 71 for sigma in sigma_vals:
42 t = client.MapTask(my_prices, args=(K, sigma))
72 t = client.MapTask(
73 price_options,
74 args=(price, strike, sigma, rate, days, paths)
75 )
43 76 taskids.append(tc.run(t))
44 77
45 78 print "Submitted tasks: ", len(taskids)
79 sys.stdout.flush()
46 80
47 81 # Block until all tasks are completed.
48 82 tc.barrier(taskids)
83 t2 = time.time()
84 t = t2-t1
85
86 print "Parallel calculation completed, time = %s s" % t
87 print "Collecting results..."
49 88
50 89 # Get the results using TaskClient.get_task_result.
51 90 results = [tc.get_task_result(tid) for tid in taskids]
52 91
53 92 # Assemble the result into a structured NumPy array.
54 prices = np.empty(nK*nsigma,
93 prices = np.empty(n_strikes*n_sigmas,
55 94 dtype=[('ecall',float),('eput',float),('acall',float),('aput',float)]
56 95 )
96
57 97 for i, price_tuple in enumerate(results):
58 98 prices[i] = price_tuple
59 prices.shape = (nK, nsigma)
60 K_vals, sigma_vals = np.meshgrid(K_vals, sigma_vals)
99
100 prices.shape = (n_strikes, n_sigmas)
101 strike_mesh, sigma_mesh = np.meshgrid(strike_vals, sigma_vals)
61 102
62 def plot_options(sigma_vals, K_vals, prices):
103 print "Results are available: strike_mesh, sigma_mesh, prices"
104 print "To plot results type 'plot_options(sigma_mesh, strike_mesh, prices)'"
105
106 #-----------------------------------------------------------------------------
107 # Utilities
108 #-----------------------------------------------------------------------------
109
110 def plot_options(sigma_mesh, strike_mesh, prices):
63 111 """
64 Make a contour plot of the option price in (sigma, K) space.
112 Make a contour plot of the option price in (sigma, strike) space.
65 113 """
66 from matplotlib import pyplot as plt
67 plt.contourf(sigma_vals, K_vals, prices)
114 plt.figure(1)
115
116 plt.subplot(221)
117 plt.contourf(sigma_mesh, strike_mesh, prices['ecall'])
118 plt.axis('tight')
68 119 plt.colorbar()
69 plt.title("Option Price")
120 plt.title('European Call')
121 plt.ylabel("Strike Price")
122
123 plt.subplot(222)
124 plt.contourf(sigma_mesh, strike_mesh, prices['acall'])
125 plt.axis('tight')
126 plt.colorbar()
127 plt.title("Asian Call")
128
129 plt.subplot(223)
130 plt.contourf(sigma_mesh, strike_mesh, prices['eput'])
131 plt.axis('tight')
132 plt.colorbar()
133 plt.title("European Put")
70 134 plt.xlabel("Volatility")
71 135 plt.ylabel("Strike Price")
136
137 plt.subplot(224)
138 plt.contourf(sigma_mesh, strike_mesh, prices['aput'])
139 plt.axis('tight')
140 plt.colorbar()
141 plt.title("Asian Put")
142 plt.xlabel("Volatility")
143
144
145
146
147
148
General Comments 0
You need to be logged in to leave comments. Login now