NumPy Periodic Dips

The stock market has periodic dips to the downside and sometimes to the upside, but those have a different name. Our Fantasy Hedge Fund needs to rebalance its portfolio 5 times a year (this is all part of our plan of Total World Domination). Therefore this User Story:

We will have a look at the probability distribution of the stock price log returns.

from matplotlib.finance import quotes_historical_yahoo

from datetime import date

import numpy

import sys

import scipy.stats

import matplotlib.pyplot


#1. Get close prices.

today = date.today()

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


quotes = quotes_historical_yahoo('AAPL', start, today)

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


#2. Get log returns.

logreturns = numpy.diff(numpy.log(close))


#3. Calculate breakout and pullback

freq = 1/float(50)

breakout = scipy.stats.scoreatpercentile(logreturns, 100 * (1 - freq) )

pullback = scipy.stats.scoreatpercentile(logreturns, 100 * freq)


#4. Generate buys and sells

buys = numpy.compress(logreturns < pullback, close)

sells = numpy.compress(logreturns > breakout, close)

print buys

print sells

print len(buys), len(sells)

print sells.sum() - buys.sum()


#5. Plot a histogram of the log returns

matplotlib.pyplot.hist(logreturns)

matplotlib.pyplot.show()

The output for AAPL and a 50 day period is:

[ 377.35 378. 373.17 415.99 603.51]

[ 370.8 366.48 419.55 571.91 555. ]

5 5

135.72