import talib as tl
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime
hq_df = DataSource('bar1d_CN_STOCK_A').read(start_date='2019-01-01',
end_date=datetime.datetime.now().strftime('%Y-%m-%d'))
hq_df['close'] = hq_df['close']/hq_df['adjust_factor']
def MACD(df, fastperiod, slowperiod, signalperiod):
columns = list(df.columns)+['dif','gold','dead']
macdDIFF, macdDEA, macd = tl.MACDEXT(df['close'], fastperiod=fastperiod, fastmatype=1, slowperiod=slowperiod, slowmatype=1, signalperiod=signalperiod, signalmatype=1)
macd = macd * 2
df['dif'] = macdDIFF
df['dea'] = macdDEA
df['macd'] = macd
df['dif_1'] = df['dif'].shift(1)
df['dea_1'] = df['dea'].shift(1)
df['gold'] = np.where((df['dif_1'] < df['dea_1'])&(df['dif'] > df['dea']),1,0)
df['dead'] = np.where((df['dif_1'] > df['dea_1'])&(df['dif'] < df['dea']),1,0)
return df[columns]
cal_df = hq_df.groupby('instrument').apply(lambda x:MACD(x,12,26,9))
cal_df_filter = cal_df[cal_df.gold+cal_df.dead>0]
cal_df_filter['dead_1'] = cal_df_filter.groupby('instrument')['dead'].shift(1)
cal_df_filter['gold_2'] = cal_df_filter.groupby('instrument')['gold'].shift(2)
cal_df_filter['dead_3'] = cal_df_filter.groupby('instrument')['dead'].shift(3)
cal_df_filter['dif_1'] = cal_df_filter.groupby('instrument')['dif'].shift(1)
cal_df_filter['dif_2'] = cal_df_filter.groupby('instrument')['dif'].shift(2)
cal_df_filter['dif_3'] = cal_df_filter.groupby('instrument')['dif'].shift(3)
cal_df_filter['gold_1'] = cal_df_filter.groupby('instrument')['gold'].shift(1)
cal_df_filter['dead_2'] = cal_df_filter.groupby('instrument')['dead'].shift(2)
cal_df_filter['gold_3'] = cal_df_filter.groupby('instrument')['gold'].shift(3)
cal_df_filter['gold_cond1'] = np.where((cal_df_filter['gold']==1)&(cal_df_filter['dif']<0),1,0)
cal_df_filter['gold_cond2'] = np.where((cal_df_filter['dead_1']==1)&(cal_df_filter['dif_1']<0),1,0)
cal_df_filter['gold_cond3'] = np.where((cal_df_filter['gold_2']==1)&(cal_df_filter['dif_2']<0),1,0)
cal_df_filter['gold_cond4'] = np.where((cal_df_filter['dead_3']==1)&(cal_df_filter['dif_3']>0),1,0)
cal_df_filter['dead_cond1'] = np.where((cal_df_filter['dead']==1)&(cal_df_filter['dif']>0),1,0)
cal_df_filter['dead_cond2'] = np.where((cal_df_filter['gold_1']==1)&(cal_df_filter['dif_1']>0),1,0)
cal_df_filter['dead_cond3'] = np.where((cal_df_filter['dead_2']==1)&(cal_df_filter['dif_2']>0),1,0)
cal_df_filter['dead_cond4'] = np.where((cal_df_filter['gold_3']==1)&(cal_df_filter['dif_3']<0),1,0)
cal_df_filter['gold_bl'] =np.where(cal_df_filter['gold_cond1']+cal_df_filter['gold_cond2']+\
cal_df_filter['gold_cond3']+cal_df_filter['gold_cond4']>3,1,0)
cal_df_filter['dead_bl'] =np.where(cal_df_filter['dead_cond1']+cal_df_filter['dead_cond2']+\
cal_df_filter['dead_cond3']+cal_df_filter['dead_cond4']>3,1,0)
cal_df_filter[cal_df_filter.gold_bl>0]