Simulated random Trading

from matplotlib.finance import quotes_historical_yahoo

from datetime import date

import numpy

import sys

import matplotlib.pyplot

 

def get_indices(high, size):

   #2. Generate random indices

   return numpy.random.randint(0, high, size)

 

#1. Get close prices.

today = date.today()

start = (today.year - 1, today.month, today.day)

#2000 simulations for AAPL with 5 buys and sells in a year

q1='AAPL'

nbuys = 5

N = 2000

quotes = quotes_historical_yahoo(q1, start, today)

close =  numpy.array([q[4] for q in quotes])

 

profits = numpy.zeros(N)

 

for i in xrange(N):

   #3. Simulate trades

   buys = numpy.take(close, get_indices(len(close), nbuys))

   sells = numpy.take(close, get_indices(len(close), nbuys))

   profits[i] = sells.sum() - buys.sum()

 

print "Profits Mean:", profits.mean()

print "Profits Std:", profits.std()

 

#4. Plot a histogram of the profits

matplotlib.pyplot.hist(profits)

matplotlib.pyplot.show()