[PYTHON] Investment quest: Make a system trade with pyhton (1)

System trade in python: draw a moving average

System trading strategy

Although the world is tough in Corona, stocks are showing the appearance of the Corona monetary easing bubble as of January 2009. Right now, I'm crazy about this trend, but as the saying goes, "Setsubun ceiling, equinoctial week", I think Ikeike is just around the corner. After that, I feel that the range market will come for a while until the next trend comes. I would like to consider system trading using machine learning that can respond to range markets and trend markets. As a library of python, there is a library called TA-Lib, but for studying, I will consider it without using it as much as possible.

As for this strategy,

    1. Buy and sell etf
    1. Use Bollinger Bands as an indicator
    1. Buy at the lower limit of the Bollinger Bands and sell at the upper limit

There are various indicators, but it is a simple Bollinger Bands strategy. After studying python in Bollinger Bands, I think it would be good if there were other good indicators (MACD, RSI) and what would happen if the indicators were combined.

While making a system trade of Bollinger Bands first

    1. So which etf is better? Which of the topix, Nikkei 225, and other indicators has the best win rate? 2.3. So, think about what σ of the Bollinger band has a good winning percentage

I will confirm and make a system trade.

Obtaining data

First, we will consider the target of 1306 Nomura Asset's TOPIX-linked exchange-traded fund. Scraping technology is postponed. Click to collect from this site. https://kabuoji3.com/ It's a little annoying, but you can get the annual csv file from 2001 with just a click. 1306_2001.csv ~ 1306_2021.csv

image.png You can get files of these daily etf price movements.

Data combination

First is the data combination. This was easily combined with pandas. I combined it without thinking deeply, but since "1306 TSE ETF TOPIX Exchange Traded Fund (ETF)" is included in the 0th line, data = pd.read_csv (file, encoding ='Shift-Jis'" , header = 1) and header = 1 on the first line image.png

Was read as the column name. Since the column name is Japanese, I changed it to appropriate English for the time being.

import pandas as pd
import matplotlib.pyplot as plt
import datetime

import matplotlib.dates as mdates

#read_Combine all the data with csv.
#1306_2001 to 1306_2021

df = None

for i in range(2001,2021):
    
    file = '1306_' + str(i) + '.csv'
    print(file)
    
    data = pd.read_csv(file,encoding='Shift-Jis',header = 1)
    
    
    df = pd.concat( [df,data],ignore_index=True)
    
df.rename(columns={'date': 'day', 'Open price': 'open_price',
                   'High price':'high_price', 'Low price':'low_price',
                   'closing price': 'end_price', 'Volume':'volume',
                   'Closing price adjustment value':'end_price_ad_value'}, inplace=True)
    
print(df.head())

For the time being, the pandas dataset has been created.

When you make a graph, it looks like this. It is the highest price in 10 years now. It's cool. image.png

Next is how to draw a Bollinger band.

How to draw Bollinger Bands

What is Bollinger Bands is quoted from the website of MONEX, Inc. https://info.monex.co.jp/technical-analysis/indicators/003.html "It is composed of a moving average line and standard deviation, and it is an index that adds a line showing the moving average and a line showing the width of price movement above and below it, and says that" most of the price falls within this band. " It is one of the technical indicators that apply statistics. "

That is, you need to calculate the moving average and standard deviation from the price of the stock. Later, in terms of "technical indicators that apply statistics," it may be compatible with machine learning. First, calculate the moving average.

Calculation of simple moving average

Simple moving average is the average price of the closing price for a certain period. So we use the rolling function of pandas. For example, in the rolling function,rolling (5) .mean ()returns the average of five numbers. So, let's calculate with df ["end_price "] .rolling (5) .mean (). Round (1) and draw a 5-day moving average.

#'day'To datetime type
df['day'] = pd.to_datetime(df['day'])
#'day'Replace with index.
df.set_index('day', inplace=True)
#Calculate the 5-day moving average
df["5day_ave"]=df["end_price"].rolling(5).mean().round(1)

#Take out the second half of 2019 from July to December
df_temp = df['2019-07':'2019-12']

#Draw on the graph
plt.plot(df_temp.index, df_temp["end_price"], label="daily")
plt.plot(df_temp.index, df_temp["5day_ave"],  label="sma5")
plt.xlabel("day")
plt.ylabel("price")
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%b-%Y'))
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=2))
plt.gca().xaxis.set_minor_locator(mdates.MonthLocator(interval=1))
plt.gcf().autofmt_xdate()

plt.legend()
plt.show()

image.png

I was able to draw a moving average line. Next, I will draw the Bollinger Bands. It is in the next Investment quest: Make a system trade with pyhton (2).

Recommended Posts

Investment quest: Make a system trade with pyhton (2)
Investment quest: Make a system trade with pyhton (1)
Make a recommender system with python
Is this a system trade?
Make a fortune with Python
Make a fire with kdeplot
Acoustic signal processing starting with Python-Let's make a stereophonic system
Let's make a GUI with python.
Let's make a breakout with wxPython
Make a filter with a django template
Let's make a graph with python! !!
Let's make a supercomputer with xCAT
Make a model iterator with PySide
Make a nice graph with plotly
System trading starting with Python3: long-term investment
Let's make a shiritori game with Python
Make a video player with PySimpleGUI + OpenCV
"System trade starting with Python3" reading memo
Make a rare gacha simulator with Flask
Make a Notebook Pipeline with Kedro + Papermill
Make a partially zoomed figure with matplotlib
Make a drawing quiz with kivy + PyTorch
Let's make a voice slowly with Python
Create a star system with Blender 2.80 script
Make a cascade classifier with google colaboratory
Let's make a simple language with PLY 1
Make a logic circuit with a perceptron (multilayer perceptron)
Make a Yes No Popup with Kivy
Make a wash-drying timer with a Raspberry Pi
Make a GIF animation with folder monitoring
Let's make a web framework with Python! (1)
Let's make a tic-tac-toe AI with Pylearn 2
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
How to make a dialogue system dedicated to beginners
A memorandum to make WebDAV only with nginx
Make a Twitter trend bot with heroku + Python
[Python] Make a game with Pyxel-Use an editor-
Make a monitoring device with an infrared sensor
Make a simple pixel art generator with Flask
How to make a dictionary with a hierarchical structure.
I want to make a game with Python
Build a cheap summarization system with AWS components
Try to make a "cryptanalysis" cipher with Python
[Python] Make a simple maze game with Pyxel
Let's replace UWSC with Python (5) Let's make a Robot
Try to make a dihedral group with Python
[Chat De Tornado] Make a chat using WebSocket with Tornado
Make holiday data into a data frame with pandas
Make a LINE WORKS bot with Amazon Lex
(Memorandum) Make a 3D scatter plot with matplodlib
System trading starting with Python 3: Investment and risk
Make one repeating string with a Python regular expression.
Make a morphological analysis bot loosely with LINE + Flask
Try to make a command standby tool with python
[Practice] Make a Watson app with Python! # 2 [Translation function]
[Practice] Make a Watson app with Python! # 1 [Language discrimination]
Make a simple Slackbot with interactive button in python
[Let's play with Python] Make a household account book
How to make a shooting game with toio (Part 1)