In the previous recipe, we tried out a trading idea. However, we have no benchmark that can tell us if the result we got was any good. It is common in such cases to trade at random, under the assumption that we should be able to beat a random process. We will simulate trading by taking some random days from a trading year. This should illustrate working with random numbers using NumPy.
If necessary, install Matplotlib. Refer to the See Also section for the corresponding recipe.
First, we need an array filled with random integers.
Generate random integers with the NumPy randint
function. This will be linked to random days of a trading year:
return numpy.random.randint(0, high, size)
Simulate trades with the random indices from the previous step. Use the NumPy take
function to extract random close prices from the array of step 1:
buys = numpy.take(close, get_indices(len(close), nbuys)) sells = numpy.take(close, get_indices(len(close), nbuys)) profits[i] = sells.sum() - buys.sum()
Let's plot a histogram of the profits for a large number of simulations:
matplotlib.pyplot.hist(profits) matplotlib.pyplot.show()
The resulting histogram of 2000 simulations for AAPL with 5 buys and sells in a year:
The following is the complete code:
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) quotes = quotes_historical_yahoo(sys.argv[1], start, today) close = numpy.array([q[4] for q in quotes]) nbuys = int(sys.argv[2]) N = int(sys.argv[3]) 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 "Mean", profits.mean() print "Std", profits.std() #4. Plot a histogram of the profits matplotlib.pyplot.hist(profits) matplotlib.pyplot.show() #python random_periodic.py AAPL 5 2000 #Mean -2.566465 #Std 133.746039463
We used the randint
function, which can be
found in the
numpy.random
module. This module contains more convenient random generators, as described in the following table: