金融量化分析-金叉和死叉
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tushare as ts
#从tushare库中获取闻泰科技股票K信息,从20190101至今,并保存为csv
df = ts.get_k_data('600745',start='2019-01-01')#
df.to_csv('600745.csv')
#利用pandas读取csv,将date列作为索引导入,并选取所需要的列
df = pd.read_csv("600745.csv", index_col='date',parse_dates=['date'])[['open','close','low','high']]
#创建两列为控制
df['ma5'] = np.nan
df['ma30'] = np.nan
# 计算5日均线和30日均线值
#方法一
# for i in range(4,len(df)):
# df.loc[df.index[i],'ma5'] = df['close'][i-4:i+1].mean()
# for i in range(29,len(df)):
# df.loc[df.index[i],'ma30'] = df['close'][i-29:i+1].mean()
#方法二,以开盘价为计算标准
df['ma5'] = df['open'].rolling(5).mean()
df['ma30'] = df['open'].rolling(30).mean()
#截取相应的值,进行绘图
df = df[:]
df[['close','ma5','ma30']].plot()
#plt.show()
#获取金叉日期和死叉日期,今天的值与昨天的值进行对比
#故先删除没有值的行
df = df.dropna()
#本处利用两种方法,第一种循环比较,将比较好的值传入列表当中
golden_cross = []
death_cross = []
for i in range(1,len(df)):
if df['ma5'][i] >= df['ma30'][i] and df['ma5'][i-1] < df['ma30'][i-1]:
golden_cross.append(df.index[i])
if df['ma5'][i] <= df['ma30'][i] and df['ma5'][i-1] > df['ma30'][i-1]:
death_cross.append(df.index[i])
#方法二 布尔值方法,shift移动列表后进行比较,得到对应的日期
#str1 = df['ma5'] < df['ma30']
#str2 = df['ma5'] >= df['ma30']
#death_cross = df[str1 & str2.shift(1)].index
#golden_cross = df[~(str1 | str2.shift(1))].index
#golden_cross
#策略目标,在出现金叉的时候按当日最高价格买入,出现死叉的日期按当日最低价卖出。
first_money = 10000
money = first_money
hold = 0 #持有多少股
# 将金叉日期与死叉日期进行合并,从新排序后,对其进行循环
sr1 = pd.Series(1, index=golden_cross)
sr2 = pd.Series(0, index=death_cross)
sr = sr1.append(sr2).sort_index()
for i in range(0, len(sr)):
p = df['high'][sr.index[i]]
if sr.iloc[i] == 1:
#金叉
buy = (money // (100*p))
hold += buy*100
money -= buy*100*p
else:
money += hold * p
hold = 0
p = df['low'][-1]
now_money = hold * p + money
print(now_money - first_money)