-3

So, I was working on some basic finance, trying to simulate a number of random stock price paths, when I encountered this inscrutable bug in the code. I try to print out a single number many times in a nested loop, but for some reason the number varies.

My code so far:

# Imports.

%matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from math import *

# Error-producing section - randnorm holds a 10x10 vector of normally distributed 
# random numbers, used in calculating my price path.

sims = 5
intervals = 5
r=.02
T=1
sigma=.15

paths = [[1]*intervals]*sims
randnorm = [[np.random.normal() for x in range(10)] for y in range(10)]
# print(randnorm)

for i in range(sims):
    for j in range(1,intervals):
        paths[i][j] = paths[i][j-1] * exp((r - .5*sigma**2)*(T/intervals) + sqrt(T/intervals)*randnorm[i][j-1])
        print(paths[0][1])

I knew something was wrong with my previous code, so I tried debugging by printing in each loop, and I get this,

0.5937221173702402
0.5937221173702402
0.5937221173702402
0.5937221173702402
1.4849274521869171
1.4849274521869171
1.4849274521869171
1.4849274521869171
0.860018700453769
0.860018700453769
0.860018700453769
0.860018700453769
1.0709782525755074
1.0709782525755074
1.0709782525755074
1.0709782525755074
0.7184834195858915
0.7184834195858915
0.7184834195858915
0.7184834195858915

What gives? I seriously do not know where I could be wrong here. It's not my random numbers, which are all different, or an index issue.

Coolio2654
  • 1,589
  • 3
  • 21
  • 46

1 Answers1

0

It has to be something with how your array was created, as making an np.ndarray of simsxintervals in size results in the outputs remaining the exact same (either 0.0 or some zero-like floating error of 0.x*10-8).

paths = np.ndarray((sims, intervals))
for i in range(sims):
    for j in range(1,intervals):
        paths[i][j] = paths[i][j-1] * exp((r - .5*sigma**2)*(T/intervals) + sqrt(T/intervals)*randnorm[i][j-1])
        print(paths[0][1])

Output:

0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0

Without more explanation of what paths actually is, and how it was made, and it's pre-loop values, it's impossible to diagnose the issue.


Edit

After the question was updated, a resolution would be to just use np.ones to make the matrix.

paths = np.ones((sims, intervals))

The current implementation is causing the issue in the marked duplicate, where each list is a reference to the same list, so modifying one will modify all of them.

Jorden
  • 653
  • 5
  • 11