Weighted and Exponential Moving Averages
Stryg for at vise menuen
Weighted and exponential moving averages are powerful tools for analyzing time series data, offering more flexibility and responsiveness than the simple moving average (SMA). The weighted moving average (WMA) assigns different weights to each data point in the window, allowing you to emphasize more recent observations or any pattern of importance you choose. The mathematical formula for the WMA of a series x with weights w over n periods is:
WMA=(w1+w2+...+wn)(w1x1+w2x2+...+wnxn)The exponential moving average (EMA) goes a step further by applying exponentially decreasing weights to past observations. This means recent data points have much more influence on the average, making the EMA especially useful for tracking trends in volatile data. The EMA is calculated recursively as:
EMAt=αxt+(1−α)EMAt−1where:
- EMAt is the current EMA value;
- xt is the current observation;
- α is the smoothing factor, typically 2/(n+1) or a window of size n.
These approaches help you capture recent trends and changes in your data more effectively than the SMA, which simply averages all points in the window equally.
12345678910111213141516171819202122import pandas as pd import matplotlib.pyplot as plt # Create a time series data = { "value": [10, 12, 13, 15, 14, 16, 18, 20, 19, 21, 22, 24, 23, 25, 27] } df = pd.DataFrame(data) # Calculate the Exponential Moving Average (EMA) with a span of 5 df["EMA_5"] = df["value"].ewm(span=5, adjust=False).mean() # Plot the original series and EMA plt.figure(figsize=(8, 4)) plt.plot(df["value"], label="Original") plt.plot(df["EMA_5"], label="EMA (span=5)", linestyle="--") plt.title("Exponential Moving Average (EMA) Example") plt.xlabel("Time") plt.ylabel("Value") plt.legend() plt.tight_layout() plt.show()
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat