量化分析(7)——移动均线、macd线

我们看股票一般看10日、20日的移动均线图。macd线也是一个很好的参考,以前很喜欢看macd曲线,觉得这条线很神奇,不过我一般不在金叉和死叉买,我喜欢在金叉之前买和死叉之前卖出。
先放一个方法作为单独的py文件,这里存放移动均线的方法。方法一是移动均线、方法二是权重移动均线,方法三是指数移动均线。

# -*- coding: utf-8 -*-
"""
Created on Wed Oct 18 18:03:57 2017

@author: Administrator
"""
import pandas as pd
import numpy as np
#移动均线
def smaCal(tsPrice,k):
    Sma=pd.Series(0.0,index=tsPrice.index)
    for i in range(k-1,len(tsPrice)):
        Sma[i]=sum(tsPrice[(i-k+1):(i+1)])/k
    return(Sma)
#权重移动均线
def wmaCal(tsPrice,weight):
    k=len(weight)
    arrWeight=np.array(weight)
    Wma=pd.Series(0,index=tsPrice.index)
    for i in range(k-1,len(tsPrice.index)):
        Wma[i]=sum(arrWeight*tsPrice[(i-k+1):(i+1)])
    return(Wma)
#指数移动均线
def ewmaCal(tsPrice,period=5,exponential=0.2):
    Ewma=pd.Series(0.0,index=tsPrice.index)
    Ewma[period-1]=np.mean(tsPrice[:period])
    for i in range(period,len(tsPrice)):
        Ewma[i]=exponential*tsPrice[i]+(1-exponential)*Ewma[i-1]
    return(Ewma)

接下来使用这个方法来看十日移动均线:

import sys
sys.path.append('C:\\Users\\Administrator\\Desktop\\Lianghua')
import movingAverage as ma
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
my_data2=ts.get_k_data('600600')
my_data2.index=my_data2.iloc[:,0]
my_data2.index=pd.to_datetime(my_data2.index,format='%Y-%m-%d')
sf_close=my_data2.close
ewma10=ma.ewmaCal(sf_close,10,0.2)
ax5=plt.subplot()
plt.plot(ewma10['2016'])

这里写图片描述

接着来看一下dif和dea图以及macd曲线的代码(这里显示的是2016年的数据):

# -*- coding: utf-8 -*-
"""
Created on Wed Oct 18 22:42:29 2017

@author: Administrator
"""

#画移动均线
import sys
sys.path.append('C:\\Users\\Administrator\\Desktop\\Lianghua')
import movingAverage as ma
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
my_data2=ts.get_k_data('600600')
my_data2.index=my_data2.iloc[:,0]
my_data2.index=pd.to_datetime(my_data2.index,format='%Y-%m-%d')
sf_close=my_data2.close
#ewma10=ma.ewmaCal(sf_close,10,0.2)
#ax5=plt.subplot()
#plt.plot(ewma10['2016'])

#画macd移动均线
DIF=ma.ewmaCal(sf_close,12,2/(1+12))-ma.ewmaCal(sf_close,26,2/(1+26))
DEA=ma.ewmaCal(DIF,9,2/(1+9))
MACD=DIF-DEA

#画图
plt.rcParams['font.sans-serif']=['SimHei']
plt.subplot(211)
plt.plot(DIF['2016'],label="DIF",color='k')
plt.plot(DEA['2016'],label="DEA",color='b',linestyle='dashed')
plt.title("信号线DIF和DEA")
plt.legend()

plt.subplot(212)
plt.bar(left=MACD['2016'].index,height=MACD['2016'],label='MACD',color='r')
plt.legend()

这里写图片描述

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值