Python绘制股票移动均线的实例

yipeiwu_com5年前Python基础

1. 前沿

移动均线是股票最进本的指标,本文采用numpy.convolve计算股票的移动均线

2. numpy.convolve

numpy.convolve(a, v, mode='full')

Returns the discrete, linear convolution of two one-dimensional sequences.

The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal [R17]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions.

If v is longer than a, the arrays are swapped before computation.

Parameters:

a : (N,) array_like

 First one-dimensional input array.

 v : (M,) array_like

 Second one-dimensional input array.

 mode : {‘full', ‘valid', ‘same'}, optional

 ‘full':

  By default, mode is ‘full'. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen.
 ‘same':

  Mode same returns output of length max(M, N). Boundary effects are still visible.
 ‘valid':

  Mode valid returns output of length max(M, N) - min(M, N) + 1. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect.



Returns:

out : ndarray

 Discrete, linear convolution of a and v.

计算公式:

eg:

>>> import numpy as np
>>> 
>>> np_list = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> 
>>> np_list
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> x = np.convolve(np_list, 2)
>>> x
array([ 2, 4, 6, 8, 10, 12, 14, 16, 18])
>>> x = np.convolve(np_list, [0.5, 0.5])
>>> x
array([ 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 4.5])

3. 移动均线计算

def moving_average(x, n, type='simple'):
 x = np.asarray(x)
 if type == 'simple':
  weights = np.ones(n)
 else:
  weights = np.exp(np.linspace(-1., 0., n))

 weights /= weights.sum()

 a = np.convolve(x, weights, mode='full')[:len(x)]
 a[:n] = a[n]
 return a
 ma10 = moving_average(close_data, 10, 'simple')
 ma20 = moving_average(close_data, 20, 'simple')

 ax1.plot(data['date'], ma10, color='c', lw=2, label='MA (10)')
 ax1.plot(data['date'], ma20, color='red', lw=2, label='MA (20)')

4. 效果图

以上这篇Python绘制股票移动均线的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用python turtle画高达

使用python turtle画高达

我就废话不多说了,直接上代码吧! import turtle t=turtle.Turtle() turtle.Turtle().screen.delay(0) tleft=turt...

python 迭代器和iter()函数详解及实例

python中迭代器和iter()函数 迭代器为类序列对象提供了一个类序列的接口。python的迭代无缝地支持序列对象,而且它还允许程序员迭代非序列类型,包括用户定义的对象。迭代器用起...

python迭代器实例简析

本文实例讲述了python迭代器的简单用法,分享给大家供大家参考。具体分析如下: 生成器表达式是用来生成函数调用时序列参数的一种迭代器写法 生成器对象可以遍历或转化为列表(或元组等数据结...

Python制作exe文件简单流程

Python制作exe文件简单流程

一:什么是exe? exe是Windows环境中的文件扩展名之一,它是一个可执行文件,虽然扩展程序在一般情况下是隐藏的,但是我们可以通过取消选中资源管理器文件夹的高级设置中的“不显示已注...

python快速编写单行注释多行注释的方法

python快速编写单行注释多行注释的方法

在python代码编写过程中,养成注释的习惯非常有用,可以让自己或别人后续在阅读代码时,轻松理解代码的含义。 如果只是简单的单行注释,可直接用“#”号开头,放于代码前面。 单行注释也可...