Understanding Moving Averages
Scorri per mostrare il menu
Moving averages are a foundational tool in time series analysis, especially for smoothing noisy data and making forecasts. The simple moving average (SMA) is one of the most basic and widely used types. An SMA is calculated by taking the arithmetic mean of a fixed number of consecutive observations in a time series. This rolling calculation helps to smooth out short-term fluctuations, making underlying trends and patterns easier to observe.
When you apply an SMA to a time series, you essentially create a new series where each value is the average of the previous n data points, where n is the window size. The main role of SMA in time series analysis is to reduce noise, making it easier to identify trends and cycles. This makes SMA a valuable tool for both data exploration and as a simple forecasting method, especially when you want to estimate the next value as the mean of recent observations.
12345678910111213141516171819202122232425import numpy as np import pandas as pd import matplotlib.pyplot as plt # Generate a sample time series: daily values with random noise np.random.seed(42) dates = pd.date_range(start="2023-01-01", periods=50) data = np.cumsum(np.random.randn(50)) + 10 # random walk series = pd.Series(data, index=dates) # Compute a simple moving average (window size = 5) window_size = 5 sma = series.rolling(window=window_size).mean() # Plot the original series and its moving average plt.figure(figsize=(10, 5)) plt.plot(series, label="Original Series") plt.plot(sma, label=f"SMA (window={window_size})", linewidth=2) plt.title("Simple Moving Average Smoothing") plt.xlabel("Date") plt.ylabel("Value") plt.legend() plt.tight_layout() plt.show()
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione