How to Calculate an Exponential Moving Average in Pandas

admin3个月前技术分析143

In time series analysis, a moving average is simply the average value of a certain number of previous periods.

An exponential moving average is a type of moving average that gives more weight to recent observations, which means it’s able to capture recent trends more quickly.

This tutorial explains how to calculate an exponential moving average for a column of values in a pandas DataFrame.

Example: Exponential Moving Average in Pandas

Suppose we have the following pandas DataFrame:

import pandas as pd#create DataFramedf = pd.DataFrame({'period': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                   'sales': [25, 20, 14, 16, 27, 20, 12, 15, 14, 19]})#view DataFrame df

        period	sales
0	1	25
1	2	20
2	3	14
3	4	16
4	5	27
5	6	20
6	7	12
7	8	15
8	9	14
9	10	19

We can use the pandas.DataFrame.ewm() function to calculate the exponentially weighted moving average for a certain number of previous periods.

For example, here’s how to calculate the exponentially weighted moving average using the four previous periods:

#create new column to hold 4-day exponentially weighted moving averagedf['4dayEWM'] = df['sales'].ewm(span=4, adjust=False).mean()#view DataFrame df

        period	sales	4dayEWM
0	1	25	25.000000
1	2	20	23.000000
2	3	14	19.400000
3	4	16	18.040000
4	5	27	21.624000
5	6	20	20.974400
6	7	12	17.384640
7	8	15	16.430784
8	9	14	15.458470
9	10	19	16.875082

We can also use the matplotlib library to visualize the sales compared to the 4-day exponentially weighted moving average:

import matplotlib.pyplot as plt#plot sales and 4-day exponentially weighted moving average plt.plot(df['sales'], label='Sales')
plt.plot(df['4dayEWM'], label='4-day EWM')#add legend to plotplt.legend(loc=2)

Exponentially weighted moving average in pandas

Additional Resources


相关文章

死亡谷谷底特征

 1. eth/btc 汇率掉到0.04以下2. eth bsc heco sol 等defi 生态平均apy 跌到10...

关于移仓

1. 大家和我一样投的是u本位季度合约。6月底合约到期要转仓。可以转到9月。也可以把合约转为现货。你目前合约的仓位是多少,就买多少价值的现货。2. 当你有一定比例的现货之后,你下次再开始定投的话。可以...

基于ahr999定投的回测

基于ahr999定投的回测

回测条件s_date = '2022-01-01'  # 定投开始时间 e_date = '2023-1...

经典八大交易系统

一、海龟交易系统核心交易思想:当价格突破20个交易周期最高点的时候入场。当价格跌破10个交易周期最低点时离场。系统一:入场:以20日突破为基础的偏短线系统 (价格超过前20天的最高价或最低价 )离场:...

【MobaXterm】设置保持SSH连接

【MobaXterm】设置保持SSH连接

1.MobaXterm如果使用了MobaXterm客户端,那么需要在设置里点选setting>SSH>sessions setting>勾选ssh Keepalivekeepaliv...

期权复习

我卖的tsla put 170的这周稳收了5u 相当于赚了5/170=3% 一周给账户额外增加了3%的额外收益这个如果你们账户里有闲置资金 可以做 风险较低策略 卖put他的意义就是万一股票跌到什么价...