from IPython.display import HTML
HTML('')
HTML('')
HTML('')
from IPython.parallel import Client
c = Client()
c.history, c.ids
dv = c[:]
print(type(dv))
lv = c.load_balanced_view()
print(type(lv))
dv.results.items()
ar = dv.scatter('x', range(64),block=True)
print(type(ar))
ar = dv.scatter('x', range(1024*1024*30),block=False)
ar.get(), ar.progress, ar.elapsed, ar.ready(), ar.serial_time, ar.wall_time
l = c[4]['x']
print(4, min(l), max(l), len(l))
l = c[6]['x']
print(6, min(l), max(l), len(l))
c[0].push(dict(x=[0]))
l= dv.pull('x',targets=0,block=True)
print(0, min(l), max(l), len(l))
l = c[7].pull('x').get()
print(7, min(l), max(l), len(l))
dv.push(dict(x=[1]))
dv.gather('x').get()
import gc
gc.collect()
with c[:].sync_imports():
import gc
%px gc.collect()
with c[:].sync_imports():
import numpy
%px x = numpy.random.randint(0,1024,10)
%%px --targets ::2
x.sort()
print(x, numpy.average(x))
%pxconfig --noblock --targets [0,1,2,3]
%px print (x, numpy.average(x))
%pxresult
from IPython.parallel import CompositeError
import random
print( c[0].pull('x').get() )
c[0].execute('numpy.append(x,[1,2,3])')
print( c[0].pull('x').get() )
i = random.choice(c.ids)
c[i].execute('x = numpy.append(x,[0])')
print( i, c[i].pull('x').get() )
try:
dv.execute('y = int(numpy.max(x)) / int(numpy.min(x))', block=True)
except CompositeError, e:
print e
%px print y
%pxresult
%%px --targets 7
from IPython import parallel
parallel.bind_kernel()
c[7].execute("%qtconsole")
import time, os
def getFewDetailsWithDelay(delay):
time.sleep(delay)
return os.getpid()
getFewDetailsWithDelay(0)
dv.apply_sync(getFewDetailsWithDelay,3)
import random, time, os
from IPython.parallel import require
@require(random, os,time)
def getFewDetails():
delay = random.randint(0,10)
time.sleep(delay)
return os.getpid()
ar = dv.apply_async(getFewDetails)
ar.progress
ar.progress, ar.get(), ar.wall_time, ar.serial_time
ar.metadata
%matplotlib inline
import matplotlib.pyplot as plt
import sys
import time
import numpy as np
price = 100.0 # Initial price
rate = 0.05 # Interest rate
days = 260 # Days to expiration
paths = 100000 # Number of MC paths
n_strikes = 6 # Number of strike values
min_strike = 90.0 # Min strike price
max_strike = 110.0 # Max strike price
n_sigmas = 5 # Number of volatility values
min_sigma = 0.1 # Min volatility
max_sigma = 0.4 # Max volatility
strike_vals = np.linspace(min_strike, max_strike, n_strikes)
sigma_vals = np.linspace(min_sigma, max_sigma, n_sigmas)
print "Strike prices: ", strike_vals
print "Volatilities: ", sigma_vals
def price_option(S=100.0, K=100.0, sigma=0.25, r=0.05, days=260, paths=10000):
"""
Price European and Asian options using a Monte Carlo method.
Parameters
----------
S : float
The initial price of the stock.
K : float
The strike price of the option.
sigma : float
The volatility of the stock.
r : float
The risk free interest rate.
days : int
The number of days until the option expires.
paths : int
The number of Monte Carlo paths used to price the option.
Returns
-------
A tuple of (E. call, E. put, A. call, A. put) option prices.
"""
import numpy as np
from math import exp,sqrt
h = 1.0/days
const1 = exp((r-0.5*sigma**2)*h)
const2 = sigma*sqrt(h)
stock_price = S*np.ones(paths, dtype='float64')
stock_price_sum = np.zeros(paths, dtype='float64')
for j in range(days):
growth_factor = const1*np.exp(const2*np.random.standard_normal(paths))
stock_price = stock_price*growth_factor
stock_price_sum = stock_price_sum + stock_price
stock_price_avg = stock_price_sum/days
zeros = np.zeros(paths, dtype='float64')
r_factor = exp(-r*h*days)
euro_put = r_factor*np.mean(np.maximum(zeros, K-stock_price))
asian_put = r_factor*np.mean(np.maximum(zeros, K-stock_price_avg))
euro_call = r_factor*np.mean(np.maximum(zeros, stock_price-K))
asian_call = r_factor*np.mean(np.maximum(zeros, stock_price_avg-K))
return (euro_call, euro_put, asian_call, asian_put)
%timeit -n1 -r1 print price_option(S=100.0, K=100.0, sigma=0.25, r=0.05, days=260, paths=100000)
rc = Client()
view = rc.load_balanced_view()
async_results = []
%%timeit -n1 -r1
for strike in strike_vals:
for sigma in sigma_vals:
# This line submits the tasks for parallel computation.
ar = view.apply_async(price_option, price, strike, sigma, rate, days, paths)
async_results.append(ar)
rc.wait(async_results) # Wait until all tasks are done.
len(async_results)
results = [ar.get() for ar in async_results]
prices = np.empty(n_strikes*n_sigmas,
dtype=[('ecall',float),('eput',float),('acall',float),('aput',float)]
)
for i, price in enumerate(results):
prices[i] = tuple(price)
prices.shape = (n_strikes, n_sigmas)
plt.figure()
plt.contourf(sigma_vals, strike_vals, prices['ecall'])
plt.axis('tight')
plt.colorbar()
plt.title('European Call')
plt.xlabel("Volatility")
plt.ylabel("Strike Price")
plt.figure()
plt.contourf(sigma_vals, strike_vals, prices['acall'])
plt.axis('tight')
plt.colorbar()
plt.title("Asian Call")
plt.xlabel("Volatility")
plt.ylabel("Strike Price")
plt.figure()
plt.contourf(sigma_vals, strike_vals, prices['eput'])
plt.axis('tight')
plt.colorbar()
plt.title("European Put")
plt.xlabel("Volatility")
plt.ylabel("Strike Price")
plt.figure()
plt.contourf(sigma_vals, strike_vals, prices['aput'])
plt.axis('tight')
plt.colorbar()
plt.title("Asian Put")
plt.xlabel("Volatility")
plt.ylabel("Strike Price")
HTML('')
HTML('')
HTML('')
HTML('')
HTML('')
HTML('')
from IPython.display import YouTubeVideo
YouTubeVideo('z1DQzrpXN_U')