Skip to content

Instantly share code, notes, and snippets.

@sawadyrr5
Created March 26, 2020 13:57
Show Gist options
  • Save sawadyrr5/590be6fc2ffeb4635a9b7c15229df20e to your computer and use it in GitHub Desktop.
Save sawadyrr5/590be6fc2ffeb4635a9b7c15229df20e to your computer and use it in GitHub Desktop.
Pythonで簡単なモメンタム投資モデルを作る

250日ルックバックでモメンタムがゼロを超えたら買い、逆にゼロを下回ったら売ります。

# -*- 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()

output_4_0.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment