1

I'm plotting Stock prices that evolve according to geometric Brownian motion. You don't need to understand the mathematics, I've taken care of it all. But, my plots are not what I want them to be. They are too bunched up together

enter image description here

and for some reason it's adding these straight lines which I think might be lines of best fit, but I can't see at all where it comes from my code.

Here is my python code. Any suggestions to help me distinguish the paths better, and get rid of those straight lines?

from scipy.stats import norm
from scipy import sqrt
import matplotlib.pyplot as plt
def Euler_disc(S0, mu, sigma, T, n): 
    times = [0]
    stocks = [S0]
    dt = ((float(T)/n))
    for i in range(0, 10): 
        for x in range(0, n): 
            times.append(times[x] + dt)
            stocks.append(stocks[x] + mu * stocks[x] * dt \
            + sigma * stocks[x] * sqrt(dt) * norm.rvs(0, 1, 1))
        plt.plot(times, stocks)
3
  • The lines are drawn because your data does not seem to be in the right order. Matplotlib doesnt sort your data points but plots one after another, connecting each one with the previous one. So if you go back to e.g. 0, 0 after the last point, there will be a line from your last point straight back to 0, 0. Commented Sep 10, 2015 at 19:26
  • What are you using the i loop for? Commented Sep 10, 2015 at 19:38
  • to plot ten paths of the stock Commented Sep 10, 2015 at 19:42

1 Answer 1

1

You are reusing the times and stocks variable in each inner loop. So everytime you reach plt.plot(times, stocks), you will replot all your calculated data.

Here is the fixed version:

from scipy.stats import norm
from scipy import sqrt
import matplotlib.pyplot as plt
def Euler_disc(S0, mu, sigma, T, n): 
    dt = ((float(T)/n))
    for i in range(0, 10): 
        times = [0]
        stocks = [S0]
        for x in range(0, n): 
            times.append(times[x] + dt)
            stocks.append(stocks[x] + mu * stocks[x] * dt \
            + sigma * stocks[x] * sqrt(dt) * norm.rvs(0, 1, 1))
        plt.plot(times, stocks)
Sign up to request clarification or add additional context in comments.

2 Comments

Nice catch. Although, you do not need that last line since I want each graph to start from the same stock value. I graphed it both ways, and I want the version without that last line.
Ok, I removed it. I just noticed that you have a random component in there, I was asking myself earlier "Why does he want to plot the same line 10 times?". Makes sense now!

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.