I edited a chuck of random walk code from this link (ps: the orginal one works):
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import random
days = 100 # time horizon
random.seed(2022)
def random_walk(startprice):
price = np.zeros(days)
x = np.round(np.random.uniform(0, 10, days))
y = np.round(np.random.uniform(0, 10, days))
price[0] = startprice
for i in range(1, days):
price[i] = (1 + 0.8*x[i] + 1.5*y[i])*price[i-1]
# print(price[i])
return price
fig, axn = plt.subplots(figsize=(10, 6))
for run in range(10):
axn.plot(random_walk(10), label='time', linewidth='2')
But my edited version throw out an error: OverflowError: cannot convert float infinity to integer
, does someone could help to fix this issue? Thanks in advance.
Advertisement
Answer
Well, x[i]
can be as large as 10, and so can y[1]
, so
(1 + 0.8*x[i] + 1.5*y[i])*price[i-1]
can be as large as (1 + 0.8*10 + 1.5*10)*price[i-1]
= 24.0 * price[i-1]
.
You only need a few hundred of those chained to overflow to infinity:
>>> import math
>>> math.nextafter(math.inf, 0)
1.7976931348623157e+308
>>> math.log(_, 24)
223.3387949931843
Of course they won’t all be 10, but it doesn’t matter all that much: exponential growth quickly explodes regardless. If, e.g., they were all 5 instead:
>>> math.log(1.7976931348623157e+308, 5)
441.0127954671545
The question is more why you don’t expect it to overflow to infinity?
Note that the code you started from did not multiply on each step. It added a “random shock” instead. That’s far better behaved.