Create a simple momentum investment model in Python

Buy when momentum exceeds zero in a 250-day lookback, and sell when momentum falls below zero.

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

Recommended Posts

Create a simple momentum investment model in Python
Create a simple GUI app in Python
Create a function in Python
Create a dictionary in Python
Create a DI Container in Python
Create a binary file in Python
Implementing a simple algorithm in Python 2
Create a Kubernetes Operator in Python
Run a simple algorithm in Python
Create a random string in Python
A simple HTTP client implemented in Python
Try drawing a simple animation in Python
Create a JSON object mapper in Python
Write a simple greedy algorithm in Python
[GPS] Create a kml file in Python
Write a simple Vim Plugin in Python 3
Set up a simple HTTPS server in Python 3
Create a Vim + Python test environment in 1 minute
Create a GIF file using Pillow in Python
Simple gRPC in Python
Create a Python module
Create SpatiaLite in Python
Create a standard normal distribution graph in Python
Create a virtual environment with conda in Python
A simple Pub / Sub program note in Python
Create a new page in confluence with Python
Create a datetime object from a string in Python (Python 3.3)
Set up a simple SMTP server in Python
Create a package containing global commands in Python
Create a Python environment
Create a MIDI file in Python using pretty_midi
Create a loop antenna pattern in Python in KiCad
[Docker] Create a jupyterLab (python) environment in 3 minutes!
Write a super simple molecular dynamics program in python
Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
In Python, create a decorator that dynamically accepts arguments Create a decorator
Create a fake Minecraft server in Python with Quarry
Take a screenshot in Python
Visualize Keras model in Python 3.5
Create a Wox plugin (Python)
Create a (simple) REST server
Create gif video in Python
Make a bookmarklet in Python
Create a python numpy array
Simple regression analysis in Python
Create a simple textlint server
Draw a heart in Python
Simple IRC client in python
Create a directory with python
I made a simple typing game with tkinter in Python
Create a local scope in Python without polluting the namespace
Create a list in Python with all followers on twitter
Create a child account for connect with Stripe in Python
A simple way to avoid multiple for loops in Python
[Python Kivy] How to create a simple pop up window
Create code that outputs "A and pretending B" in python
Create a simple video analysis tool with python wxpython + openCV
Create a simple Python development environment with VSCode & Docker Desktop
Create a tool to check scraping rules (robots.txt) in Python
Create a python machine learning model relearning mechanism with mlflow