Python code to determine the monthly signal of a relative strength investment

Updated monthly signal for Relative Strength Investment on My Blog However, until now, I had to manually acquire data and calculate in Excel.

This time, I wrote python code to judge the monthly signal. I'm a beginner with python for several months, so please forgive me though it may be unsightly code. As far as I can see, it seems to be working properly.

1. Data scraping

[Monthly_check]RS_signal.ipynb


import numpy as np
import pandas as pd
from datetime import datetime
import urllib.request

#Obtain and save investment trust data csv from the SMTAM website.
#To minimize scraping, once scraped, save it as a csv file.

#JE:Japanese stocks, EE:Emerging market equities, IE:Developed country stocks, JB:Japanese bond, EB:Emerging Market Bonds, IB:Developed Government Bonds, IR:Developed country REIT, JR:Nippon REIT
url_list = {'JE':'https://www.smtam.jp/chart_data/140833/140833.csv',
            'EE':'https://www.smtam.jp/chart_data/140841/140841.csv',
            'IE':'https://www.smtam.jp/chart_data/140834/140834.csv',
            'JB':'https://www.smtam.jp/chart_data/140835/140835.csv',
            'EB':'https://www.smtam.jp/chart_data/140842/140842.csv',
            'IB':'https://www.smtam.jp/chart_data/140836/140836.csv',
            'IR':'https://www.smtam.jp/chart_data/140838/140838.csv',
            'JR':'https://www.smtam.jp/chart_data/140837/140837.csv'} 

for key in url_list:
    url = url_list[key]
    title = "{0}.csv".format(key)
    urllib.request.urlretrieve(url,title)

2. Signal judgment

[Monthly_check]RS_signal.ipynb


#Create data that summarizes the cumulative base prices of all funds
assets = ['JE','EE','IE','JB','EB','IB','JR','IR']
df_all = pd.DataFrame()
for asset in assets:
    asset_file = "{0}.csv".format(asset)
    df = pd.read_csv(asset_file, skiprows = [0], names = ['date','nav', 'div', 'aum'],
                    parse_dates = True, index_col = 0)

    df['div'] = pd.to_numeric(df['div'],errors='coerce')
    df['div'] = df['div'].fillna(0)
    
    df['cum_nav'] = (df['nav'] + df['div']) / df['nav'].shift(1)
    df[asset] = df['cum_nav'].cumprod()
    df_all[asset] = df[asset]


#Signal judgment by converting daily data to monthly data
dfm = df_all.resample('M').ffill()
dfm = dfm[dfm.index < datetime.now()] 

calc = pd.DataFrame(columns = ['JE','EE','IE','JB','EB','IB','JR','IR'])
calc.loc['asset class'] = ['Japanese stocks','Emerging market stocks','Developed country stocks','Japan bond','Emerging market bonds',
                          'Developed government bonds','Nippon REIT','Developed country REIT']
calc.loc['3 months'] = (dfm.iloc[-1] / dfm.iloc[-4] -1)*100
calc.loc['6 months'] = (dfm.iloc[-1] / dfm.iloc[-7] -1)*100
calc.loc['12 months'] = (dfm.iloc[-1] / dfm.iloc[-13] -1)*100
calc.loc['mean'] = (calc.loc['3 months']+calc.loc['6 months']+calc.loc['12 months'])/3
calc.loc['rank'] = calc.loc['mean'].rank(ascending = False).astype(int)
calc.loc['latest nav'] = dfm.iloc[-1]
calc.loc['12ma NAV'] = dfm.iloc[-12:].mean()
calc.loc['Buy/Sell'] = np.where(calc.loc['latest nav'] > calc.loc['12ma NAV'], 'Buy', 'Sell')

#Display monthly signal judgment result
date = dfm.index.max()
print(str(date.year) + 'Year' + str(date.month) + 'The signal at the end of the month is as follows.')
calc.T.set_index('rank')[['asset class', 'Buy/Sell']].sort_index()

When executed, the following will be displayed (should be) on the Jupyter Notebook. output.png

3. Reflected in the blog

Here is a blog post that reflects the above signal.  ↓ [Relative Strength Investment Monthly Signal Commentary (based on the end of March 2020)]

4. Conclusion

Monthly Signal Excel Update It took decades of manual work to complete. It has to be used for decades to be cost effective.

The code that judges the signal is really amateurish. I would like to improve when I improve.

Recommended Posts

Python code to determine the monthly signal of a relative strength investment
How to determine the existence of a selenium element in Python
Python Note: The mystery of assigning a variable to a variable
Display the signal strength RSSI of a specific SSID (mac)
A story that struggled to handle the Python package of PocketSphinx
How to check the memory size of a variable in Python
First python ② Try to write code while examining the features of python
I wrote the code to write the code of Brainf * ck in python
How to check the memory size of a dictionary in Python
Implement a deterministic finite automaton in Python to determine multiples of 3
[Python3] Define a decorator to measure the execution time of a function
[python] A note that started to understand the behavior of matplotlib.pyplot
[Python] A simple function to find the center coordinates of a circle
[Python] A program that rotates the contents of the list to the left
Measure the relevance strength of a crosstab
[Python3] Rewrite the code object of the function
[python] [meta] Is the type of python a type?
[Python] Get the character code of the file
The story of blackjack A processing (python)
Display the signal strength RSSI of a specific SSID (raspberry pi (linux))
Have Alexa run Python to give you a sense of the future
[Python] A program that calculates the number of socks to be paired
[Introduction to Python] How to sort the contents of a list efficiently with list sort
I made a program to check the size of a file in Python
Code reading of Safe, a library for checking password strength in Python
Python: I want to measure the processing time of a function neatly
I made a function to see the movement of a two-dimensional array (Python)
I found out by making a python script to record radiko while reading the code of the predecessors
How to run the practice code of the book "Creating a profitable AI with Python" on Google Colaboratory
"A book to train programming skills to fight in the world" Python code answer example --1.9 Rotation of strings
Various ways to read the last line of a csv file in Python
How to pass the execution result of a shell command in a list in Python
How to calculate the volatility of a brand
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
[Python] Read the source code of Bottle Part 2
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
Get the caller of a function in Python
[Python] Test the moon matagi of relative delta
Make a copy of the list in Python
A note about the python version of python virtualenv
Build a python environment to learn the theory and implementation of deep learning
[Python] A rough understanding of the logging module
Python script to get a list of input examples for the AtCoder contest
Output in the form of a python array
Code for checking the operation of Python Matplotlib
Convert the character code of the file with Python3
A python amateur tries to summarize the list ②
I tried to refactor the code of Python beginner (junior high school student)
I made a script to record the active window using win32gui of Python
A discussion of the strengths and weaknesses of Python
[Python] Throw a message to the slack channel
[Python] Determine the type of iris with SVM
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
"A book to train programming skills to fight in the world" Python code answer example --1.2 Count the number of the same characters
Run the output code with tkinter, saying "A, pretending to be B" in python
How to identify the element with the smallest number of characters in a Python list?
How to check in Python if one of the elements of a list is in another list
A memo of misunderstanding when trying to load the entire self-made module with Python3
A story about trying to introduce Linter in the middle of a Python (Flask) project
Don't take an instance of a Python exception class directly as an argument to the exception class!