Reputation: 67
Here is my code:
import random
def stock_sim(price,time,mu,std):
y=range(time)
for i in y:
y[i]=price+random.lognormvariate(mu,std)
return y
print(stock_sim(100,5,0,.2))
It returns:
[101.44054391531468, 100.73246087607879, 101.00880842134261, 101.14332126597128, 100.79412638906443]
I need it to return:
[100, 101.44054391531468, 100.73246087607879, 101.00880842134261, 101.14332126597128]
The first value should be the intial price on first day and then the following 4 changed prices.
Upvotes: 0
Views: 51
Reputation:
One possibility would be
def stock_sim(price,time,mu,std):
return [price]+[price + random.lognormvariate(mu,std) for i in range(time)]
There are many other ways, one could be to insert an item to the left, or create the list beforehand in the other solutions.
def stock_sim(price,time,mu,std):
temp = [price + random.lognormvariate(mu,std) for i in range(time)]
temp.insert(0,price)
return temp
I am not sure how big your lists will grow and if performance can be an issue. In this case a deque would be the better solution
from collections import deque
def stock_sim(price,time,mu,std):
temp = deque([price + random.lognormvariate(mu,std) for i in range(time)])
temp.appendleft(price)
return temp
Upvotes: 0
Reputation: 180482
Just keep a separate list and add price first:
def stock_sim(price,time,mu,std):
y = []
y.append(price)
for i in range(time):
y.append(price+random.lognormvariate(mu,std))
return y
Upvotes: 2