[PYTHON] [Cistre] Beyond MACD ♬

I noticed that I tried the MACD method the other day with various brands. Isn't this a bit slow to signal? ??

Aside from the fact that it is not good to do it on a daily basis, it was originally defined as follows.

MACD = 12-day EMA-26-day EMA
Signal = MACD 9-day EMA
Histogram = Signal-MACD

Therefore, it is a judgment standard that it is only necessary to be able to judge the next day's buying and selling from the daily data. As a characteristic output, let's take a look at the now popular'ZM'. 3.png

It is a very monotonous picture that rises to the right, and if you can predict the ups and downs obediently, you can make a lot of money.

* A word because it looks like a stupid story if there is a misunderstanding. .. .. "If you buy it and keep it for a long time, you can make a lot of money in this case, but in reality, the lever is large as it is due to financial efficiency, so it is a premise that you can not hold it with an instant explosion and you will lose money." "This brand has doubled the lever, so even if you bought it in January, it's now tripled if you have it. This looks safe, but the risk of going down. Is about the same, so ... "

If you look closely, the moment when you cross 0 in the histogram is a little late, and if the period of lowering is short, you sell at the place where it almost goes down, and conversely, if you go up quickly, you buy at the place where it goes up. There may be. This is a little wasteful. If you buy and sell after confirming the lowering and raising, it has almost the same meaning as the human eye and judgment. Here, the aim is automatic trading, and the efficiency and accuracy of trading are essential, so I would like to have the ability to predict numerical fluctuations.

  • I will pursue here, but it is not the main subject of today.

Therefore, although there is no theory, we improved this MACD method and devised a way to issue a trading signal at an earlier stage. The definition used this time is as follows. ** When using this, please call it mu_method **

series ;Data in chronological order
series2, cycle = decompose(series)
MACD2 = series2-26 days EMA(series2)
Signal2 = MACD2 9-day EMA
Histogram = Signal2-MACD2
  • Refer to the bonus code for details. In other words, the original data series itself was a little noisy and the error was too large, so it was smoothed by EMA on the 12th. However, when you decompose the series, the noise element disappears, so you can treat it almost like smoothed data. Based on that, calculate 26-day EMA and MACD. As a result, series2, which goes up and down near the raw data, gives a much faster trading signal than the one that was EMAd on the 12th. The results are as follows. 2.png

The gif animation is as follows. Three images (MACD, MACD of trend, mu-method) are played repeatedly, but the picture with ZM in the title is the picture after this improvement. Compared to the original MACD, the signal clearly shifts to the left for more than 3 days, which I think will be in time for buying and selling.

  • It seems that a decline will be seen early next week. ** It's lowered on Friday the 12th ** YahooFinance zm.gif I put the code as a bonus.

Summary

-Improved the MACD trading signal so that it can be issued quickly in time for the actual trading.

・ I wonder if I will finally do it. ..

bonus

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
from pandas_datareader import data
import statsmodels.api as sm
from statsmodels.tsa.seasonal import STL

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

def EMA1(x, n):
    #k = 3.45*(n+1)
    a= 2/(n+1)
    return pd.Series(x).ewm(alpha=a).mean()

stock0 = 'ZM'
stock = stock0  #+ '.JP'
start = dt.date(2020,1,1)
end = dt.date(2020,6,13)
df = pd.DataFrame(get_stock(stock, start, end))
date_df=df['Close'].index.tolist()
series = df['Close'].values.tolist()

bunseki = "trend" #series" #cycle" #trend
cycle, trend = sm.tsa.filters.hpfilter(series, 144)
df['Close'] = trend
series2 = df['Close'].values.tolist()

df['Close']=series  #series" #cycle" #trend
df['Close2']=series2
df['y12'] = EMA1(df['Close2'], 12)
df['y26'] =  EMA1(df['Close2'], 26)
df['MACD'] = df['y12'] -df['y26']
df['MACD2'] = df['Close2'] -df['y26']
df['signal2'] = EMA1(df['MACD2'], 9)
df['signal'] = EMA1(df['MACD'], 9)
df['hist_']=df['MACD2']-df['signal2']
date_df=df['Close'].index.tolist()
print(df[len(series)-10:len(series)])

fig, (ax1,ax2) = plt.subplots(2,1,figsize=(1.6180 * 8, 4*2),dpi=200)
ax1.plot(df['Close'],label="series")
ax1.plot(df['Close2'],label="series2")
ax1.plot(df['y12'],label="y12")
ax1.plot(df['y26'],label="y26")
ax2.plot(df['MACD2'],label="MACD2")
#ax2.plot(df['MACD'],label="MACD")
ax2.plot(df['signal2'],label="signal2")
#ax2.plot(df['signal'],label="signal")
ax2.bar(date_df,df['hist_'])
ax1.set_title("{}".format(stock0))
ax1.legend()
ax2.legend()
ax1.grid()
ax2.grid()
ax2.set_ylim(-5,20)
plt.savefig("./stock/{}/newck_ema_df_decompose_%5K%25D_{}_{}now{}.png ".format(stock0,stock,bunseki,start))
plt.pause(1)
plt.close()

Recommended Posts