17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで簡単なモメンタム投資モデルを作る

Posted at

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

17
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?