Lab Dates: Wednesday-Thursday, 8-9 May 2013

Today's lab focuses on simulations from Chapter 9.

Random Walks and Stock Prices

Random walks (and their more sophisticated cousins, Monte Carlo methods) are used to simulate diverse phenomena from predicting stock prices to predicting the weather.

We will focus on simulating how the price of a stock changes over a year. We will start with the price of $1, and each day with probability prob (entered by the user), the price will increase by a dollar. If it does not increase, it's price will go down by a dollar:

    money = 1

    for day in range(365):
        if (random() < prob):
            money = money + 1
        else
            money = money - 1

We can make a graphic version of this by plotting the change in money made each day:

def simulateYear(prob, win):

    #we'll start with $1 on day 0:
    oldPt = Point(0,1)
    money = 1
    

    for day in range(365):
        if (random() < prob):
            money = money + 1
        else:
            money = money - 1
        newPt = Point(day,money)
        Line(oldPt, newPt).draw(win)
        oldPt = newPt

    #Return the price of the stock on the last day:
    return(oldPt.getY())

To run this program, we will also need a main:

def main():
    w = GraphWin("Stock Price Simulation", 400,200)
    w.setCoords(-10,-100,365,100)
    endingValue = [0]*10
    

    p = eval(input("Please enter a number between 0 and 1:"))

    #draw axis:
    Line(Point(0,0),Point(365,0)).draw(w)
    Line(Point(0,-100),Point(0,100)).draw(w)

    for i in range(10):
        endingValue[i] = simulateYear(p,w)

    print("The ending values of our simulation were:", endingValue)

    w.getMouse()
    w.close()

Put these all in one file (along with the necessary import statements at the top of the file for math, graphics, and random). What happens when you run the program? Try entering values .5, .25, and .75 for the starting probabilities.

Lastly, the program prints out all the money earned at the end of each year of the simulation. Modify the code so that it prints out the maximum value and minimum value of the ending values (hint: use the built-in python function or see discussion at the end of Chapter 7 text or slides).

After completing your program, go to Labs in Blackboard and click on the link: Lab 10 and answer the questions (if you do not get the answers right the first time, try again until you do).