需求:双均线策略制定¶
1.使用tushare包获取某股票的历史行情数据
2.计算该股票历史数据的5日均线和30日均线
什么是均线?
对于每一个交易日,都可以计算出前N天的移动平均值,然后把这些移动平均值连起来,成为一条线,就叫做N日移动平均线。移动平均线常用线有5天、10天、30天、60天、120天和240天的指标。
5天和10天的是短线操作的参照指标,称做日均线指标;
30天和60天的是中期均线指标,称做季均线指标;
120天和240天的是长期均线指标,称做年均线指标。
均线计算方法:MA=(C1+C2+C3+...+Cn)/N C:某日收盘价 N:移动平均周期(天数)
3.分析输出所有金叉日期和死叉日期
股票分析技术中的金叉和死叉,可以简单解释为:
分析指标中的两根线,一根为短时间内的指标线,另一根为较长时间的指标线。
如果短时间的指标线方向拐头向上,并且穿过了较长时间的指标线,这种状态叫“金叉”;
如果短时间的指标线方向拐头向下,并且穿过了较长时间的指标线,这种状态叫“死叉”;
一般情况下,出现金叉后,操作趋向买入;死叉则趋向卖出。当然,金叉和死叉只是分析指标之一,要和其他很多指标配合使用,才能增加操作的准确性。
4.如果我从假如我从2010年1月1日开始,初始资金为100000元,金叉尽量买入,死叉全部卖出,则到今天为止,我的炒股收益率如何?
分析:
买卖股票的单价使用开盘价
买卖股票的时机
最终手里会有剩余的股票没有卖出去
会有。如果最后一天为金叉,则买入股票。估量剩余股票的价值计算到总收益。
剩余股票的单价就是用最后一天的收盘价。
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
df = ts.get_k_data('000001',start='1990-01-01')
df.head()
df.info()
df['date'] = pd.to_datetime(df['date'])
df.info()
df.set_index('date',inplace=True)
df.head()
df['code'] = df['code'].astype('int')
df.info()
ma5 = df['close'].rolling(5).mean()
ma30 = df['close'].rolling(30).mean()
df['ma5'] = ma5
df['ma30'] = ma30
df.head()
data = df[30:]
plt.plot(data['ma5'][100:200],label='ma5')
plt.plot(data['ma30'][100:200],label='ma30')
plt.legend()
s1 = ma5 > ma30
s2 = ma5 < ma30
s3 = s2.shift(1)
death_cross_time = data.loc[s1&s3].index
golden_cross_time = data.loc[~(s1|s3)].index
new_df = data['2010':'2020']
new_df
s1 = ma5 < ma30
s2 = ma5 > ma30
s3 = s2.shift(1)
death_cross_time = new_df.loc[s1&s3].index
golden_cross_time = new_df.loc[~(s1|s3)].index
death_cross_time
first_money = 100000
cost_money = 100000
s1 = pd.Series(data=1,index=golden_cross_time)
s2 = pd.Series(data=0,index=death_cross_time)
s = s1.append(s2)
s = s.sort_index()
s
hold = 0
for i in range(len(s)):
if s[i] == 1:
date = s.index[i]
price = new_df.loc[date]['open']
hand_count = cost_money // (100*price)
hold = hand_count*100
cost_money -= hold * price
else:
death_time = s.index[i]
sell_price = new_df.loc[death_time]['open']
cost_money += (sell_price*hold)
hold = 0
last_price = new_df['open'][-1]
last_money = hold * last_price
print('总收益:',cost_money+last_money-first_money)
总收益: 426296.2999999997