Z. Joe
Z. Joe

Reputation: 1

Python error: could not broadcast input array from shape (20,10) into shape (10)

I have the following code and get this error: S[i+1,:] = (S[i,:] + np.cumsum(np.sqrt(dt)np.random.randn(nsims),axis=0)) + epsilon_plusnp.random.poisson(lambda_plus,(M,nsims))

ValueError: could not broadcast input array from shape (20,10) into shape (10)

sigma = 0.1
dt = 0.05
lambda_plus = 2
lambda_minus = 2
M = 20 #number of steps
epsilon_plus = 1.0/2
epsilon_minus = 1.0/2   
T = 1
nsims = 10
s = 100
S = s*np.ones((M,nsims))

def price(lambda_plus, lambda_minus, M, T, dt, nsims):
    for i in range(M-1):
        S[i+1,:]  = (S[i,:] + np.cumsum(np.sqrt(dt)*np.random.randn(nsims),axis=0)) + epsilon_plus*np.random.poisson(lambda_plus,(M,nsims))
    return S

The error occurs when I add the part of epsilon_plus*np.random.poisson(lambda_plus,(M,nsims)). How can I add this part to S?

Upvotes: 0

Views: 147

Answers (1)

Grismar
Grismar

Reputation: 31416

The problem is this expression:

S[t-1] + sigma*math.sqrt(dt)*A + epsilon_plus*B-epsilon_minus*C

All three terms you're adding sigma*math.sqrt(dt)*A, epsilon_plus*B, and epsilon_minus*C have shape (201,), and so does the result after adding to S[t-1] - but you're trying to assign it to S[t], which has shape (1,).

You need to explain what exactly you expect to store in S[t] for me to provide a solution - I don't want to reverse engineer / guess intent from your code.

Upvotes: 1

Related Questions