Identifying the Method
To test if the data in a time series (a pd.Series) is identically distributed, we need to check whether the statistical properties of the distribution (e.g., mean, variance, and higher moments) remain constant over time. This involves testing for stationarity in the time series.
Key Methods to Consider:
-
Augmented Dickey-Fuller (ADF) Test:
- Tests for the presence of a unit root, which indicates non-stationarity.
- Null hypothesis: The time series has a unit root (non-stationary).
- Alternative hypothesis: The time series is stationary.
-
Kolmogorov-Smirnov (KS) Test:
- Compares the empirical cumulative distribution function (ECDF) of two samples.
- Can be used to compare the distribution of subsets of the time series to see if they are identical.
-
Ljung-Box Test:
- Tests for autocorrelation in the time series.
- Useful for detecting dependencies in the data but does not directly test for identical distribution.
-
Visual Inspection (e.g., Rolling Statistics):
- Compute rolling mean and variance to visually inspect changes over time.
- Not a formal statistical test but provides intuitive insights.
Justification for Chosen Method:
The Augmented Dickey-Fuller (ADF) Test is chosen because it is specifically designed to test for stationarity in time series data. A stationary time series implies that the data is identically distributed over time. While the KS test can compare distributions, it requires splitting the data into arbitrary subsets, which may introduce bias. Visual inspection is subjective and lacks statistical rigor. The Ljung-Box test focuses on autocorrelation rather than distributional properties.
Python Code for the Augmented Dickey-Fuller Test
Below is the Python code to test if the data in a time series is identically distributed using the ADF test:
import pandas as pd
from statsmodels.tsa.stattools import adfuller
import matplotlib.pyplot as plt
def test_identical_distribution(time_series: pd.Series, significance_level=0.05):
"""
Test if a time series is identically distributed using the Augmented Dickey-Fuller (ADF) test.
Parameters:
time_series (pd.Series): The time series data to test.
significance_level (float): The significance level for the test (default is 0.05).
Returns:
dict: A dictionary containing the test results.
"""
# Perform the ADF test
result = adfuller(time_series)
# Extract test statistics and critical values
test_statistic = result[0]
p_value = result[1]
critical_values = result[4]
# Determine if the null hypothesis is rejected
is_stationary = p_value < significance_level
# Print interpretation
print("ADF Test Results:")
print(f"Test Statistic: {test_statistic}")
print(f"P-value: {p_value}")
print("Critical Values:")
for key, value in critical_values.items():
print(f" {key}: {value}")
if is_stationary:
print("\nConclusion: The time series is stationary (identically distributed).")
else:
print("\nConclusion: The time series is non-stationary (not identically distributed).")
# Return detailed results
return {
"test_statistic": test_statistic,
"p_value": p_value,
"critical_values": critical_values,
"is_stationary": is_stationary
}
# Example usage
if __name__ == "__main__":
# Generate example time series data
data = pd.Series([i + np.random.normal(0, 1) for i in range(100)]) # Non-stationary example
# Test for identical distribution
results = test_identical_distribution(data)
Explanation of the Code:
-
ADF Test:
- The
adfuller function from statsmodels performs the ADF test.
- It returns the test statistic, p-value, and critical values for different confidence levels.
-
Interpretation:
- If the p-value is less than the significance level (e.g., 0.05), we reject the null hypothesis and conclude that the time series is stationary (identically distributed).
- Otherwise, we fail to reject the null hypothesis, indicating non-stationarity.
-
Visualization (Optional):
- You can add rolling statistics (mean and variance) to visualize stationarity:
rolling_mean = time_series.rolling(window=10).mean()
rolling_std = time_series.rolling(window=10).std()
plt.figure(figsize=(10, 6))
plt.plot(time_series, label="Original Series")
plt.plot(rolling_mean, label="Rolling Mean", color="red")
plt.plot(rolling_std, label="Rolling Std", color="green")
plt.legend()
plt.title("Rolling Statistics")
plt.show()
Alternative Considerations:
- If the time series exhibits seasonality or trends, you may need to apply transformations (e.g., differencing, detrending) before testing.
- For very large datasets, consider subsampling to reduce computation time.
Final Answer:
The chosen method is the Augmented Dickey-Fuller (ADF) Test, implemented in the provided Python code.