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 Oscillator ②ImmediateDeprecationError of Google Finance data #587 ③pandas.core.window.rolling.Rolling.min
・ Introduction to Systre ・ Move the code ・ How is it now?
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
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. 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. 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 Stocks ⑨A trader’s guide to the stochastic oscillator
Sony; There are many shops. .. .. A little overbought. .. .. Japan Airlines 9201; It was overbought. .. .. But can you buy it on Monday? Sumitomo Mitsui Financial Group 8316; Hmm, overbought. .. .. NTT DoCoMo 9437; If it's oversold and blue comes up, buy it ♬
It's easy to use, so let's use it ・ Stock_trade / stc2.py
・ 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.
・ Yahoo Finance is prohibited from scraping Automatic acquisition (scraping) of Yahoo! Finance publication information is prohibited
Recommended Posts