日线定义
常见移动均线有5天、10天、30天、60天、120天。其中5天、10天是短期均线参考,作为日均线指标。
30天、60天指标是中期均线指标,作为季均线指标。
120天、240天是长期均线指标,作为年均线指标。
金叉和死叉
金叉是指短期均线上穿长期均线,是买入信号。
死叉是指短期均线下穿长期均线,是卖出信号。
示例题目
1)获取000063从2018年1月1日开始到2019年底的历史数据,股票为赛为智能。
2)使用pandas计算出3日均线和20日均线
3)输出所有的金叉日期和死叉均线
4)假设有10w,则计算按照金叉买入,死叉卖出的规则,这两年的盈利情况。
import numpy as np
import tushare as ts
import pandas as pd
ts.get_hist_data("300044", start = "2018-05-14", end = "2019-12-31").to_csv("d:/300044.csv")
df = pd.read_csv("d:/300044.csv", index_col="date", parse_dates=["date"])
df["ma3"] = np.NaN
#for i in range(3, len(df)):
# df.loc[df.index[i] ,"ma3"] = df["close"][i-2:i+1].mean()
df["ma3"] = df["open"].rolling(3).mean()
df = df.dropna()
golden_cross = []
dead_cross = []
for i in range(1, len(df)):
if (df["ma3"][i] >= df["ma20"][i]) and (df["ma3"][i - 1] < df["ma20"][i-1]):
golden_cross.append(df.index[i])
for i in range(1, len(df)):
if (df["ma3"][i] <= df["ma20"][i]) and (df["ma3"][i - 1] > df["ma20"][i-1]):
dead_cross.append(df.index[i])
print(golden_cross)
print(dead_cross)
first_money = 100000
money = first_money
hold = 0
sr1 = pd.Series(1, index=golden_cross)
sr2 = pd.Series(0, index=dead_cross)
sr = sr1.append(sr2).sort_index()
print(sr)
for i in range(0, len(sr)):
price = df["open"][sr.index[i]]
if sr.iloc[i] == 1:
buy = money // (price * 100)
hold += buy * 100
money -= buy * 100 * price
print(sr.index[i], "buy socket, price:", price, "spent money:", buy * 100 * price)
else:
money += price * hold
hold = 0
print(sr.index[i], "sell socket, price:", price, " money:", money)
price = df["open"][-1]
now_money = money + price * hold
print("my income:", now_money - first_money)
回测证明,按照金叉买进,死叉卖出方式并不能保证赚钱,我们使用赛为智能作为标的,测试了从2018年5月14日至2019年底的数据,投入10W,亏损7.5万,仅剩2.5万不到,可以说是亏的只剩裤衩了!
如果您喜欢这篇文章,别忘了点赞和评论哦!