要求: 1. 使用tushare包获取某股票的历史行情数据 2. 使用pandas包计算该股票历史数据的5日均线和30日均线 3. 使用matplotlib包可视化历史数据的收盘价和两条均线 4. 分析输出所有金叉日期和死叉日期 5. 如果我从2010年1月1日开始,初始资金为100000元。金叉尽量买入,死叉全部卖出,则到今天为止,我的股票收益率为多少??
import numpy as np
import pandas as pd
import matplotlib as plt
import tushare as ts
# 获取财经数据
df = ts.get_k_data("601318",start="2000-01-01")
df.to_csv("601318.csv")
# 读取财经数据并计算五日、三十日的平均收盘价
df = pd.read_csv("601318.csv",index_col = 'date',parse_dates = ['date'])[['open','close','low','high']]
df['ma5'] = df['close'].rolling(5).mean()
df['ma30'] = df['close'].rolling(30).mean()
df[['close','ma5','ma30']].plot()
# 获取金叉和死叉的日期
ar1 = df['ma5'] < df['ma30']
ar2 = df['ma5'] >= df['ma30']
death_cross = df[ar1 & ar2.shift(1)].index
golden_cross = df[-(ar1 | ar2.shift(1))].index
# 执行交易策略
first_money = 100000
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['open'][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['open'][-1]
now_money = hold * p + money
print(now_money)
|