[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬

I tried Stochastic Oscillator, the entrance to system trading, after raising the stock price. The python code is in Reference ①, so it's 3 years old, so if you think it's still there, it won't work. So, I'll put it together in an article so I don't forget it. 【reference】 ①Investing with Python: Stochastic OscillatorImmediateDeprecationError of Google Finance data #587pandas.core.window.rolling.Rolling.min

What i did

・ Introduction to Systre ・ Move the code ・ How is it now?

・ Introduction to Systre

Basically ① Buy when it goes down ② Sell when it goes up It is OK if the system can automate that. Is ① going down any more? ② Can it go up any more? There is a risk, so I would like to identify that as well. One of the most commonly used methods for this determination is to use the Stochastic Oscillator graph shown in Reference (1), and this time we will describe how to code it so that it can be used. The Stochastic Oscillator is calculated as follows:

%K = (Current Close - Lowest Low)/(Highest High - Lowest Low) * 100
%D = 3-day SMA of %K
Lowest Low =The lowest low for the look-back period)
Highest High =Highest high for the look-back period)
3-day SMA =3-day simple moving average

A lookback period of 14 days is usually used. How to find the simple moving average is as follows

SMA(n) = \frac {\sum_{i=0}^{n-1}(CLOSE_i)} {n}

【reference】 ④ Analyzing stocks to understand corporate performance

・ Move the code

Actually, the code of reference ① does not work. In addition, Yahoo Finance is prohibited from scraping.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
from pandas_datareader import data

You can get it by specifying the date on yahoo, google, and other pay sites, but you cannot specify the end date on this site. However, it works as the same function by extracting what you need from the retrieved data as follows: Also, since the data sequence is reversed, it is reversed. 【reference】 ⑥ [Get a specific row / column from a data frame with Pandas](https://pythondatascience.plavox.info/pandas/%E8%A1%8C%E3%83%BB%E5%88%97%E3% 81% AE% E6% 8A% BD% E5% 87% BA) ⑦Right way to reverse pandas.DataFrame?

def get_stock(stock,start,end):
    df = data.DataReader(stock, 'stooq',start)["Close"]
    df = df.iloc[::-1]
    return df[start:end]

def get_high(stock,start,end):
    df = data.DataReader(stock, 'stooq',start)['High']
    df = df.iloc[::-1]
    return df[start:end]

def get_low(stock,start,end):
    df = data.DataReader(stock, 'stooq',start)['Low']
    df = df.iloc[::-1]
    return df[start:end]

Calculate the above% K below. Here, rolling (). Max () of pandas has been changed, and it can be calculated by doing the following according to reference ③.

def STOK(close, low, high, n): 
    STOK = ((close - low.rolling(n).min()) / (high.rolling(n).max() - low.rolling(n).min())) * 100
    return STOK

Below is the function that calculates% D. Calculate% K to calculate the 3-day simple moving average.

def STOD(close, low, high, n):
    STOK = ((close - low.rolling(n).min()) / (high.rolling(n).max() - low.rolling(n).min())) * 100
    STOD = STOK.rolling(3).mean()
    return STOD

The brand uses sony. The period is the same as Reference ① above. In the first place, the number of days to look back on% K and% D is also 14 days.

stock = '6758.JP' #sony
start = dt.date(2016,1,1)
end = dt.date(2016,12,31)
df = pd.DataFrame(get_stock(stock, start, end))
df['High'] = get_high(stock, start, end)
df['Low'] = get_low(stock, start, end)
df['%K'] = STOK(df['Close'], df['Low'], df['High'], 14)
df['%D'] = STOD(df['Close'], df['Low'], df['High'], 14)

I will output the data for confirmation below.

print(df[0:30])
print(df.tail())
              Close     High      Low         %K         %D
Date
2016-01-04  2875.56  2981.55  2859.04        NaN        NaN
2016-01-05  2880.90  2916.39  2849.30        NaN        NaN
...
2016-01-21  2363.56  2506.53  2363.06        NaN        NaN
2016-01-22  2458.85  2470.05  2405.86  15.487720        NaN
2016-01-25  2468.09  2498.74  2439.42  18.493802        NaN
2016-01-26  2363.06  2408.78  2359.66   0.595113  11.525545
2016-01-27  2442.81  2453.99  2409.75  18.250258  12.446391
...
2016-02-15  2379.61  2408.29  2293.05  34.207540  16.258774
2016-02-16  2415.11  2459.84  2316.39  39.242858  27.149584
              Close     High      Low         %K         %D
Date
2016-12-26  3261.97  3293.31  3260.04  65.381424  70.155819
2016-12-27  3253.17  3264.93  3237.51  59.458713  65.992247
2016-12-28  3266.87  3296.23  3249.25  62.741071  62.527069
2016-12-29  3228.71  3261.97  3196.41  22.300469  48.166751
2016-12-30  3205.22  3240.46  3192.49   8.557408  31.199649
              Close     High      Low         %K         %D

Finally, the graph is output below. Since% D lacks data for 15 days (there is no data on Saturdays and Sundays in the first place), align the horizontal axes of ax1 and ax2 by plotting from the 16th day.

fig, (ax1,ax2) = plt.subplots(2,1,figsize=(1.6180 * 4, 4*1))
ax1.plot(df['Close'][16:],label = "close")
ax2.plot(df['%K'][16:],label = "%K")
ax2.plot(df['%D'][16:],label = "%D")
ax1.legend()
ax2.legend()
ax1.grid()
ax2.grid()
plt.savefig("./stock/stc_%K%D_6758.png ")
plt.show()

The result is as follows. stc_%K%D_6758.png I can't feel relieved, so I'll try to output the same output as the reference site. The 2016 chart of "FB" could be reproduced, and the same graphs of% K and% D were obtained. stc_%K%D_yahoo.png By the way, you can check the stock price of FB in 2016 in Reference ⑧.

Well, see the following reference ⑨ etc. for what to do from these charts. Reference ⑨ Google Translate and quote. ** "If it is above 80, the market is considered overbought and values below 20 are considered oversold.% K (blue line in the graph below) and% D (red line below). The intersection of these two lines indicates that the market is about to change direction. If% K is above% D, it is a buy signal unless the value exceeds 80. , When% K falls below% D, it is considered a sell signal unless the value falls below 20. "** 【reference】 ⑧ Facebook (Facebook, Inc.) Stock Price / US StocksA trader’s guide to the stochastic oscillator

・ How is it now?

Sony; There are many shops. .. .. A little overbought. .. .. stc_%K%D_6758_now.png Japan Airlines 9201; It was overbought. .. .. But can you buy it on Monday? stc_%K%D_9201.JP_now.png Sumitomo Mitsui Financial Group 8316; Hmm, overbought. .. .. stc_%K%D_8316.JP_now.png NTT DoCoMo 9437; If it's oversold and blue comes up, buy it ♬ stc_%K%D_9437.JP_now.png

I put the whole code below

It's easy to use, so let's use it ・ Stock_trade / stc2.py

Summary

・ I drew a stochastic Oscillator and played with it. ・ I feel like I can use it seriously

・ Is there an indicator? ・ Do you do systole? ・ If this is the case, it is likely that the transaction fee will go bankrupt, and it will be necessary to devise ways to see it over a long period of time.

bonus

・ Yahoo Finance is prohibited from scraping Automatic acquisition (scraping) of Yahoo! Finance publication information is prohibited

Recommended Posts

[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬
I played with PyQt5 and Python3
I made a system that automatically decides whether to run tomorrow with Python and adds it to Google Calendar.
I made a server with Python socket and ssl and tried to access it from a browser
[System trade] I tried playing with Stochastic Oscillator by decomposing with python ♬
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
I tried to make a periodical process with Selenium and Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
[Introduction to StyleGAN] I played with "A woman transforms into Mayuyu" ♬
I drew a heatmap with seaborn [Python]
[Introduction to Pytorch] I played with sinGAN ♬
[Introduction to AWS] I played with male and female voices with Polly and Transcribe ♪
I want to make a game with Python
I want to write to a file with Python
System trading starting with Python 3: Investment and risk
I ran GhostScript with python, split the PDF into pages, and converted it to a JPEG image.
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
When I tried to create a virtual environment with Python, it didn't work
I want to write an element to a file with numpy and check it.
I tried to easily create a fully automatic attendance system with Selenium + Python
Introduction to AI creation with Python! Part 3 I tried to classify and predict images with a convolutional neural network (CNN)
I tried to draw a route map with Python
I want to work with a robot in python.
I made a LINE BOT with Python and Heroku
I tried to automatically generate a password with Python3
I want to run a quantum computer with Python
I made a program to convert images into ASCII art with Python and OpenCV
A simple system that automatically shoots with object detection and sends it to LINE
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
Image processing with Python (I tried binarizing it into a mosaic art of 0 and 1)
I made a package to filter time series with python
I wrote a program quickly to study DI with Python ①
Associate Python Enum with a function and make it Callable
I made a simple book application with python + Flask ~ Introduction ~
I evaluated the strategy of stock system trading with Python.
Try to bring up a subwindow with PyQt5 and Python
[Python] I installed the game from pip and played it
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried a stochastic simulation of a bingo game with Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
I want to improve efficiency with Python even in an experimental system (2) RS232C and pySerial
I also tried to imitate the function monad and State monad with a generator in Python
[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.
I want to make a voice changer using Python and SPTK with reference to a famous site
I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
[5th] I tried to make a certain authenticator-like tool with python
I made a simple circuit with Python (AND, OR, NOR, etc.)
I made a library to easily read config files with Python
IPynb scoring system made with TA of Introduction to Programming (Python)
I want to use a wildcard that I want to shell with Python remove
[Introduction to Python3 Day 1] Programming and Python
[2nd] I tried to make a certain authenticator-like tool with python
I want to solve APG4b with Python (only 4.01 and 4.04 in Chapter 4)
A memorandum when I tried to get it automatically with selenium
[Introduction to Python] I compared the naming conventions of C # and Python.
[Python] A memo that I tried to get started with asyncio
I made a fortune with Python.
I made a Nyanko tweet form with Python, Flask and Heroku
I tried to create a list of prime numbers with python
I want to do a full text search with elasticsearch + python
Hadoop introduction and MapReduce with Python