📜  如何在Python中计算移动平均线?

📅  最后修改于: 2022-05-13 01:55:13.397000             🧑  作者: Mango

如何在Python中计算移动平均线?

在本文中,我们将了解如何在Python中计算移动平均线。移动平均是指一组观测值的固定大小子集的一系列平均值。它也被称为滚动平均、运行平均、滚动平均或运行平均。

考虑 n 个观测值的集合,k 是用于确定任何时间 t 的平均值的窗口大小。然后通过最初取当前窗口中存在的前 k 个观察值的平均值并将其存储在列表中来计算移动平均列表。现在,根据要确定的移动平均的条件扩展窗口,并再次计算窗口中存在的元素的平均值并将其存储在列表中。这个过程一直持续到窗口到达集合的末尾。

例如:给定一个包含五个整数 arr=[1, 2, 3, 7, 9] 的列表,我们需要计算列表的移动平均值,窗口大小指定为 3。我们将首先计算前 3 个元素的平均值,然后将存储为第一个移动平均线。然后窗口将向右移动一个位置,并再次计算窗口中存在的元素的平均值并将其存储在列表中。同样,该过程将重复,直到窗口到达数组的最后一个元素。以下是上述方法的说明:

下面是实现:

Python3
# Program to calculate moving average
arr = [1, 2, 3, 7, 9]
window_size = 3
  
i = 0
# Initialize an empty list to store moving averages
moving_averages = []
  
# Loop through the array to consider
# every window of size 3
while i < len(arr) - window_size + 1:
    
    # Store elements from i to i+window_size
    # in list to get the current window
    window = arr[i : i + window_size]
  
    # Calculate the average of current window
    window_average = round(sum(window) / window_size, 2)
      
    # Store the average of current
    # window in moving average list
    moving_averages.append(window_average)
      
    # Shift window to right by one position
    i += 1
  
print(moving_averages)


Python3
# Program to calculate moving average using numpy
  
import numpy as np
  
arr = [1, 2, 3, 7, 9]
window_size = 3
  
i = 0
# Initialize an empty list to store moving averages
moving_averages = []
  
# Loop through the array t o
#consider every window of size 3
while i < len(arr) - window_size + 1:
  
    # Calculate the average of current window
    window_average = round(np.sum(arr[
      i:i+window_size]) / window_size, 2)
      
    # Store the average of current
    # window in moving average list
    moving_averages.append(window_average)
      
    # Shift window to right by one position
    i += 1
  
print(moving_averages)


Python
# Python program to calculate
# simple moving averages using pandas
import pandas as pd
  
arr = [1, 2, 3, 7, 9]
window_size = 3
  
# Convert array of integers to pandas series
numbers_series = pd.Series(arr)
  
# Get the window of series
# of observations of specified window size
windows = numbers_series.rolling(window_size)
  
# Create a series of moving
# averages of each window
moving_averages = windows.mean()
  
# Convert pandas series back to list
moving_averages_list = moving_averages.tolist()
  
# Remove null entries from the list
final_list = moving_averages_list[window_size - 1:]
  
print(final_list)


Python
# Program to calculate cumulative moving average
# using numpy
  
import numpy as np
  
arr = [1, 2, 3, 7, 9]
  
i = 1
# Initialize an empty list to store cumulative moving
# averages
moving_averages = []
  
# Store cumulative sums of array in cum_sum array
cum_sum = np.cumsum(arr);
  
# Loop through the array elements
while i <= len(arr):
  
    # Calculate the cumulative average by dividing
    # cumulative sum by number of elements till 
    # that position
    window_average = round(cum_sum[i-1] / i, 2)
      
    # Store the cumulative average of
    # current window in moving average list
    moving_averages.append(window_average)
      
    # Shift window to right by one position
    i += 1
  
print(moving_averages)


Python
# Python program to calculate
# cumulative moving averages using pandas
import pandas as pd
  
arr = [1, 2, 3, 7, 9]
window_size = 3
  
# Convert array of integers to pandas series
numbers_series = pd.Series(arr)
  
# Get the window of series of
# observations till the current time
windows = numbers_series.expanding()
  
# Create a series of moving averages of each window
moving_averages = windows.mean()
  
# Convert pandas series back to list
moving_averages_list = moving_averages.tolist()
  
print(moving_averages_list)


Python
# Program to calculate exponential
# moving average using formula
  
import numpy as np
  
arr = [1, 2, 3, 7, 9]
x=0.5  # smoothening factor
  
i = 1
# Initialize an empty list to
# store exponential moving averages
moving_averages = []
  
# Insert first exponential average in the list
moving_averages.append(arr[0])
  
# Loop through the array elements
while i < len(arr):
  
    # Calculate the exponential
    # average by using the formula
    window_average = round((x*arr[i])+
                           (1-x)*moving_averages[-1], 2)
      
    # Store the cumulative average
    # of current window in moving average list
    moving_averages.append(window_average)
      
    # Shift window to right by one position
    i += 1
  
print(moving_averages)


Python
# Python program to
# calculate exponential moving averages
import pandas as pd
  
arr = [1, 2, 3, 7, 9]
  
# Convert array of integers to pandas series
numbers_series = pd.Series(arr)
  
# Get the moving averages of series
# of observations till the current time
moving_averages = round(numbers_series.ewm(
  alpha=0.5, adjust=False).mean(), 2)
  
# Convert pandas series back to list
moving_averages_list = moving_averages.tolist()
  
print(moving_averages_list)


输出:

[2.0, 4.0, 6.33]

简单移动平均线:

SMA 是通过在当前窗口中的某个时间获取 k(窗口大小)观察值的未加权平均值来计算的。它用于分析趋势。

公式:

SMAj = (1/k) * ∑ (i=j-1 to j+k-1)  ai

在哪里,

  • SMA j = 第 j 个窗口的简单移动平均线
  • k = 窗口大小
  • a i = 观察集的第 i 个元素

方法一:使用 Numpy

Python的 Numpy 模块提供了一种简单的方法来计算观察数组的简单移动平均值。它提供了一个名为 numpy.sum() 的方法,该方法返回给定数组的元素之和。可以通过找到窗口中存在的元素的总和并将其除以窗口大小来计算移动平均值。

Python3

# Program to calculate moving average using numpy
  
import numpy as np
  
arr = [1, 2, 3, 7, 9]
window_size = 3
  
i = 0
# Initialize an empty list to store moving averages
moving_averages = []
  
# Loop through the array t o
#consider every window of size 3
while i < len(arr) - window_size + 1:
  
    # Calculate the average of current window
    window_average = round(np.sum(arr[
      i:i+window_size]) / window_size, 2)
      
    # Store the average of current
    # window in moving average list
    moving_averages.append(window_average)
      
    # Shift window to right by one position
    i += 1
  
print(moving_averages)

输出:

[2.0, 4.0, 6.33]

方法 2:使用 Pandas

Python的 Pandas 模块提供了一种简单的方法来计算一系列观察值的简单移动平均值。它提供了一个名为 pandas.Series.rolling(window_size) 的方法,该方法返回指定大小的滚动窗口。可以通过对上面获得的窗口对象使用 pandas.Series.mean()函数来计算窗口的平均值。 pandas.Series.rolling(window_size) 将返回一些空系列,因为它需要至少 k 个(窗口大小)元素来滚动。

Python

# Python program to calculate
# simple moving averages using pandas
import pandas as pd
  
arr = [1, 2, 3, 7, 9]
window_size = 3
  
# Convert array of integers to pandas series
numbers_series = pd.Series(arr)
  
# Get the window of series
# of observations of specified window size
windows = numbers_series.rolling(window_size)
  
# Create a series of moving
# averages of each window
moving_averages = windows.mean()
  
# Convert pandas series back to list
moving_averages_list = moving_averages.tolist()
  
# Remove null entries from the list
final_list = moving_averages_list[window_size - 1:]
  
print(final_list)

输出:

[2.0, 4.0, 6.33]

累积移动平均线

CMA 是通过取计算时所有观测值的未加权平均值来计算的。它用于时间序列分析。

公式:

CMAt = (1/kt) * ∑ (i=0 to k)  ai

在哪里:

  • CMA t = 时间 t 的累积移动平均线
  • k t = 到时间 t 的观察次数
  • ai = 观察集的第 i 个元素

方法一:使用 Numpy

Python的 Numpy 模块提供了一种简单的方法来计算观察数组的累积移动平均值。它提供了一个名为 numpy.cumsum() 的方法,该方法返回给定数组元素的累积和的数组。可以通过将元素的累积总和除以窗口大小来计算移动平均值。

