python - Efficient Way to Recursively Multiply -


i'm creating n_mc paths of simulated stock prices s n points in each path, excluding initial point. algorithm recursive on previous value of stock price, given path. here's have now:

import numpy np import time  n_mc = 1000 n = 10000  s = np.zeros((n_mc, n+1)) s0 = 1.0 s[:, 0] = s0  start_time_normals = time.clock() z = np.exp(np.random.normal(size=(n_mc, n))) print "generate normals time = ", time.clock() - start_time_normals  start_time_prices = time.clock() in xrange(n_mc):     j in xrange(1, n+1):         s[i, j] = s[i, j-1]*z[i, j-1]  print "pices time = ", time.clock() - start_time_prices 

the times were:

generate normals time =  1.07 pices time =  9.98 

is there more efficient way generate arrays s, perhaps using numpy's routines? nice if normal random variables z generated more quickly, too, i'm not hopeful.

it's not necessary loop on 'paths', because they're independent of each other. so, can remove outer loop for in xrange(n_mc) , operate on entire columns of s , z.

for accelerating recursive computation, let's consider single 'path'. z vector containing random values @ each timestep (all known ahead of time). s vector should contain output @ each timestep. s0 initial output @ time zero. j time.

your code defines ouput recursively:

s[j] = s[j-1]*z[j-1] 

let's expand this:

s[1] = s[0]*z[0]  s[2] = s[1]*z[1]      = s[0]*z[0]*z[1]  s[3] = s[2]*z[2]      = s[0]*z[0]*z[1]*z[2]  s[4] = s[3]*z[3]      = s[0]*z[0]*z[1]*z[2]*z[3] 

each output s[j] given s[0] times product of random values 0 j-1. can calculate cumulative products using numpy.cumprod(), should more efficient looping:

s = np.concatenate(([s0], s0 * np.cumprod(z[0:-1]))) 

you can use axis parameter operating along 1 dimension of matrix (e.g. doing in parallel across 'paths').


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -