主旨思想:
金叉主要指股票行情指标的短期线向上穿越长期线的交叉,反之当行情指标的短期线向下穿越长期线的交叉,称之为死叉。
实现方法
当x日的移动平均线上升并且交叉穿过Y日的移动平均线的时候买入
当x日的移动平均线下降并且交叉穿过Y日的移动平均线的时候卖出
python实现
import psycopg2
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def query_sql(sql):
conn = psycopg2.connect(database='quant', host='10.211.55.20', port='5432', user='kiwi',password='xx')
conn.set_client_encoding('utf-8')
cursor = conn.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
return rows
sql = """
select trade_date,sec_code,open_price,curr_price,high_price,low_price,trade_vol from sec_quotation_his where sec_code='600030'
and trade_date >= '2020-07-01'
and trade_date < '2020-11-01'
order by 1;
"""
rows = query_sql(sql)
df = pd.DataFrame(rows,columns=['trade_date','sec_code','open_price','curr_price','high_price','low_price','trade_vol'])
# 5日平均
df['SMA5'] = df['curr_price'].rolling(window=5).mean()
# 10日平均
df['SMA10'] = df['curr_price'].rolling(window=10).mean()
# 20日平均
df['SMA20'] = df['curr_price'].rolling(window=20).mean()
#设定索引为交易日
#df.set_index('trade_date',inplace=True)
# 基于索引进行查询
#df.loc['2020-10-09']
# 画图
#df[['curr_price','SMA5','SMA10','SMA20']].plot(figsize = (18,6),grid = True)
# 计算回归
df['yes_price'] = df['curr_price'].shift(1)
# 连续收益率
df['return'] = np.log((df['curr_price']/df['yes_price']).astype('float'))
# 离散收益率
df['return_dis'] = df['curr_price']/df['yes_price'] - 1
df['return_dis2'] = df['curr_price'].astype('float').pct_change()
# 删除NA数据
df = df.dropna(axis=0,how='any')
# 计算金叉
df['position'] = np.where(df['SMA5'] > df['SMA20'],1,-1)
df['position'].plot(figsize = (18,6),grid = True)
print(df[['trade_date','position']])
#df['return'].cumsum().apply(np.exp).plot(figsize = (18,6),grid = True)
plt.show()