Python

# Program to calculate cumulative moving average
# using numpy
  
import numpy as np
  
arr = [1, 2, 3, 7, 9]
  
i = 1
# Initialize an empty list to store cumulative moving
# averages
moving_averages = []
  
# Store cumulative sums of array in cum_sum array
cum_sum = np.cumsum(arr);
  
# Loop through the array elements
while i <= len(arr):
  
    # Calculate the cumulative average by dividing
    # cumulative sum by number of elements till 
    # that position
    window_average = round(cum_sum[i-1] / i, 2)
      
    # Store the cumulative average of
    # current window in moving average list
    moving_averages.append(window_average)
      
    # Shift window to right by one position
    i += 1
  
print(moving_averages)

输出:

[1.0, 1.5, 2.0, 3.25, 4.4]

方法 2:使用 Pandas

Python的 Pandas 模块提供了一种简单的方法来计算一系列观察值的累积移动平均值。它提供了一个名为 pandas.Series.expanding() 的方法,该方法返回一个跨越时间 t 之前的所有观察值的窗口。可以通过对上面获得的窗口对象使用 pandas.Series.mean()函数来计算窗口的平均值。

Python

# Python program to calculate
# cumulative moving averages using pandas
import pandas as pd
  
arr = [1, 2, 3, 7, 9]
window_size = 3
  
# Convert array of integers to pandas series
numbers_series = pd.Series(arr)
  
# Get the window of series of
# observations till the current time
windows = numbers_series.expanding()
  
# Create a series of moving averages of each window
moving_averages = windows.mean()
  
# Convert pandas series back to list
moving_averages_list = moving_averages.tolist()
  
print(moving_averages_list)

输出:

[1.0, 1.5, 2.0, 3.25, 4.4]

指数移动平均线

EMA 是通过一次取观测值的加权平均值来计算的。观察的权重随时间呈指数下降。它用于分析最近的变化。

公式:

EMAt =  αat + (1- α)EMAt-1

在哪里:

  • EMA t = 时间 t 的指数移动平均线
  • α = 观察权重随时间减少的程度
  • a t = 在时间 t 的观察

Python

# Program to calculate exponential
# moving average using formula
  
import numpy as np
  
arr = [1, 2, 3, 7, 9]
x=0.5  # smoothening factor
  
i = 1
# Initialize an empty list to
# store exponential moving averages
moving_averages = []
  
# Insert first exponential average in the list
moving_averages.append(arr[0])
  
# Loop through the array elements
while i < len(arr):
  
    # Calculate the exponential
    # average by using the formula
    window_average = round((x*arr[i])+
                           (1-x)*moving_averages[-1], 2)
      
    # Store the cumulative average
    # of current window in moving average list
    moving_averages.append(window_average)
      
    # Shift window to right by one position
    i += 1
  
print(moving_averages)

输出:

[1, 1.5, 2.25, 4.62, 6.81]

方法一:使用熊猫

Python的 Pandas 模块提供了一种简单的方法来计算一系列观察值的指数移动平均值。它提供了一种名为 pandas.Series.ewm.mean() 的方法来计算给定观察值的指数移动平均值。 pandas.Series.ewm() 采用称为平滑因子的参数,即观察权重随时间减小的程度。平滑因子的值始终介于 0 和 1 之间。

Python

# Python program to
# calculate exponential moving averages
import pandas as pd
  
arr = [1, 2, 3, 7, 9]
  
# Convert array of integers to pandas series
numbers_series = pd.Series(arr)
  
# Get the moving averages of series
# of observations till the current time
moving_averages = round(numbers_series.ewm(
  alpha=0.5, adjust=False).mean(), 2)
  
# Convert pandas series back to list
moving_averages_list = moving_averages.tolist()
  
print(moving_averages_list)

输出:

[1.0, 1.5, 2.25, 4.62, 6.81]

应用

  1. 时间序列分析:用于平滑短期变化并突出趋势和周期等长期观察结果。
  2. 财务分析:用于股票市场的财务分析,例如计算股票价格、收益和分析市场趋势。
  3. 环境工程:用于通过考虑污染物浓度等各种因素来分析环境条件。
  4. 计算机性能分析:用于通过计算平均 CPU 利用率、平均进程队列长度等指标来分析计算机性能。