import ystockquote import pylab import numpy import math import datetime from collections import defaultdict def main(): date_a = '1990-01-01' date_b = '2014-01-01' indices = ['^FTSE', '^GDAXI', '^FCHI', '^SSMI', '^BFX', # '^OMX', '^OSEAX', '^IBEX' # Europe '^N225', '^HSI', '^STI', '^AORD', '^BSESN', '^JKSE', '^KLSE', '^NZ50', '^NSEI', '^KS11', '^TWII', #Asia '^MERV', '^GSPTSE', '^MXX', '^GSPC', '^IPSA', # '^BVSP' # Americas '^CCSI', '^TA100'] # Africa windows = [0, 10, 20, 40, 100, 200] # 0 means buy and hold all_returns = {} all_returns_n = {} for window in windows: all_returns[window] = defaultdict(float) all_returns_n[window] = defaultdict(int) for index in indices: try: data = ystockquote.get_historical_prices(index, date_a, date_b) except: print 'could not scrape', index continue x = sorted(data.keys()) y = [math.log(float(data[date]['Close'])) for date in x] x = [datetime.date(*map(int, d.split('-'))) for d in x] for window in windows: returns = [] dates = [] for i in xrange(len(x)-window-1): if window > 0: dp = (y[i+window] - y[i]) # / numpy.std(y[i:i+window]) else: dp = 1.0 dt = y[i+window+1] - y[i+window] returns.append((dp > 0) * dt) date = x[i+window] dates.append(date) all_returns[window][date] += (dp > 0) * dt all_returns_n[window][date] += 1.0 years = (max(dates) - min(dates)).days / 365.25 print '%20s %3d %5.2f' % (index, window, sum(returns) / numpy.std(returns) / 16 / years) for window in windows: dates = sorted(all_returns[window].keys()) returns = [all_returns[window][date] / all_returns_n[window][date] for date in dates] years = (max(dates) - min(dates)).days / 365.25 print '%20s %3d %5.2f' % ('ALL', window, sum(returns) / numpy.std(returns) / 16 / years) if window > 0: label = 'Momentum (%d days)' % window else: label = 'Buy and hold' returns_dumb = 100.0 * numpy.exp(numpy.cumsum(returns)) returns_adj = numpy.cumsum(returns) / numpy.std(returns) / 16 # Std devs per year pylab.plot(dates, returns_adj, label=label) # pylab.yscale('log') pylab.legend(loc='upper left') # pylab.show() pylab.savefig('indices.png') if __name__ == '__main__': main()