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
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.
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).
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()
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.
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
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.
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
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