3

I am attempting to build a graph in Python. However, I am trying to do this over a period of 250 days, and am trying to use a while command to iterate up to t<250.

However, this is not working for some reason. Additionally, while I have imported matplotlib, I am not overly familiar with how to plot the graph (which would not have data anyway if the code is not iterating), but want to space out the days and price on the x and y-axis so it displays correctly and numbers are not bunched together, etc.

I am still trying to solve this, but would be very grateful for any additional input.

2 Answers 2

1

What you were missing was a vector of the x-values, actually t-values. Secondly only numpy not math allows you to vectorize a function, so if the input is a vector then the function makes an evaluation for each input value and returns a vector.

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt


mu = 0.09
v = 0.15
s0 = 500
#Expected return k (per year), k = mu-(v**2)/2
k = mu-(v**2)/2

t=np.arange(0,250)

#Simulation
s1 =  s0*np.exp(k*t/250+v*s0*np.sqrt(t/250)) 
plt.figure(figsize=(10, 6), dpi=80)

plt.plot(t,s1)

plt.xlim(0.0, 250.0)
plt.xticks(np.linspace(0, 250, 11, endpoint=True))
#plt.ylim(0, 10000)
# plt.yticks(np.linspace(00, 10000, 10, endpoint=True))

plt.title(r'Stock Returns')

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks. I have a follow up question if I may; I am using the IPython program to run the above (which I used before and displayed the graphs). However, when I run the code, e.g. plt.plot(t,s1), I just get an output message saying [<matplotlib.lines.Line2D at 0xe690cf82e8>]. The graph itself does not actually display. Any ideas?
That depends on your environment. In Ipython (jupyter) you don't need plt.show() in most cases. Plot pops up in separate window though. I mostly use inline plots %matplotlib inline or %pylab inline.
0

I can immediately see one major problem with the script. It would be better to compute t and s1 as numpy arrays in advance.

t = np.arange(250)
s1 = s0*np.exp(k*t/250+v*s0*np.sqrt(t/250))

Both t and s1 are now numpy arrays. With this you can make the plot easily

 plt.plot(t,s1) # line plot

Once you got that you can add bells and whistles as you like.

What is implemented in your script is that one point (t,s1) is plotted and that was replaced by the next point (t, s1) and so on by the while loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.