Achetez lorsque l'élan dépasse zéro dans une période d'analyse de 250 jours, et vendez lorsque l'élan tombe en dessous de zéro.
# -*- coding: utf-8 -*-
import pandas_datareader.data as web
from datetime import datetime
import talib as ta
import matplotlib.pyplot as plt
import pandas as pd
# make plots inline
%matplotlib inline
# setting parameters
ticker = 'SPY'
sd = datetime(2001, 1, 1)
ed = datetime(2015, 12, 31)
period = 250
# getting price data
d = web.DataReader(ticker, 'yahoo', sd, ed)
d.sort_index(ascending=True, inplace=True)
# calcurating momentum
momentum = ta.MOM(d['Adj Close'].values, period)
# initialize
maxcnt = d['Adj Close'].count()
cash = [None for row in range(maxcnt)]
position = [None for row in range(maxcnt)]
asset = [None for row in range(maxcnt)]
cash[0] = 10000
position[0] = 0
# simulation
for i, (index, row) in enumerate(d.iterrows()):
if i > 0:
cash[i] = cash[i-1]
position[i] = position[i-1]
if momentum[i] > 0 and momentum[i-1] < 0:
# open(buy)
amount = cash[i] // row['Adj Close']
position[i] += amount
cash[i] -= amount * row['Adj Close']
elif momentum[i] < 0 and momentum[i-1] > 0:
# close(sell)
cash[i] += position[i] * row['Adj Close']
position[i] = 0
asset[i] = cash[i] + position[i] * row['Adj Close']
d['asset'] = asset
# plot result
d2 = pd.DataFrame()
d2['Stock'] = d['Adj Close']/d['Adj Close'][0]*100
d2['Performance'] = asset/asset[0]*100
d2.plot()
plt.show()
Recommended Posts