雙均線分析示例

日線定義

常見移動均線有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萬不到,可以說是虧的只剩褲衩了!

 

 

如果您喜歡這篇文章,別忘了點贊和評論哦!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章