import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.stats.diagnostic import acorr_ljungbox
# Prepare data
close_prices = nifty_50['Close'].dropna()
diff_prices = close_prices.diff().dropna()
# Set up a multi-panel visualization comparing Original vs. Differenced Series
fig, axes = plt.subplots(3, 2, figsize=(16, 12))
# ==========================================
# METHOD 1: VISUAL CHECK
# ==========================================
# Original Prices Plot
axes[0, 0].plot(close_prices, color='royalblue')
axes[0, 0].set_title("Method 1 (Visual): Original Close Price (Strong Trend/Walk)", fontsize=11, fontweight='bold')
axes[0, 0].grid(True)
# Differenced Prices Plot
axes[0, 1].plot(diff_prices, color='purple')
axes[0, 1].axhline(y=0, color='black', linestyle='--')
axes[0, 1].set_title("Method 1 (Visual): 1st-Order Differenced Price (Fluctuates Around 0)", fontsize=11, fontweight='bold')
axes[0, 1].grid(True)
# ==========================================
# METHOD 2: ACF & PACF PLOTS
# ==========================================
# Original Prices ACF
sm.graphics.tsa.plot_acf(close_prices, lags=30, ax=axes[1, 0], color='royalblue', vlines_kwargs={"colors": 'royalblue'})
axes[1, 0].set_title("Method 2: ACF of Original Prices (Slow Linear Decay)", fontsize=11, fontweight='bold')
axes[1, 0].grid(True)
# Differenced Prices ACF
sm.graphics.tsa.plot_acf(diff_prices, lags=30, ax=axes[1, 1], color='purple', vlines_kwargs={"colors": 'purple'})
axes[1, 1].set_title("Method 2: ACF of Differenced Prices (Uncorrelated/White Noise)", fontsize=11, fontweight='bold')
axes[1, 1].grid(True)
# Original Prices PACF
sm.graphics.tsa.plot_pacf(close_prices, lags=30, ax=axes[2, 0], color='royalblue', vlines_kwargs={"colors": 'royalblue'})
axes[2, 0].set_title("Method 2: PACF of Original Prices (Spike at Lag 1)", fontsize=11, fontweight='bold')
axes[2, 0].grid(True)
# Differenced Prices PACF
sm.graphics.tsa.plot_pacf(diff_prices, lags=30, ax=axes[2, 1], color='purple', vlines_kwargs={"colors": 'purple'})
axes[2, 1].set_title("Method 2: PACF of Differenced Prices (No Significant Spikes)", fontsize=11, fontweight='bold')
axes[2, 1].grid(True)
plt.tight_layout()
plt.show()