Table of Contents

				
					#import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.stattools import kpss
				
			
				
					# Generate synthetic stationary and non-stationary data
np.random.seed(17)
				
			
				
					# Stationary data: White noise
stationary_data = np.random.normal(size=100)
				
			
				
					# Create a random walk with larger step size to make it more volatile
random_walk = np.cumsum(np.random.normal(scale=2, size=n))  # Increase the scale for larger volatility
trend = np.linspace(0, 30, n)  # Add a strong linear trend (larger trend)

# Combine random walk and trend for clear non-stationary behavior
non_stationary_data = random_walk + trend
				
			
				
					# Plot the data
plt.figure(figsize=(10,5))
plt.subplot(1, 2, 1)
plt.plot(stationary_data)
plt.title('Stationary Data')

plt.subplot(1, 2, 2)
plt.plot(non_stationary_data)
plt.title('Non-Stationary Data')
plt.tight_layout()
plt.show()
				
			
parts of the ADF test –
tuple
				
					result = kpss(stationary_data)
				
			
				
					print(result)
				
			
access by index
				
					print('ADF Test Statistic:', result[0]) 
				
			
				
					print('p-value:', result[1])   
				
			
				
					print('Number of Lags Used:', result[2])  
				
			
				
					print('Critical Values:', result[3]) 
				
			
				
					adf_stat, p_value, lags, n_obs = result
				
			
				
					print(adf_stat)
				
			
				
					# Function to perform ADF test
def kpss_test(series):
    result = kpss(series)
    print(f'p-value: {result[1]}')
    if result[1] <= 0.05:
        print("=> Strong evidence against the null hypothesis, reject the null hypothesis. Data is non-stationary.")
    else:
        print("=> Weak evidence against the null hypothesis, fail to reject the null hypothesis. Data is level or trend stationary.")

				
			
				
					kpss_test(stationary_data)
				
			
				
					kpss_test(non_stationary_data)
				
			

Free Community

Join 1,000+ AI Automation Builders

Weekly tutorials, live calls & direct access to Ryan & Matt.

Join Free →

Keep Learning

Streamlit Async

Streamlit runs Python scripts top-to-bottom when ever a user interacts with widget.Streamlit is synchronous by default, meaning each function waits for the...

Streamlit Caching

Streamlit runs your script from top to bottom whenever you interact with the app.This execution model makes development super easy. But it...

Streamlit Tutorial

Streamlit can help businesses automate a ton of tasks in a short amount of time. It essentially is a quick UI you...

Gradient boosting classifier

Gradient Boosting is an ensemble technique that builds a strong model by combining multiple weak decision trees. While it may seem similar...