python编写移动平均

Trading softwares come with different types of moving averages already pre-installed and ready to charted. But it can be interesting to understand how to calculate these moving averages so as to be able to use them when you’re back-testing potential strategies.

交易软件带有不同类型的移动平均线,这些移动平均线已经预先安装并可以绘制图表。 但是,了解如何计算这些移动平均值,以便在对潜在策略进行回测时能够使用它们,可能会很有趣。

If you want a do-it-yourself method, then the below will surely interest you. All that is needed is a python interpreter such as SPYDER. The different “known” types of moving averages are:

如果您想自己动手做,那么下面的内容一定会让您感兴趣。 所需要的只是一个Python解释器,例如SPYDER。 移动平均的不同“已知”类型为:

  • Simple moving average.

    简单的移动平均线。

  • Exponential moving average.

    指数移动平均线。

  • Smoothed moving average.

    平滑的移动平均线。

  • Linear-weighted moving average.

    线性加权移动平均线。

We will go through each one, define it, code it, and chart it.

我们将仔细研究,定义,编码和绘制图表。

简单移动平均线 (Simple moving average)

As the name suggests, this is your plain simple average that is used everywhere in statistics and basically any other part in our lives. It is simply the total values of the observations divided by the number of observations.

顾名思义,这是您的简单平均数,可用于统计数据中以及我们生活中的其他任何部分。 它只是观测值的总值除以观测值的数量。

Mathematically speaking, it can be written down as:

从数学上讲,它可以记为:

In python, we can define a function that calculates moving averages as follows:

在python中,我们可以定义一个函数来计算移动平均值,如下所示:

def ma(Data, period, onwhat, where):

    for i in range(len(Data)):            try:                Data[i, where] = (Data[i - period:i + 1, onwhat].mean())

            except IndexError:                pass    return Data

The function takes your data structure represented by the Data variable, the moving average period (20, 60, 200, etc.) represented by the period variable, what do you want to apply it on (on OHLC data structures, choose 3 for close prices because python indexing starts at zero) represented by the onwhat variable, and the where variable is where do you want the moving average column to appear. Note that you must have an array of more than 4 columns for this to work, because it doesn’t automatically create a new column, but simply populate it.

该功能把你的数据结构表示由数据变量,移动平均周期(20,60,200,等) 期间变量表示,要应用它在做什么(上OHLC数据结构,选择3紧密价格(因为python索引从零开始)由onwhat变量表示,而where变量是您希望移动平均列显示的位置。 请注意,您必须具有超过4列的数组才能起作用,因为它不会自动创建新列,而只是填充它。

EURUSD Daily time horizon with 200-Day simple moving average.
EURUSD每日时间范围与200天简单移动平均线。

指数移动平均线 (Exponential moving average)

As opposed to the simple moving average that gives equal weights to all observations, the exponential moving average gives more weight to the more recent observations. It reacts more than the simple moving average with regards to recent movements.

与简单的移动平均线赋予所有观察值相同的权重相反,指数移动平均线赋予较新的观察值更多的权重。 对于最近的走势,它的React比简单的移动平均数还要多。

Mathematically speaking, it can be written down as:

从数学上讲,它可以记为:

The smoothing factor is often 2. Note, that if we increase the smoothing factor (also known as alpha) then, the more recent observations will have more weight.

平滑因子通常为2。请注意,如果我们增加平滑因子(也称为alpha),则最近的观测值将具有更大的权重。

In python language, we can define a function that calculates the EMA as follows:

在python语言中,我们可以定义一个计算EMA的函数,如下所示:

def ema(Data, alpha, window, what, whereSMA, whereEMA):

    # alpha is the smoothing factor    # window is the lookback period    # what is the column that needs to have its average calculated    # where is where to put the exponential moving average

    alpha = alpha / (window + 1.0)    beta  = 1 - alpha

    # First value is a simple SMA    Data[window - 1, whereSMA] = np.mean(Data[:window - 1, what])

    # Calculating first EMA    Data[window, whereEMA] = (Data[window, what] * alpha) + (Data[window - 1, whereSMA] * beta)# Calculating the rest of EMA    for i in range(window + 1, len(Data)):            try:                Data[i, whereEMA] = (Data[i, what] * alpha) + (Data[i - 1, whereEMA] * beta)

            except IndexError:                pass    return Data

The function is self-explanatory as it merely reproduces the EMA function presented above.

该函数是不言自明的,因为它仅复制了上面介绍的EMA函数。

EURUSD Daily time horizon with 200-Day exponential moving average.
EURUSD每日时间范围和200天指数移动平均线。

平滑的移动平均线 (Smoothed moving average)

This moving average takes into account the general picture and is less impacted by recent movements. It’s my favourite trend-following indicator. Mathematically speaking, it can be found by simply multiplying the Days variable in the EMA function by 2 and subtract 1. This means that to transform an exponential moving average into a smoothed one, we follow this equation in python language, that transforms the exponential moving average into a smoothed one:

该移动平均线考虑了总体情况,受近期走势的影响较小。 这是我最喜欢的趋势跟踪指标。 从数学上来说,可以通过将EMA函数中的Days变量乘以2并减去1来找到。这意味着要将指数移动平均值转换为平滑的均值,我们使用python语言遵循此方程式,从而转换了指数移动平均成一个平滑的:

smoothed = (exponential * 2) - 1 # From exponential to smoothed
EURUSD Daily time horizon with 200-Day smoothed moving average.
EURUSD 200天平滑移动平均线的每日时间范围。

线性加权移动平均 (Linear-weighted moving average)

It is a simple moving average that places more weight on recent data. The most recent observation has the biggest weight and each one prior to it has a progressively decreasing weight. Intuitively, it has less lag than the other moving averages but it’s also the least used, and hence, what it gains in lag reduction, it loses in popularity.

这是一个简单的移动平均线,对近期数据有更多的重视。 最近的观测值具有最大的权重,而在此之前的每个观测值的权重都逐渐减小。 从直觉上讲,它的滞后性比其他移动平均线要小,但使用最少,因此,减少滞后所获得的好处就不受欢迎了。

Mathematically speaking, it can be written down as:

从数学上讲,它可以记为:

In python language, we can define a function that calculates moving averages as follows:

在python语言中,我们可以定义一个函数来计算移动平均值,如下所示:

def lwma(Data, period):    weighted = []    for i in range(len(Data)):            try:                total = np.arange(1, period + 1, 1) # weight matrix

                matrix = Data[i - period + 1: i + 1, 3:4]                matrix = np.ndarray.flatten(matrix)                matrix = total * matrix # multiplication                wma = (matrix.sum()) / (total.sum()) # WMA                weighted = np.append(weighted, wma) # add to array            except ValueError:                pass    return weighted
EURUSD Daily time horizon with 200-Day weighted moving average.
EURUSD每日时间范围和200天加权移动平均线。

Basically, if we have a dataset composed of two numbers [1, 2] and we want to calculate a linear weighted average, then we will do the following:

基本上,如果我们有一个由两个数字[1、2]组成的数据集,并且想要计算线性加权平均值,那么我们将执行以下操作:

  • (2 x 2) + (1 x 1) = 5(2 x 2)+(1 x 1)= 5
  • 5 / 3 = 1.665/3 = 1.66

This assumes a time series with the number 2 as being the most recent observation.

这假定数字为2的时间序列是最近的观测值。

结论 (Conclusion)

So, which one to choose? That question is left to the risk profile of the trader and her familiarity with the moving average. Some prefer plain simple moving averages while others try to dig deeper by using combinations of exponential and smoothed moving averages. It all depends on you to find your favourite one. My advice? Consider longer-term moving averages.

那么,选择哪一个呢? 这个问题留给交易者的风险状况以及她对移动平均线的熟悉程度。 一些人更喜欢简单的简单移动平均线,而另一些人则试图通过使用指数移动平均线和平滑移动平均线的组合来更深入地研究。 这完全取决于您找到自己喜欢的一个。 我的建议? 考虑长期移动平均线。

https://pixabay.com/photos/trading-analysis-forex-chart-643722/https://pixabay.com/photos/trading-analysis-forex-chart-643722/

翻译自: https://towardsdatascience.com/how-to-code-different-types-of-moving-averages-in-python-4f8ed6d2416f

python编写移动平均


http://www.taodudu.cc/news/show-4043403.html

相关文章:

  • 使用DAX(Power BI)的移动平均线
  • python 移动平均线_Python中的SMA(短期移动平均线)
  • SMA(简单移动平均线)
  • 统计学分析公式 MA移动平均线
  • 为新开的餐厅设计网站html,18个以餐饮美食为主题的优秀网页设计
  • H5 HTML 移动端触摸拖拽drag drop 自定义拖拽样式 使用PointerEvent模拟的拖拽方案
  • Angular cdk 学习之 drag-drop
  • vue drag函数拖拽效果实现
  • Vue 拖拽缩放组件 vue-drag-resize属性
  • Android使用DragAndDrop拖拽效果实现宫格位置变换
  • Js学习之拖拉事件(drag)
  • d3.js学习笔记(5)drag拖拽操作数据
  • H5--drag拖拽事件
  • android游戏备份农场,zynga旗下的虚拟农场farmville将正式进入android平台
  • Zynga完成对快速增长的超休闲游戏领域的领导者——伊斯坦布尔的Rollic的收购
  • Zynga旗下魔法三消手机游戏《Harry Potter: Puzzles Spells》邀请玩家一起参加最新推出的游戏内系列活动——俱乐部挑战赛
  • Zynga的数据分析
  • 解密Zynga:专注 流水线 数据控
  • Zynga发布魔法三消手游《Harry Potter: Puzzles Spells》
  • Zynga就收购顶尖移动设备游戏《Toon Blast》和《Toy Blast》的开发商伊斯坦布尔Peak公司达成协议
  • Zynga任命Noel Watson为董事会成员
  • 曹金明:Zynga大败局--数据控是如何把游戏做败的
  • Zynga和StarLark庆祝《Golf Rival》面世四周年
  • Zynga将Cocos2D-X移植到Emscripten
  • Zynga和Unity:独家奖励广告
  • 创造下一个Zynga传奇
  • Zynga以特别的《CSR Racing 2》系列活动庆祝布加迪110周年
  • 游戏出海Get,TikTok联手Zynga推出一款基于HTML5打造的手机游戏
  • Zynga重返公有云 是否大势所趋
  • Zynga公布2019年第三季度财务业绩

python编写移动平均_如何在Python中编写不同类型的移动平均线。相关推荐

  1. python 字节流分段_如何在Python中编写简单代码,并且速度超越Spark?

    全文共 3482字,预计学习时长 7分钟 如今,大家都在Python工具(pandas和Scikit-learn)的简洁性.Spark和Hadoop的可扩展性以及Kubernetes的操作就绪之间做选 ...

  2. python 线性回归模型_如何在Python中建立和训练线性和逻辑回归ML模型

    python 线性回归模型 Linear regression and logistic regression are two of the most popular machine learning ...

  3. python mqtt库_如何在 Python 中使用 MQTT

    Python 是一种广泛使用的解释型.高级编程.通用型编程语言.Python 的设计哲学强调代码的可读性和简洁的语法(尤其是使用空格缩进划分代码块,而非使用大括号或者关键词).Python 让开发者能 ...

  4. unbantu上python安装步骤_如何在Ubuntu中安装Python 3.6?

    Python是增长最快的主要通用编程语言.原因有很多,比如它的可读性和灵活性,易于学习和使用,可靠和高效. 有两个主要的Python版本被使用- 2和3 (Python的现在和未来);前者将看不到新的 ...

  5. python进程暂停_如何在Python中暂停多进程?

    我希望用户能够在怎么开始的实现它?在 我的代码是:# -*- coding: utf-8 -*- from PySide import QtCore, QtGui from Ui_MainWindow ...

  6. python 拟合正态分布_如何在Python中拟合双高斯分布?

    我试图使用Python获得数据(link)的双高斯分布.原始数据的格式为: 对于给定的数据,我想获得图中所示峰值的两个高斯分布.我用以下代码(source)进行了尝试:from sklearn imp ...

  7. python 概率分布函数_如何在Python中实现这五类强大的概率分布

    匿名用户 1级 2016-04-25 回答 首页 所有文章 观点与动态 基础知识 系列教程 实践项目 工具与框架应用 工具资源 伯乐在线 > Python - 伯乐在线 > 所有文章 &g ...

  8. python 获取当前目录_如何在Python中获取当前的工作目录?

    python 获取当前目录 To get the current working directory in Python, there is a library function getcwd() i ...

  9. eclipse配置python开发环境_如何在Eclipse中配置python开发环境

    展开全部 步骤1: 下载用于在2113Eclipse中开发Python的插件PyDev. 步骤2: 解压5261python.将解压后的features和plugins文件4102夹中的1653内容拷 ...

  10. win10系统64位安装python什么版本_如何在win10中安装Python

    本文主要讲解win10如何安装python,希望对初学的小伙伴有帮助.环境:win 10 64位操作系统1.python下载https://www.python.org/downloads/2.x和3 ...

最新文章

  1. 安装.Net的痛苦经历!
  2. iOS 加密的3种方法
  3. Python 学习第三部分函数——第一章函数基础
  4. GraphQL入门之graphql-java项目的介绍
  5. Objective-C之MRC、ARC模式下,属性修饰关键字strong、retain、assign、weak的区别和联系...
  6. WPF在代码中创建DataTemplate时候的异常
  7. 进程与服务的签名_服务器被黑客攻击后如何查找溯源攻击
  8. 单目相机 svd 从图像恢复3维位置_IMU辅助下的单目视觉坐标传递
  9. 译DevExpress v16.1更新说明(WinForms篇)
  10. python中的三种排序方法,使用冒泡对列表排序,使用自带sort方法进行排序
  11. 51单片机温度控制系统报警器,不会做课程设计的就拿走
  12. 噫吁嚱!文言文亦能编程!此诚年度最骚语言也
  13. 什么是diff算法?
  14. 【正点原子FPGA连载】第三章 硬件资源详解 -摘自【正点原子】新起点之FPGA开发指南_V2.1
  15. ABAP ALV详细教程(二)
  16. ECShop 替换手机版购物首页(2)
  17. Cisco AAA 配置
  18. 【天天读书】2023 年,科技行业的创业者们推荐这 47 本书 | 创始人书单
  19. 软件项目管理实践经验谈
  20. Ajax 传递数组、表单+

热门文章

  1. 【构建更好的软件—TeamDev】上海道宁为您带来强大且富有洞察力的TeamDev产品及自定义解决方案
  2. 【实验分享】通过Console口登录到Cisco设备
  3. 谈谈我职业生涯中的三次潦倒--Leo病中的思考 续
  4. 皮影机器人ppt_机器人皮影戏装置的制作方法
  5. SQL高级查询—实验报告
  6. mysql tp5时间倒叙_tp5(thinkPHP5框架)时间查询操作实例分析
  7. 什么是谷歌趋势(Google Trends)
  8. 车载以太网 PHY 物理层测试TC8 测试需求
  9. (很详细的)数据库Transact-SQL语句:数据查询(基本查询、嵌套查询、连接查询)
  10. asp.net web压力测试