Skip to content

Plotting in Python?

An answer to this question on Stack Overflow.

Question

I wrote a program in Python that calculates a random walk for an array given certain parameters.

I presume the "random" function is working, since I get the output " (I am using iPython). However, I cannot plot the function on a graph, because the float() argument must be a string or number, not a function. Nevertheless, given the recursive nature of the variables in question, it needs to be defined as a function for the program to run.

How can I graph this?

Answer

How about this?

randomnumbers = np.random.normal((mu*(price/10)), (v*(price/10)), days) #This variable generates a series of random numbers based on the normal distribution and in accordance with the return and volatility specified.
randomwalk    = [simAssetPrice[i-1] + randomnumbers[i] + k for i in range(1,days)]
plt.plot(randomwalk)
plt.ylabel('Price')
plt.show()

I had to use one more random number then you specified.

In place of your randomwalk() function, I've used a list comprehension.

Using the same names for variables as for functions is bound to mess things up. Also, since you wrote:

randomwalk
plt.plot(randomwalk)

You were referring to a "pointer" to the function. You need to write randomwalk(simAssetPrice, randomnumbers) in order to call the function.

You may want to review how functions work in Python.