##// END OF EJS Templates
Improved Monte-Carlo options pricing example.
Improved Monte-Carlo options pricing example.

File last commit:

r2525:b83de157
r2525:b83de157
Show More
mcdriver.py
148 lines | 4.7 KiB | text/x-python | PythonLexer
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337 #!/usr/bin/env python
"""Run a Monte-Carlo options pricer in parallel."""
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 #-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import sys
import time
Brian E Granger
Fixed most of the examples. A few still don't work, but this is a start.
r1338 from IPython.kernel import client
Brian Granger
Initial draft of Windows HPC documentation.
r2344 import numpy as np
from mcpricer import price_options
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 from matplotlib import pyplot as plt
#-----------------------------------------------------------------------------
# Setup parameters for the run
#-----------------------------------------------------------------------------
def ask_question(text, the_type, default):
s = '%s [%r]: ' % (text, the_type(default))
result = raw_input(s)
if result:
return the_type(result)
else:
return the_type(default)
cluster_profile = ask_question("Cluster profile", str, "default")
price = ask_question("Initial price", float, 100.0)
rate = ask_question("Interest rate", float, 0.05)
days = ask_question("Days to expiration", int, 260)
paths = ask_question("Number of MC paths", int, 10000)
n_strikes = ask_question("Number of strike values", int, 5)
min_strike = ask_question("Min strike price", float, 90.0)
max_strike = ask_question("Max strike price", float, 110.0)
n_sigmas = ask_question("Number of volatility values", int, 5)
min_sigma = ask_question("Min volatility", float, 0.1)
max_sigma = ask_question("Max volatility", float, 0.4)
strike_vals = np.linspace(min_strike, max_strike, n_strikes)
sigma_vals = np.linspace(min_sigma, max_sigma, n_sigmas)
#-----------------------------------------------------------------------------
# Setup for parallel calculation
#-----------------------------------------------------------------------------
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337
Brian Granger
Work in the documentation.
r2345 # The MultiEngineClient is used to setup the calculation and works with all
# engine.
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 mec = client.MultiEngineClient(profile=cluster_profile)
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337
Brian Granger
Work in the documentation.
r2345 # The TaskClient is an interface to the engines that provides dynamic load
# balancing at the expense of not knowing which engine will execute the code.
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 tc = client.TaskClient(profile=cluster_profile)
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337
Brian Granger
Work in the documentation.
r2345 # Initialize the common code on the engines. This Python module has the
# price_options function that prices the options.
Brian Granger
Initial draft of Windows HPC documentation.
r2344 mec.run('mcpricer.py')
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 #-----------------------------------------------------------------------------
# Perform parallel calculation
#-----------------------------------------------------------------------------
print "Running parallel calculation over strike prices and volatilities..."
print "Strike prices: ", strike_vals
print "Volatilities: ", sigma_vals
sys.stdout.flush()
# Submit tasks to the TaskClient for each (strike, sigma) pair as a MapTask.
t1 = time.time()
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337 taskids = []
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 for strike in strike_vals:
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337 for sigma in sigma_vals:
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 t = client.MapTask(
price_options,
args=(price, strike, sigma, rate, days, paths)
)
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337 taskids.append(tc.run(t))
bgranger
Adding figures for options pricing example.
r2346 print "Submitted tasks: ", len(taskids)
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 sys.stdout.flush()
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337
Brian Granger
Work in the documentation.
r2345 # Block until all tasks are completed.
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337 tc.barrier(taskids)
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 t2 = time.time()
t = t2-t1
print "Parallel calculation completed, time = %s s" % t
print "Collecting results..."
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337
Brian Granger
Work in the documentation.
r2345 # Get the results using TaskClient.get_task_result.
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337 results = [tc.get_task_result(tid) for tid in taskids]
Brian Granger
Work in the documentation.
r2345 # Assemble the result into a structured NumPy array.
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 prices = np.empty(n_strikes*n_sigmas,
Brian Granger
Work in the documentation.
r2345 dtype=[('ecall',float),('eput',float),('acall',float),('aput',float)]
Brian Granger
Initial draft of Windows HPC documentation.
r2344 )
Brian Granger
Improved Monte-Carlo options pricing example.
r2525
Brian Granger
Initial draft of Windows HPC documentation.
r2344 for i, price_tuple in enumerate(results):
prices[i] = price_tuple
Brian Granger
Improved Monte-Carlo options pricing example.
r2525
prices.shape = (n_strikes, n_sigmas)
strike_mesh, sigma_mesh = np.meshgrid(strike_vals, sigma_vals)
Brian E Granger
Adding examples from ipython1-dev to docs/examples/kernel. These ...
r1337
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 print "Results are available: strike_mesh, sigma_mesh, prices"
print "To plot results type 'plot_options(sigma_mesh, strike_mesh, prices)'"
#-----------------------------------------------------------------------------
# Utilities
#-----------------------------------------------------------------------------
def plot_options(sigma_mesh, strike_mesh, prices):
Brian Granger
Initial draft of Windows HPC documentation.
r2344 """
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 Make a contour plot of the option price in (sigma, strike) space.
Brian Granger
Initial draft of Windows HPC documentation.
r2344 """
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 plt.figure(1)
plt.subplot(221)
plt.contourf(sigma_mesh, strike_mesh, prices['ecall'])
plt.axis('tight')
Brian Granger
Initial draft of Windows HPC documentation.
r2344 plt.colorbar()
Brian Granger
Improved Monte-Carlo options pricing example.
r2525 plt.title('European Call')
plt.ylabel("Strike Price")
plt.subplot(222)
plt.contourf(sigma_mesh, strike_mesh, prices['acall'])
plt.axis('tight')
plt.colorbar()
plt.title("Asian Call")
plt.subplot(223)
plt.contourf(sigma_mesh, strike_mesh, prices['eput'])
plt.axis('tight')
plt.colorbar()
plt.title("European Put")
Brian Granger
Initial draft of Windows HPC documentation.
r2344 plt.xlabel("Volatility")
plt.ylabel("Strike Price")
Brian Granger
Improved Monte-Carlo options pricing example.
r2525
plt.subplot(224)
plt.contourf(sigma_mesh, strike_mesh, prices['aput'])
plt.axis('tight')
plt.colorbar()
plt.title("Asian Put")
plt.xlabel("Volatility")