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开发语言,可能就会遇到一些棘手的问题,比如电脑上不知不觉已经安装了多个python版本,python3.8/3.10/3.11,甚至一些软件中也集成有python解释器;那么我编写的python代码,到底是使用哪个解释器在执行?我通过pip包管理工具安装的依赖包到底在那个地方2024-05-05Python解析json时提示“string indices must be integers”问题解决方法
这篇文章主要介绍了Python解析json时提示“string indices must be integers”问题解决方法,结合实例形式分析了Python解析json字符串操作规范与相关使用技巧,需要的朋友可以参考下2019-07-07基于Python的网页自动化工具DrissionPage的使用详解
DrissionPage 是一个基于 python 的网页自动化工具,它既能控制浏览器,也能收发数据包,还能把两者合而为一,下面就跟随小编一起来学习一下它的具体使用吧2024-01-01Python 安装setuptools和pip工具操作方法(必看)
下面小编就为大家带来一篇Python 安装setuptools和pip工具操作方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-05-05
最新评论