##// END OF EJS Templates
Merging Brian's trunk-dev....
Brian Granger -
r2530:9d940dc9 merge
parent child Browse files
Show More
@@ -28,7 +28,10 b' from zope.interface import Interface, implements'
28 from twisted.internet.base import DelayedCall
28 from twisted.internet.base import DelayedCall
29 DelayedCall.debug = True
29 DelayedCall.debug = True
30
30
31 from foolscap import Referenceable, DeadReferenceError
31 try:
32 from foolscap.api import Referenceable, DeadReferenceError
33 except ImportError:
34 from foolscap import Referenceable, DeadReferenceError
32 from foolscap.referenceable import RemoteReference
35 from foolscap.referenceable import RemoteReference
33
36
34 from IPython.kernel.pbutil import packageFailure, unpackageFailure
37 from IPython.kernel.pbutil import packageFailure, unpackageFailure
@@ -24,7 +24,10 b' from twisted.internet import reactor, defer'
24 from twisted.python import log
24 from twisted.python import log
25
25
26 import foolscap
26 import foolscap
27 from foolscap import Tub, UnauthenticatedTub
27 try:
28 from foolscap.api import Tub, UnauthenticatedTub
29 except ImportError:
30 from foolscap import Tub, UnauthenticatedTub
28
31
29 from IPython.config.loader import Config
32 from IPython.config.loader import Config
30 from IPython.kernel.configobjfactory import AdaptedConfiguredObjectFactory
33 from IPython.kernel.configobjfactory import AdaptedConfiguredObjectFactory
@@ -22,7 +22,11 b' import warnings'
22 from twisted.python import components
22 from twisted.python import components
23 from twisted.python.failure import Failure
23 from twisted.python.failure import Failure
24 from zope.interface import Interface, implements, Attribute
24 from zope.interface import Interface, implements, Attribute
25 from foolscap import DeadReferenceError
25
26 try:
27 from foolscap.api import DeadReferenceError
28 except ImportError:
29 from foolscap import DeadReferenceError
26
30
27 from IPython.utils.coloransi import TermColors
31 from IPython.utils.coloransi import TermColors
28
32
@@ -24,7 +24,10 b' from zope.interface import Interface, implements'
24 from twisted.internet import defer
24 from twisted.internet import defer
25 from twisted.python import components, failure
25 from twisted.python import components, failure
26
26
27 from foolscap import Referenceable
27 try:
28 from foolscap.api import Referenceable
29 except ImportError:
30 from foolscap import Referenceable
28
31
29 from IPython.kernel import error
32 from IPython.kernel import error
30 from IPython.kernel import map as Map
33 from IPython.kernel import map as Map
@@ -20,7 +20,11 b' __docformat__ = "restructuredtext en"'
20
20
21 from zope.interface import Interface, implements
21 from zope.interface import Interface, implements
22 from twisted.python import components
22 from twisted.python import components
23 from foolscap import DeadReferenceError
23
24 try:
25 from foolscap.api import DeadReferenceError
26 except ImportError:
27 from foolscap import DeadReferenceError
24
28
25 from IPython.kernel.twistedutil import blockingCallFromThread
29 from IPython.kernel.twistedutil import blockingCallFromThread
26 from IPython.kernel import task, error
30 from IPython.kernel import task, error
@@ -24,7 +24,10 b' from zope.interface import Interface, implements'
24 from twisted.internet import defer
24 from twisted.internet import defer
25 from twisted.python import components
25 from twisted.python import components
26
26
27 from foolscap import Referenceable
27 try:
28 from foolscap.api import Referenceable
29 except ImportError:
30 from foolscap import Referenceable
28
31
29 from IPython.kernel import task as taskmodule
32 from IPython.kernel import task as taskmodule
30 from IPython.kernel.clientinterfaces import (
33 from IPython.kernel.clientinterfaces import (
@@ -1,71 +1,148 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Run a Monte-Carlo options pricer in parallel."""
2 """Run a Monte-Carlo options pricer in parallel."""
3
3
4 #-----------------------------------------------------------------------------
5 # Imports
6 #-----------------------------------------------------------------------------
7
8 import sys
9 import time
4 from IPython.kernel import client
10 from IPython.kernel import client
5 import numpy as np
11 import numpy as np
6 from mcpricer import price_options
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 # The MultiEngineClient is used to setup the calculation and works with all
46 # The MultiEngineClient is used to setup the calculation and works with all
9 # engine.
47 # engine.
10 mec = client.MultiEngineClient(profile='mycluster')
48 mec = client.MultiEngineClient(profile=cluster_profile)
11
49
12 # The TaskClient is an interface to the engines that provides dynamic load
50 # The TaskClient is an interface to the engines that provides dynamic load
13 # balancing at the expense of not knowing which engine will execute the code.
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 # Initialize the common code on the engines. This Python module has the
54 # Initialize the common code on the engines. This Python module has the
17 # price_options function that prices the options.
55 # price_options function that prices the options.
18 mec.run('mcpricer.py')
56 mec.run('mcpricer.py')
19
57
20 # Define the function that will make up our tasks. We basically want to
58 #-----------------------------------------------------------------------------
21 # call the price_options function with all but two arguments (K, sigma)
59 # Perform parallel calculation
22 # fixed.
60 #-----------------------------------------------------------------------------
23 def my_prices(K, sigma):
61
24 S = 100.0
62 print "Running parallel calculation over strike prices and volatilities..."
25 r = 0.05
63 print "Strike prices: ", strike_vals
26 days = 260
64 print "Volatilities: ", sigma_vals
27 paths = 100000
65 sys.stdout.flush()
28 return price_options(S, K, sigma, r, days, paths)
66
29
67 # Submit tasks to the TaskClient for each (strike, sigma) pair as a MapTask.
30 # Create arrays of strike prices and volatilities
68 t1 = time.time()
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.
39 taskids = []
69 taskids = []
40 for K in K_vals:
70 for strike in strike_vals:
41 for sigma in sigma_vals:
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 taskids.append(tc.run(t))
76 taskids.append(tc.run(t))
44
77
45 print "Submitted tasks: ", len(taskids)
78 print "Submitted tasks: ", len(taskids)
79 sys.stdout.flush()
46
80
47 # Block until all tasks are completed.
81 # Block until all tasks are completed.
48 tc.barrier(taskids)
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 # Get the results using TaskClient.get_task_result.
89 # Get the results using TaskClient.get_task_result.
51 results = [tc.get_task_result(tid) for tid in taskids]
90 results = [tc.get_task_result(tid) for tid in taskids]
52
91
53 # Assemble the result into a structured NumPy array.
92 # Assemble the result into a structured NumPy array.
54 prices = np.empty(nK*nsigma,
93 prices = np.empty(n_strikes*n_sigmas,
55 dtype=[('ecall',float),('eput',float),('acall',float),('aput',float)]
94 dtype=[('ecall',float),('eput',float),('acall',float),('aput',float)]
56 )
95 )
96
57 for i, price_tuple in enumerate(results):
97 for i, price_tuple in enumerate(results):
58 prices[i] = price_tuple
98 prices[i] = price_tuple
59 prices.shape = (nK, nsigma)
99
60 K_vals, sigma_vals = np.meshgrid(K_vals, sigma_vals)
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
114 plt.figure(1)
67 plt.contourf(sigma_vals, K_vals, prices)
115
116 plt.subplot(221)
117 plt.contourf(sigma_mesh, strike_mesh, prices['ecall'])
118 plt.axis('tight')
68 plt.colorbar()
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 plt.xlabel("Volatility")
134 plt.xlabel("Volatility")
71 plt.ylabel("Strike Price")
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