Detect golden crosses on stock charts in Python

Introduction

As a signal when buying stocks, there is a phenomenon on the chart called Golden Cross. It's a technique that's mostly found in chart analysis books, but is it really a valid technique? In this article, we define the golden cross and consider whether it is a valid buying signal. (Caution: It is a discussion of whether it is valid within the defined range, and it is not intended to criticize the method. Therefore, the link of the reference financial site is not provided. Also, the use of the program and analysis results At your own risk.) 【Implementation content】

--Defining the Golden Cross and creating a detection program --Verification of whether Golden Cross is a signal at the time of purchase

Definition of Golden Cross

The golden cross is when the short-term moving average exceeds the long-term moving average (for the moving average, Develop an investment algorithm in Python 2. Please refer to items / 6337543ba3eb700d0aaa "Explanation of moving average")). First, I set the daily stock price as the closing price (honestly, I don't know which of "opening price", "closing price", "high price", and "low price" is better). Next, you need to set the length of this averaging period. This time, the short-term average was set to 5 days and the long-term average was set to 25 days. Lastly, the day before the "exceeded day" was set as the day when the long-term average was higher and the day when the short-term average was higher.

Golden cross detection

I will explain the program that detects the golden cross. The output result is as follows. The blue line is the daily stock price and the red square is the golden cross (the y value of the red square is the stock price for better visibility). goldencross_detection.png

I will explain in the order of the program (the summarized source is goldencross_detection.py and I put it at the bottom). For the first stock price acquisition, [Stock price acquisition and candlestick chart creation in Python]( See http://qiita.com/kjybinp1105/items/be462b481b47b6f94b14 "Getting stock prices and creating candlestick charts in Python").

Stock price acquisition


import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import pandas as pd

#Setting the period
start = datetime.datetime(2011, 1, 1)
end = datetime.datetime(2017, 5, 30)

#Stock price acquisition
df = web.DataReader('TM', 'google', start, end)
df = df.loc[:, ['Close']]

Use pandas.rolling to calculate the moving average. As per the program, adjust the length of the average period in windows. Naturally, the average is the average of the period with the current day as the last day. It is not used for the moving average, but by setting center = True, it is possible to make the average centered on the current day.

Calculation of moving average


#Setting the average period
short_term = 5
long_term = 25

#Calculation of period average
df['av_short'] = df['Close'].rolling(window=short_term).mean()#Short term average
df['av_long'] = df['Close'].rolling(window=long_term).mean()#Long-term average

Detects golden cross. In the program, the stock price on the day of the Golden Cross is entered in the column'golden_flag', and None on other days.

Golden cross detection and illustration


#Golden cross detection
df['golden_flag'] = 0
current_flag=0
previous_flag=1
for i,price in df.iterrows():
    if(price['av_short']>price['av_long']):
        current_flag = 1
    else:
        current_flag = 0
    if(current_flag*(1-previous_flag)):
        df.loc[i,'golden_flag']=price['av_long']
    else:
        df.loc[i,'golden_flag']= None
    previous_flag = current_flag

#Illustrated
df.plot(style=['-'])
plt.scatter(x= df.index,y = df['golden_flag'],marker='s',color='red')
plt.show()

Stock price transition after the golden cross

Next, after the Golden Cross, let's see if the stock price is rising. Assuming that the stock price on the day of the Golden Cross is 1.0, we will plot the stock price 1 to 20 days later. If the golden cross is a signal at the time of buying, the stock price should rise overall. Regarding the program (transition_after_goldencross.py), there are many duplicates, so I will explain only three points.

  1. Next day based on DataFrame.index To convert a date to one day later with the datetime module, you need to set "day + datetime.timedelta (days = 1)" as "day + 1" will result in an error. Furthermore, since the stock price does not always exist the next day, I made a function that returns the next day containing the index of the DataFrame as shown below.

A function that returns the day after the stock price exists


def GetIndexNextDay(df,day):
    for p in range(1,10)://10 is suitable
        if((day+datetime.timedelta(days=p)) in df.index):
            next_day = day+datetime.timedelta(days=p)
            return next_day
  1. From List to DataFrame I saved the stock price transition as a List, converted it to a DataFrame, and then plotted it. From the beginning, I thought that I could do it with DataFrame, but I managed to make it like this.
  2. Ingenuity in the illustration It's hard to see just the transition of all the Golden Crosses from 2011 to 2017, so I calculated the average and plotted it prominently (red). The results based on the above three items are as follows. The black line is the stock price transition from the date of each golden cross detection. Since the stock price on the detection date is 1.0, it is all 1.0 on day = 0. The red line is the average of all black lines. To be honest, it doesn't look like it's rising on average. transition_after_goldencross.png

At the end

The Golden Cross personally didn't look like a signal when buying. However, if you look closely, many sites and books have fake golden crosses, so be careful. I also wrote how to distinguish it, but it is written sensuously and it seems that it is not easy to implement, so I will end here this time.

Reference site

Element reference and assignment in pandas DataFrame index https://hydrocul.github.io/wiki/numpy/pandas-dataframe-ref-index.html

matplotlib.markers http://matplotlib.org/api/markers_api.html#module-matplotlib.markers

Dataframe assignment method http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Develop an investment algorithm in Python 2 http://qiita.com/hiroshimoda/items/6337543ba3eb700d0aaa

Source code

goldencross_detection.py


import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import pandas as pd

#Setting the period
start = datetime.datetime(2011, 1, 1)
end = datetime.datetime(2017, 5, 30)

#Stock price acquisition
df = web.DataReader('TM', 'google', start, end)
df = df.loc[:, ['Close']]

#Setting the average period
short_term = 5
long_term = 25

#Calculation of period average
df['av_short'] = df['Close'].rolling(window=short_term).mean()#Short term average
df['av_long'] = df['Close'].rolling(window=long_term).mean()#Long-term average

#Golden cross detection
df['golden_flag'] = 0
current_flag=0
previous_flag=1
for i,price in df.iterrows():
    if(price['av_short']>price['av_long']):
        current_flag = 1
    else:
        current_flag = 0
    if(current_flag*(1-previous_flag)):
        df.loc[i,'golden_flag']=price['av_long']
    else:
        df.loc[i,'golden_flag']= None
    previous_flag = current_flag


#Illustrated
df.plot(style=['-'])
plt.scatter(x= df.index,y = df['golden_flag'],marker='s',color='red')

plt.show()

transition_after_goldencross.py


import datetime
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import pandas as pd

def GetIndexNextDay(df,day):
    for p in range(1,10):
        if((day+datetime.timedelta(days=p)) in df.index):
            next_day = day+datetime.timedelta(days=p)
            return next_day

#Stock price acquisition
start = datetime.datetime(2011, 1, 1)#Stock price acquisition start date
end = datetime.datetime(2017, 5, 30)#Stock price acquisition end date
df = web.DataReader('TM', 'google', start, end)
df = df.loc[:, ['Close']]

#Calculation of period average
short_term = 5#Short-term average length
long_term = 25#Long-term average length
df['av_short'] = df['Close'].rolling(window=short_term).mean()#Calculation of short-term average
df['av_long'] = df['Close'].rolling(window=long_term).mean()#Long-term average calculation

#Golden cross detection
golden_day = []
df['golden_flag'] = 0
current_flag=0
previous_flag=1
for i,price in df.iterrows():
    if(price['av_short']>price['av_long']):
        current_flag = 1
    else:
        current_flag = 0
    if(current_flag*(1-previous_flag)):
        df.loc[i,'golden_flag']=price['Close']
        golden_day.append(i)
    else:
        df.loc[i,'golden_flag']= None
    previous_flag = current_flag
    
#Save transition
transitions = []
for day in golden_day:
    day_transition = [df['Close'][day]/df['Close'][day]]
    next_day = day
    for term in range(1,20):
        next_day = GetIndexNextDay(df,next_day)
        day_transition.append(df['Close'][next_day]/df['Close'][day])
    transitions.append(day_transition)
    
#Illustrated
df2 = (pd.DataFrame(ss)).T
df_mean = ((df2.T).mean()).T
df2.plot(legend=False,color = 'black')
df_mean.plot(color = 'red',lw=5)
plt.show()

Recommended Posts

Detect golden crosses on stock charts in Python
Get stock prices and create candlestick charts in Python
Drawing candle charts in python
Detect keystrokes in python (tty)
Detect keystrokes in Python (without Enter)
Displaying candlestick charts in Python (matplotlib edition)
Find files like find on linux in Python
Notes on nfc.ContactlessFrontend () for nfcpy in python
Run AzureKinect in Python on Christmas Eve.
Detect temperature using python on Raspberry Pi 3!
Displaying candlestick charts in Python (Plotly edition)
Notes on using code formatter in Python
Run Python in C ++ on Visual Studio 2017
Detect slide switches using python on Raspberry Pi 3!
Attempt to detect English spelling mistakes in python
Run Python YOLOv3 in C ++ on Visual Studio 2017
Detect magnet switches using python on Raspberry Pi 3!
Notes on using dict in python [Competition Pro]
A note on optimizing blackbox functions in Python
Note on encoding when LANG = C in Python
Try working with Mongo in Python on Mac
To write to Error Repoting in Python on GAE
ABC125_C --GCD on Blackboard [Notes solved in Python]
TensorFlow: Run data learned in Python on Android
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Meta-analysis in Python
Python on Windows
Unittest in python
twitter on python3
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
python on mac
Lifegame in Python.
FizzBuzz in Python
StepAIC in Python
N-gram in python
Csv in python
Disassemble in Python
Reflection in Python
Python on Windbg
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python