如何计算 R 中的指数移动平均线?
在本文中,我们将了解如何在 R 编程语言中计算指数移动平均线。
指数移动平均线 (EMA)告诉我们前 K 个数据点的加权平均值。 EMA 对最近的数据点赋予了更大的权重和重要性。为了获得 EMA,我们将使用 R 编程语言中的 pracma 包。要安装运行以下命令:
install.packages("pracma")
创建数据框进行演示
R
# create data frame
df <- data.frame(Rank=1:10,
Marks=c(65, 60, 54, 46, 37,
30, 29, 25, 24, 19))
# Display data frame
print(df)
R
library(pracma)
df <- data.frame(Rank=1:10,
Marks=c(65, 60, 54, 46, 37,
30, 29, 25, 24, 19))
# Exponentially weighted moving average
# using the 3 previous marks
df$EMA <- movavg(df$Marks, n=3, type='e')
# Display DataFrame
print(df)
R
library(ggplot2)
library(reshape2)
library(pracma)
df <- data.frame(Rank=1:10,
Marks=c(65, 60, 54, 46, 37,
30, 29, 25, 24, 19))
# Exponentially weighted moving average
# using the 3 previous marks
df$EMA <- movavg(df$Marks, n=3, type='e')
df <- melt(df , id.vars = 'Rank', variable.name = 'series')
ggplot(df, aes(Rank, value)) +
geom_line(aes(colour = series))
输出:
Rank Marks
1 1 65
2 2 60
3 3 54
4 4 46
5 5 37
6 6 30
7 7 29
8 8 25
9 9 24
10 10 19
计算 R 中的指数移动平均线
movavg()函数用于计算 R 中的 EMA。
movavg(x, n, type=c(“s”, “t”, “w”, “m”, “e”, “r”))
Arguments
- x: time series as numeric vector.
- n: backward window length.
- type: one of “s”, “t”, “w”, “m”, “e”, or “r”.
R
library(pracma)
df <- data.frame(Rank=1:10,
Marks=c(65, 60, 54, 46, 37,
30, 29, 25, 24, 19))
# Exponentially weighted moving average
# using the 3 previous marks
df$EMA <- movavg(df$Marks, n=3, type='e')
# Display DataFrame
print(df)
输出:
Rank Marks EMA
1 1 65 65.00000
2 2 60 62.50000
3 3 54 58.25000
4 4 46 52.12500
5 5 37 44.56250
6 6 30 37.28125
7 7 29 33.14062
8 8 25 29.07031
9 9 24 26.53516
10 10 19 22.76758
EMA 的可视化
在这里,我们将通过折线图将标记与 3 天指数加权移动平均线进行比较。
R
library(ggplot2)
library(reshape2)
library(pracma)
df <- data.frame(Rank=1:10,
Marks=c(65, 60, 54, 46, 37,
30, 29, 25, 24, 19))
# Exponentially weighted moving average
# using the 3 previous marks
df$EMA <- movavg(df$Marks, n=3, type='e')
df <- melt(df , id.vars = 'Rank', variable.name = 'series')
ggplot(df, aes(Rank, value)) +
geom_line(aes(colour = series))
输出: