L010 - TSA Journal
L010 - TSA Journal
Index
1 Practical - 1: ARIMA 1
6 Practical - 6: ARMA 72
7 Practical - 7: SARIMA 79
8 Practical - 8: ARIMA 96
🎀 Pg No. 0 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Practical 1
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
#url = "https://github.com/jbrownlee/Datasets/blob/master/airline-passengers.csv"
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
df = pd.read_csv(url, parse_dates= ['Month'], index_col = 'Month')
df.columns = ['Passengers']
df.head()
🎀 Pg No. 1 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
def test_stationarity(series):
result = adfuller(series)
print(f'ADF Statistic: {result[0]:.4f}')
print(f'p-value: {result[1]:.4f}')
if result[1] <= 0.05:
print('The series is stationary.')
else:
print('The series is non-stationary.')
test_stationarity(df['Passengers'])
df_diff = df['Passengers'].diff().dropna()
df_diff.plot(title = 'Differenced Series')
plt.show()
🎀 Pg No. 2 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
test_stationarity(df_diff)
🎀 Pg No. 3 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.title("PACF Plot")
plt.show()
🎀 Pg No. 4 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
train = df['Passengers'][:-24]
test = df['Passengers'][-24:]
🎀 Pg No. 5 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.show()
acf(x, main="")
🎀 Pg No. 6 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
pacf(x, main="")
set.seed(1)
x<-w<-rnorm(100, mean=0, sd=1)
for(t in 2:100) x[t] <- x[t-1] + w[t]
plot(x, type='l', xlab='Time')
acf(x, main="")
🎀 Pg No. 7 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
pacf(x, main="")
import numpy as np
import matplotlib.pyplot as mtp
import pandas as pd
🎀 Pg No. 8 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
x = data_set.iloc[:, :-1].values
y = data_set.iloc[:, -1].values
y_pred = regressor.predict(x_test)
x_pred = regressor.predict(x_train)
print(x_pred)
🎀 Pg No. 9 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Practical 2
import pandas as pd
🎀 Pg No. 10 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.holtwinters import ExponentialSmoothing
sales = [210, 220, 230, 300, 310, 305, 280, 290, 295, 310, 320, 330, 220, 225, 235, 310, 315,
310, 285, 295, 300, 315, 325, 335]
dates = pd.date_range(start='2022-01-01', periods=len(sales), freq='MS')
df = pd.Series(sales, index=dates)
df.plot(title="Monthly Retail Sales ($)", figsize=(10, 4))
plt.ylabel("Sales")
plt.grid()
plt.show()
#forecast = fit.forecast(12)
forecast = fit.forecast(24)
plt.figure(figsize=(12, 4))
df.plot(title="Actual")
forecast.plot(label = "Forecast", linestyle='--', color='red')
plt.xlabel("Date")
plt.ylabel("Sales")
plt.title("Holt Winter's Additive Forecast - Retail Sales")
plt.legend()
plt.grid()
🎀 Pg No. 11 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.show()
np.random.seed(42)
months = pd.date_range(start="2021-01-01", periods=36, freq="MS")
# Trend + Seasonality + Noise
demand = (
500 +
np.linspace(0, 300, 36) + # upward trend
50 * np.sin(2*np.pi*months.month/12) + # 1 year cycle
np.random.normal(0, 20, 36) # random noise
)
df = pd.Series(demand, index=months)
df.name = "Monthly Electronics Demand"
plt.figure(figsize=(10, 4))
df.plot()
plt.title("Monthly Electronics Demand")
plt.xlabel("Date")
plt.ylabel("Demand")
plt.grid()
plt.show()
🎀 Pg No. 12 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
#forecast = fit.forecast(12)
forecast = fit.forecast(24)
plt.figure(figsize=(12, 4))
df.plot(title="Actual", marker="o")
forecast.plot(label = "Forecast", marker="o", linestyle='--', color='red')
plt.xlabel("Date")
plt.ylabel("Units Sold")
plt.title("Holt Winter's Additive Forecast - Electronic Demand")
plt.legend()
plt.grid()
plt.show()
🎀 Pg No. 13 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
energy = [310, 280, 275, 260, 240, 230, 220, 225, 240, 280, 300, 330, 325, 295, 285, 270, 250,
240, 230, 235, 255, 290, 310, 340]
dates = pd.date_range(start='2022-01-01', periods=len(energy), freq='MS')
df = pd.Series(energy, index=dates)
df.plot(title="Monthly Electricity Usage (kWh)", marker="o", figsize=(10, 4))
plt.ylabel("Electricity Consumptoin (kWh)")
plt.xlabel("Date")
plt.grid()
plt.show()
#forecast = fit.forecast(12)
forecast = fit.forecast(24)
plt.figure(figsize=(12, 4))
df.plot(title="Actual", marker="o")
forecast.plot(label = "Forecast", marker="o", linestyle='--', color='red')
plt.xlabel("Date")
plt.ylabel("Electricity Consumptoin (kWh)")
plt.title("Holt Winter's Multiplicative Forecast - Electricity Consumption")
plt.legend()
plt.grid()
plt.show()
🎀 Pg No. 14 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(10)
months = pd.date_range(start="2019-01-01", periods=60, freq="MS")
df = pd.Series(visitors, index=months)
df.name = "Monthly Visitors (Kashmir)"
plt.figure(figsize=(10, 4))
df.plot(title="Monthly Visitors (Kashmir)", marker="o", figsize=(10, 4))
plt.title("Monthly Visitors (Kashmir)")
plt.xlabel("Date")
plt.ylabel("Visitors")
plt.grid()
plt.show()
🎀 Pg No. 15 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
#forecast = fit.forecast(12)
forecast = fit.forecast(24)
plt.figure(figsize=(12, 4))
df.plot(title="Actual", marker="o")
forecast.plot(label = "Forecast", marker="o", linestyle='--', color='red')
plt.xlabel("Date")
plt.ylabel("Monthly Visitors (Kashmir)")
plt.title("Holt Winter's Additive Forecast - Monthly Visitors (Kashmir)")
plt.legend()
plt.grid()
plt.show()
🎀 Pg No. 16 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
t observation
1 1996 150.3
2 1997 150.9
3 1998 151.4
4 1999 151.9
5 2000 152.5
🎀 Pg No. 17 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Time Series:
Start = 1
End = 24
Frequency = 1
[1] 150.3000 150.3000 150.4800 150.7560 151.0992 151.5194 151.9336
[8] 152.3135 152.7295 152.9906 153.1434 153.5204 153.9343 154.4640
[15] 155.0148 155.4904 155.8533 156.1973 156.5281 156.9097 157.3268
[22] 157.7087 157.9761 158.3133
holt_model <- holt(data$observation, alpha = 0.3, beta = 0.2, initial = "simple", h=1)
holt_fitted <- fitted(holt_model)
holt_fitted
🎀 Pg No. 18 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Time Series:
Start = 1
End = 24
Frequency = 1
[1] 150.9000 151.2840 151.7098 152.1392 152.5755 153.0563 153.5035
[8] 153.8884 154.2965 154.5103 154.5694 154.8706 155.2332 155.7551
[15] 156.3330 156.8436 157.2224 157.5642 157.8777 158.2424 158.6512
[22] 159.0242 159.2599 159.5653
ggplot() +
geom_line(aes(x=data$t, y=data$observation, color="Original"), size = 1) +
geom_line(aes(x=data$t, y=ses_fitted, color="SES (Alpha = 0.3)"), linetype="dashed", size =
1) +
geom_line(aes(x=data$t, y=holt_fitted, color="Holts (Alpha = 0.3, beta=0.2)"),
linetype="dotted", size = 1) +
ggtitle("Comparison of SES and Holt's Method") +
xlab("Year") +
ylab("Observation") +
scale_color_manual(values=c("blue", "red", "green")) +
theme_minimal()
Practical 3
🎀 Pg No. 19 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.holtwinters import SimpleExpSmoothing, Holt
from statsmodels.tsa.stattools import adfuller
sales_data = [200, 210, 215, 220, 230, 225, 235, 240, 250, 255, 260, 265]
dates = pd.date_range(start="2023-01-01", periods=len(sales_data), freq='M')
sales_series = pd.Series(sales_data, index=dates)
Sales_series
#model = SimpleExpSmoothing(sales_series)
model = Holt(sales_series)
#fit = model.fit(smoothing_level=0.4, optimized=False)
fit = model.fit(smoothing_level=0.4, smoothing_slope=0.2, optimized=False)
print(fit.summary())
🎀 Pg No. 20 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = fit.forecast(6)
plt.figure(figsize=(9, 4))
plt.plot(sales_series, label='Original Data', marker='o')
plt.plot(fit.fittedvalues, label='Fitted Values', linestyle='--', marker='x')
plt.plot(forecast, label='Forecast', linestyle='--', marker='o', color='red')
plt.title('Simple Exponential Smoothing Forecast')
plt.xlabel('Months')
plt.ylabel('Sales (in thousands)')
plt.legend()
plt.grid()
plt.tight_layout()
plt.show()
🎀 Pg No. 21 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
series = df['Consumption']
Series
model = Holt(series)
fit = model.fit(smoothing_level=0.4, smoothing_slope=0.2, optimized=False)
print(fit.summary())
🎀 Pg No. 22 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = fit.forecast(6)
plt.figure(figsize=(9, 4))
plt.plot(series, label='Original Data', marker='o')
plt.plot(fit.fittedvalues, label='Fitted Values', linestyle='--', marker='x')
plt.plot(forecast, label='Forecast', linestyle='--', marker='o', color='red')
plt.title('Simple Exponential Smoothing Forecast')
plt.xlabel('Months')
plt.ylabel('Electricity Consumption')
plt.legend()
plt.grid()
plt.tight_layout()
plt.show()
🎀 Pg No. 23 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(42)
plt.figure(figsize=(9, 4))
series.plot(title='Simulated Stationary Time Series (White Noise)')
plt.grid()
plt.show()
🎀 Pg No. 24 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
model = Holt(series)
fit = model.fit(smoothing_level=0.4, smoothing_slope=0.2, optimized=False)
print(fit.summary())
forecast = fit.forecast(6)
print("Forecasted Data for next 6 Months: ")
print(forecast.round(2))
🎀 Pg No. 25 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(9, 4))
plt.plot(series, label='Original Data', marker='o')
plt.plot(fit.fittedvalues, label='Fitted Values', linestyle='--', marker='x')
plt.plot(forecast, label='Forecast', linestyle='--', marker='o', color='red')
plt.title('Holt’s Linear Trend Forecast')
plt.xlabel('Months')
plt.ylabel('Data')
plt.legend()
plt.grid()
plt.tight_layout()
plt.show()
🎀 Pg No. 26 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
result = adfuller(df['Visits'])
print("ADF Statistics: ", result[0])
print("p-value: ", result[1])
🎀 Pg No. 27 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
df_diff = df['Visits'].diff().dropna()
result_df = adfuller(df_diff)
print("ADF Statistics: ", result_df[0])
print("p-value: ", result_df[1])
🎀 Pg No. 28 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
data <- c(150.3, 150.9, 151.4, 151.9, 152.5, 152.9, 153.2, 153.7, 153.6, 153.5, 154.4, 154.9,
155.7, 156.3, 156.6, 156.7, 157, 157.3, 157.8, 158.3, 158.6, 158.6, 159.1, 159.3)
time_series_data <- ts(data, start=1996, frequency=1)
Time_series_data
Time Series:
Start = 1996
End = 2019
Frequency = 1
[1] 150.3 150.9 151.4 151.9 152.5 152.9 153.2 153.7 153.6 153.5 154.4
[12] 154.9 155.7 156.3 156.6 156.7 157.0 157.3 157.8 158.3 158.6 158.6
[23] 159.1 159.3
Model Information:
Simple exponential smoothing
Call:
ses(y = time_series_data, h = 1, alpha = 0.3)
Smoothing parameters:
alpha = 0.3
Initial states:
l = 151.4724
sigma: 1.2231
🎀 Pg No. 29 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Error measures:
ME RMSE MAE MPE MAPE MASE
Training set 0.991261 1.171032 1.107357 0.6346283 0.7118224 2.70949
ACF1
Training set 0.580185
Forecasts:
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
2020 158.6095 157.0421 160.177 156.2123 161.0068
🎀 Pg No. 30 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 31 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
# Moving Average
year <- 1991:2003
co2_concentration <- c(355.62, 356.36, 357.1, 358.86, 360.9, 362.58, 363.04, 365.58, 368.3,
369.47, 371.03, 373.61, 357.61)
co2_ts <- ts(co2_concentration, start=1991, frequency=1)
co2_ts
Time Series:
Start = 1991
End = 2003
Frequency = 1
[1] 355.62 356.36 357.10 358.86 360.90 362.58 363.04 365.58 368.30 369.47
[11] 371.03 373.61 357.61
🎀 Pg No. 32 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
[1] 367.4167
window_size <- 3
ma_col <- moving_avg_manual(co2_concentration, window_size)
ma_col
Forecast CO2 Concentration for 2004 using 3-year moving average: 367.4167
🎀 Pg No. 33 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast<-predict(hw_model, n.ahead=12)
forecast
🎀 Pg No. 34 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 35 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 36 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Practical 4
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.ar_model import AutoReg
from statsmodels.tsa.stattools import acf
🎀 Pg No. 37 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
future = result.forecast(steps=3)
print("Next 3 predictions:", future.tolist())
Future
data = [200, 202, 198, 203, 207, 210, 212, 215, 214, 217]
series = pd.Series(data)
Series
🎀 Pg No. 38 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(8, 4))
plt.plot(series, marker='o')
plt.title("Weekly Sales Data")
plt.xlabel("Week")
plt.ylabel("Sale Units")
plt.grid()
plt.show()
plot_acf(series, lags=5)
🎀 Pg No. 39 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.show()
plot_acf(series, lags=2)
plt.show()
plot_pacf(series, lags=5)
plt.show()
🎀 Pg No. 40 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plot_pacf(series, lags=2)
plt.show()
🎀 Pg No. 41 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = result.forecast(steps=3)
print("Forecast for next 3 weeks:", forecast.tolist())
Forecast
🎀 Pg No. 42 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 43 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plot_acf(df['Temperature'], lags=5)
plt.title("Autocorrelation (ACF) Plot")
plt.xlabel("Lag")
plt.ylabel("Autocorrelation")
plt.show()
🎀 Pg No. 44 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(10, 4))
🎀 Pg No. 45 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
df['Temperature'].plot(label='Original')
forecast.plot(label='Forecast', linestyle = '--', color='red')
plt.title('AutoRegression Forecast (Next 10 Days)')
plt.legend()
plt.grid()
plt.show()
🎀 Pg No. 46 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 47 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = result.forecast(steps=2)
print("Forecast for next 3 weeks:", forecast.tolist())
Forecast
🎀 Pg No. 48 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plot_acf(sales_series)
🎀 Pg No. 49 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plot_pacf(sales_series)
🎀 Pg No. 50 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = result.forecast(steps=2)
print("Forecast for next 3 weeks:", forecast.tolist())
Forecast
🎀 Pg No. 51 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = result.forecast(steps=8)
print("Forecast for next 3 weeks:", forecast.tolist())
Forecast
🎀 Pg No. 52 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.grid()
plt.show()
sales_ts <- ts(c(750, 1000, 1300, 1650, 1900, 2200, 2550, 2900, 3300, 3700, 4100))
sales_ts
Time Series:
🎀 Pg No. 53 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Start = 1
End = 11
Frequency = 1
[1] 750 1000 1300 1650 1900 2200 2550 2900 3300 3700 4100
🎀 Pg No. 54 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
summary(arma_model)
Call:
arma(x = sales_ts, order = c(1, 0, 0))
Model:
ARMA(1,0)
Residuals:
Min 1Q Median 3Q Max
-61.754 -16.301 0.848 17.875 55.375
Coefficient(s):
Estimate Std. Error t value Pr(>|t|)
ar1 1.049e+00 9.807e-03 106.96 <2e-16 ***
intercept 2.310e+02 2.277e+01 10.14 <2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Fit:
sigma^2 estimated as 1030, Conditional Sum-of-Squares = 9268.23, AIC = 111.52
🎀 Pg No. 55 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Practical 5
data.head()
🎀 Pg No. 56 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
def check_stationary(series):
result = adfuller(series)
print("ADF Statistics: ", result[0])
print("p-value: ", result[1])
if result[1] <= 0.05:
print("The series is stationary")
else:
print("The series is not stationary")
check_stationary(data['Sales'])
data_diff = data['Sales'].diff().dropna()
check_stationary(data_diff)
plot_acf(data_diff, lags=10)
plot_pacf(data_diff, lags=10)
plt.show()
🎀 Pg No. 57 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = result.forecast(steps=12)
print("Forecast for next 3 weeks:", forecast.tolist())
forecast.head()
🎀 Pg No. 58 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(10, 5))
plt.plot(data['Sales'], marker='o', label='Actual')
plt.plot(forecast_df['Forecast'], marker='o', label='Forecast', linestyle='--')
plt.title('ARIMA (1, 1, 1) Sales Forecast')
plt.legend()
plt.show()
🎀 Pg No. 59 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 60 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
check_stationary(df['Passengers'])
data_diff = df['Passengers'].diff().dropna()
check_stationary(data_diff)
data_diff = data_diff.diff().dropna()
check_stationary(data_diff)
🎀 Pg No. 61 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = result.forecast(steps=24)
print("Forecast for next 3 weeks:", forecast.tolist())
forecast.head()
plt.figure(figsize=(10, 5))
plt.plot(df['Passengers'], marker='o', label='Actual')
plt.plot(forecast, marker='o', label='Forecast', linestyle='--')
plt.title('ARIMA (2, 1, 2) Passengers')
plt.legend()
plt.show()
🎀 Pg No. 62 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
library(forecast)
library(tseries)
sales<-c(200, 220 ,230 ,250 ,270, 300, 310, 320, 340, 350, 370, 400, 410, 420, 450, 470, 500,
520, 540, 560, 580, 600, 620, 650)
head(sales)
[1] 200 220 230 250 270 300
🎀 Pg No. 63 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
#Checking Stationarity
adf.test(sales_ts)
data: sales_ts
Dickey-Fuller = -0.72851, Lag order = 2, p-value = 0.956
alternative hypothesis: stationary
Coefficients:
drift
19.5652
s.e. 1.4392
🎀 Pg No. 64 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 65 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
adf.test(air_ts)
Augmented Dickey-Fuller Test
data: air_ts
🎀 Pg No. 66 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Coefficients:
ar1 ar2 ma1
0.5960 0.2143 -0.9819
s.e. 0.0888 0.0880 0.0292
summary(model_air)
Series: air_ts
ARIMA(2,1,1)(0,1,0)[12]
Coefficients:
ar1 ar2 ma1
0.5960 0.2143 -0.9819
s.e. 0.0888 0.0880 0.0292
🎀 Pg No. 67 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
set.seed(42)
🎀 Pg No. 68 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 69 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
ARIMA(0,1,0)
🎀 Pg No. 70 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Practical 6
import pandas as pd
🎀 Pg No. 71 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
data = [100, 104, 107, 111, 115, 118, 120, 124, 127, 130]
series = pd.Series(data)
plot_acf(series, lags=5)
plot_pacf(series, lags=5)
plt.show()
🎀 Pg No. 72 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = result.forecast(steps=3)
print("Forecast for next 3 weeks:", forecast.tolist())
forecast.head()
🎀 Pg No. 73 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(10, 5)),
plt.plot(series, marker='o', label='Actual')
plt.plot(forecast, marker='o', label='Forecast', linestyle='--')
plt.title('ARMA (2, 0, 0)')
plt.legend()
plt.show()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
🎀 Pg No. 74 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(42)
months=pd.date_range(start='2018-01-01', periods=60, freq="M")
sales = 200+np.arange(60)*2+np.random.normal(0, 10, 60)
df=pd.DataFrame({'Months': months, "Sales": sales})
df.set_index("Months", inplace=True)
df.head()
plt.figure(figsize=(10, 4))
plt.plot(df["Sales"], label="Monthly Sales")
plt.title("Monthly Sales Time Series")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
🎀 Pg No. 75 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
result = adfuller(df["Sales"])
print("ADF Statistics: ", result[0])
print("p-value: ", result[1])
auto_model.plot_diagnostics(figsize=(12, 6))
🎀 Pg No. 76 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = auto_model.get_forecast(steps=12)
forecast_df = forecast.summary_frame()
plt.figure(figsize=(10, 4))
plt.plot(df["Sales"], label="Actual Sales")
plt.plot(forecast_df['mean'], label="Forecast Sales")
plt.fill_between(forecast_df.index, forecast_df['mean_ci_lower'], forecast_df['mean_ci_upper'],
color='pink', alpha=0.3)
plt.title("Forecast of Next 12 Months")
plt.xlabel("Years")
plt.ylabel("Sales")
plt.legend()
plt.show()
🎀 Pg No. 77 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Practical 7
🎀 Pg No. 78 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(0)
date_range = pd.date_range(start='2020-01-01', periods=48, freq='M')
trend = np.linspace(100, 200, 48)
seasonality = 20*np.sin(2*np.pi*date_range.month/12)
noise = np.random.normal(0, 5, 48)
data = trend + seasonality + noise
df = pd.DataFrame({'Sales': data}, index=date_range)
df.head()
🎀 Pg No. 79 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = model_fit.get_forecast(steps=12)
forecast_df = forecast.summary_frame()
plt.figure(figsize=(10, 5))
🎀 Pg No. 80 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.plot(df, label='Observed')
plt.plot(forecast_df['mean'], label='Forecast')
plt.fill_between(forecast_df.index, forecast_df['mean_ci_lower'], forecast_df['mean_ci_upper'],
color='pink', alpha=0.3)
plt.title('SARIMA Forecast')
plt.legend()
plt.show()
np.random.seed(0)
date_range = pd.date_range(start='2020-01', periods=36, freq='M')
seasonality = 30+15*np.sin(2*np.pi*date_range.month/12)
noise = np.random.normal(0, 3, 36)
data = seasonality + noise
df = pd.DataFrame({'Sales': data}, index=date_range)
df.head()
🎀 Pg No. 81 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = model_fit.get_forecast(steps=12)
forecast_df = forecast.summary_frame()
plt.figure(figsize=(10, 5))
plt.plot(df, label='Observed')
plt.plot(forecast_df['mean'], label='Forecast')
plt.fill_between(forecast_df.index, forecast_df['mean_ci_lower'], forecast_df['mean_ci_upper'],
color='pink', alpha=0.3)
🎀 Pg No. 82 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.title('SARIMA Forecast')
plt.legend()
plt.show()
np.random.seed(2)
date_range = pd.date_range(start='2019-01', periods=60, freq='M')
trend = np.linspace(80, 120, 60)
seasonality = 1+0.4*np.sin(2*np.pi*date_range.month/12)
noise = np.random.normal(0, 2, 60)
data = trend * seasonality + noise
df = pd.DataFrame({'Sales': data}, index=date_range)
df.head()
🎀 Pg No. 83 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = model_fit.get_forecast(steps=12)
forecast_df = forecast.summary_frame()
plt.figure(figsize=(10, 5))
plt.plot(df, label='Observed')
plt.plot(forecast_df['mean'], label='Forecast')
🎀 Pg No. 84 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(3)
date_range = pd.date_range(start='2020-01', periods=48, freq='M')
pattern = np.random.choice([10, 20, 30], size=12, replace=True)
trend = 0.5*np.arange(48)
seasonality = np.tile(pattern, 4)
noise = np.random.normal(0, 5, 48)
data = trend + seasonality + noise
df = pd.DataFrame({'Sales': data}, index=date_range)
df.head()
🎀 Pg No. 85 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = model_fit.get_forecast(steps=12)
forecast_df = forecast.summary_frame()
plt.figure(figsize=(10, 5))
plt.plot(df, label='Observed')
plt.plot(forecast_df['mean'], label='Forecast')
🎀 Pg No. 86 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(3)
date_range = pd.date_range(start='2021-01', periods=48, freq='M')
seasonality = 5*np.sin(2*np.pi*date_range.month/12)
noise = np.random.normal(0, 10, 48)
data = 50 + seasonality + noise
df = pd.DataFrame({'Sales': data}, index=date_range)
df.head()
🎀 Pg No. 87 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = model_fit.get_forecast(steps=12)
forecast_df = forecast.summary_frame()
plt.figure(figsize=(10, 5))
plt.plot(df, label='Observed')
plt.plot(forecast_df['mean'], label='Forecast')
🎀 Pg No. 88 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
data.plot(title='Airline Passengers')
plt.show()
🎀 Pg No. 89 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
result = adfuller(data['Passengers'])
print('ADF Statistic: %f' % result[0])
print('p-value: %f' % result[1])
🎀 Pg No. 90 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
sarima_fit = sarima.fit()
print(sarima_fit.summary())
forecast = sarima_fit.get_forecast(steps=12)
forecast_df = forecast.summary_frame()
plt.plot(data['Passengers'], label='Observed')
plt.plot(forecast_df['mean'], label='Forecast')
plt.fill_between(forecast_df.index, forecast_df['mean_ci_lower'], forecast_df['mean_ci_upper'],
color='pink', alpha=0.2)
plt.title('SARIMA Forecast')
plt.legend()
plt.show()
np.random.seed(0)
🎀 Pg No. 91 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
🎀 Pg No. 92 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = model_fit.get_forecast(steps=12)
pred_df = forecast.summary_frame()
plt.plot(df['Sales'], label='Observed')
plt.plot(pred_df['mean'], label='Forecast')
plt.fill_between(pred_df.index, pred_df['mean_ci_lower'], pred_df['mean_ci_upper'],
color='pink', alpha=0.3)
plt.title('SARIMA Forecast (Synthetic Data)')
plt.legend()
plt.show()
🎀 Pg No. 93 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
url = 'https://raw.githubusercontent.com/diyapratheep/EDA-on-Retail-Sales-Data/refs/heads/
main/retail_sales_dataset.csv'
data = pd.read_csv(url, index_col='Date', parse_dates=['Date'])
data.head()
🎀 Pg No. 94 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = model_fit.get_forecast(steps=12)
pred_df = forecast.summary_frame()
plt.plot(df['Sales'], label='Observed')
plt.plot(pred_df['mean'], label='Forecast')
plt.fill_between(pred_df.index, pred_df['mean_ci_lower'], pred_df['mean_ci_upper'],
color='pink', alpha=0.2)
plt.title('SARIMA Forecast (Synthetic Multiplicative Seasonal Data)')
plt.legend()
plt.show()
🎀 Pg No. 95 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Practical 8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
np.random.seed(0)
months = pd.date_range(start='2020-01', periods=36, freq='M')
base_sales = 300 + np.random.normal(0, 20, 36)
for i in range(len(months)):
if months[i].month in [10, 11]:
base_sales[i] += 200
sales = pd.Series(base_sales, index=months)
forecast = fit.get_forecast(steps=12)
pred = forecast.predicted_mean
conf = forecast.conf_int()
plt.figure(figsize=(10, 5))
plt.plot(sales, label='Observed Sales')
plt.plot(pred, label='Forecast')
plt.fill_between(conf.index, conf.iloc[:, 0], conf.iloc[:, 1], color='pink', alpha=0.3)
plt.title('Sony TV Sales FOrecast with ATIMA (Diwali Spikes)')
plt.legend()
plt.show()
🎀 Pg No. 96 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
for i in range(len(weeks)):
if weeks[i].month in [10, 11]:
sales[i] += 150
sales_series = pd.Series(sales, index=weeks)
forecast = fit.get_forecast(steps=20)
pred = forecast.predicted_mean
conf = forecast.conf_int()
plt.figure(figsize=(10, 5))
plt.plot(sales_series, label='Observed Sales')
plt.plot(pred, label='Forecast')
plt.fill_between(conf.index, conf.iloc[:, 0], conf.iloc[:, 1], color='pink', alpha=0.3)
plt.title('Sony TV Weekly Sales Forecast During Diwali')
plt.legend()
plt.show()
🎀 Pg No. 97 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
sales[40:60]+=100
series = pd.Series(sales, index=days)
forecast = fit.get_forecast(steps=30)
pred = forecast.predicted_mean
conf = forecast.conf_int()
plt.figure(figsize=(10, 5))
plt.plot(series, label='Observed Sales')
plt.plot(pred, label='Forecast')
plt.fill_between(conf.index, conf.iloc[:, 0], conf.iloc[:, 1], color='pink', alpha=0.3)
plt.title('Sony TV Weekly Sales Forecast 20 days before Diwali')
plt.legend()
plt.show()
🎀 Pg No. 98 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
forecast = fit.get_forecast(steps=5)
pred = forecast.predicted_mean
conf = forecast.conf_int()
plt.figure(figsize=(10,5))
plt.plot(series, label="Observed")
plt.plot(pred, label="Forecast")
plt.fill_between(conf.index, conf.iloc[:,0], conf.iloc[:,1], alpha=0.3)
plt.title("Sony TV Yearly Sales Forecast (Diwali Growth Effect)")
plt.legend()
plt.show()
🎀 Pg No. 99 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
for i in range(len(months)):
if months[i].month == 10:
sales[i] += 250
forecast = fit.get_forecast(steps=12)
pred = forecast.predicted_mean
conf = forecast.conf_int()
plt.figure(figsize=(10,5))
plt.plot(series, label="Observed")
plt.plot(pred, label="Forecast")
plt.fill_between(conf.index, conf.iloc[:,0], conf.iloc[:,1], alpha=0.3)
plt.axvline(x=pd.to_datetime("2022-10-01"), color="red", linestyle="--", label="Diwali")
plt.title("Sony TV Sales Forecast Pre vs Post Diwali")
plt.legend()
plt.show()
🎀 Pg No. 100 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(42)
n = 80
series = pd.Series(100+0.5*np.arange(n)+np.random.normal(0, 2, n))
n_obs = fit.nobs
sigma2 = fit.mse
k = fit.df_model+1
fpe = sigma2 * (n_obs + k)/(n_obs - k)
print("Synthethic Example")
print("AIC: ", fit.aic)
print("BIC: ", fit.bic)
print("FPE: ", fpe)
🎀 Pg No. 101 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(0)
n = 100
steps = np.random.normal(0, 1, n)
series = pd.Series(np.cumsum(steps))
🎀 Pg No. 102 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
n_obs = fit.nobs
sigma2 = fit.mse
k = fit.df_model+1
fpe = sigma2 * (n_obs + k)/(n_obs - k)
np.random.seed(10)
n = 120
time = np.arange(n)
series = 50+10*np.sin(2*np.pi*time/12)+np.random.normal(0, 2, n)
orders = [(1, 1, 1), (1, 1, 2), (2, 1, 2), (3, 1, 2), (2, 0, 2)]
results = []
for order in orders:
model = ARIMA(series, order=order)
fit = model.fit()
n_obs = fit.nobs
sigma2 = fit.mse
k = fit.df_model+1
fpe = sigma2 * (n_obs + k)/(n_obs - k)
results.append((order, fit.aic, fit.bic, fpe))
🎀 Pg No. 103 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
8.2 ARIMA - R
library(forecast)
data("AirPassengers")
ts_data <- AirPassengers
plot(ts_data, main="AirPassengers Data")
🎀 Pg No. 104 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Coefficients:
ar1 ar2 ma1
0.5960 0.2143 -0.9819
s.e. 0.0888 0.0880 0.0292
data("JohnsonJohnson")
ts_data <- JohnsonJohnson
🎀 Pg No. 105 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Coefficients:
ar1 ar2 ar3 ma1
-0.1712 0.1387 -0.208 -0.6636
s.e. 0.1769 0.1701 0.121 0.1542
🎀 Pg No. 106 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
Practical 9
🎀 Pg No. 107 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(42)
months = pd.date_range(start='2018-01-01', periods=60, freq='M')
plt.figure(figsize=(10, 5))
plt.plot(data['Sales'], marker='o', label='Monthly Sales')
plt.title('Synthetic Diwali Sales Data (2018-2022)')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.legend()
plt.show()
🎀 Pg No. 108 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
n_obs = fit.nobs
sigma2 = fit.mse
k = fit.df_model + 1
fpe = sigma2*(n_obs+k)/(n_obs-k)
return {'Order':order, 'AIC': fit.aic, 'BIC': fit.bic, 'FPE': fpe}
🎀 Pg No. 109 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(10, 5))
plt.plot(data.index, data['Auto_Sales'], marker='o', label='Automobile Sales (Dec)')
plt.title('AutoMobile Sales In India (2010-2022)')
plt.xlabel('Year')
plt.ylabel('Sales')
plt.legend()
plt.show()
🎀 Pg No. 110 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(42)
n=80
data = pd.Series(50+0.5*np.arange(n)+np.random.normal(0, 2, n))
n_obs = fit.nobs
sigma2 = fit.mse
k = fit.df_model + 1
fpe = sigma2*(n_obs+k)/(n_obs-k)
Practical 10
🎀 Pg No. 111 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from arch import arch_model
🎀 Pg No. 112 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(10, 4))
plt.plot(fit.conditional_volatility, label="Conditional Volatility")
plt.title("Conditional Volatility of S&P 500 Returns")
plt.xlabel("Date")
plt.ylabel("Volatility")
plt.legend()
plt.show()
🎀 Pg No. 113 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(10, 4))
plt.plot(fit.conditional_volatility, label="Conditional Volatility")
plt.title("Conditional Volatility of S&P 500 Returns")
plt.xlabel("Date")
plt.ylabel("Volatility")
plt.legend()
plt.show()
🎀 Pg No. 114 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
gold.head()
gold_returns = 100*gold["Close"].pct_change().dropna()
plt.figure(figsize=(10, 4))
plt.plot(fit.conditional_volatility, label="Conditional Volatility")
plt.title("GARCH(1, 1) on Gold Prices")
🎀 Pg No. 115 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.xlabel("Date")
plt.ylabel("Volatility")
plt.legend()
plt.show()
🎀 Pg No. 116 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
results = []
for p, q in models:
model = arch_model(gold_returns, vol='GARCH', p=p, q=q)
fit = model.fit()
results.append({"Model":f"GARCH{p}, {q}",
"AIC":fit.aic,
"BIC":fit.bic,
"Loglikelihood":fit.loglikelihood})
df = pd.DataFrame(results)
print("Model Comparison")
Df
np.random.seed(42)
n = 500
eps = np.random.normal(size = n)
vol = np.zeros(n)
ret = np.zeros(n)
alpha0, alpha1 = 0.1, 0.8
🎀 Pg No. 117 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(10, 4))
plt.plot(arch_fit.conditional_volatility, label="ARCH(1) Conditional Volatility")
plt.xlabel("Date")
plt.ylabel("Volatility")
plt.legend()
plt.show()
np.random.seed(123)
n = 500
eps = np.random.normal(size = n)
vol = np.zeros(n)
🎀 Pg No. 118 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
ret = np.zeros(n)
omega, alpha, beta = 0.05, 0.1, 0.85
plt.figure(figsize=(10, 4))
plt.plot(garch_fit.conditional_volatility, label="GARCH(1, 1) Conditional Volatility")
plt.xlabel("Date")
plt.ylabel("Volatility")
plt.legend()
plt.show()
🎀 Pg No. 119 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
np.random.seed(99)
n = 500
eps = np.random.normal(size = n)
phi = 0.3
vol = np.zeros(n)
ret = np.zeros(n)
omega, alpha, beta = 0.05, 0.1, 0.85
🎀 Pg No. 120 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
print(ar_garch.summary())
plt.figure(figsize=(10, 4))
plt.plot(ar_garch.conditional_volatility, label="AR(1) GARCH(1, 1) Conditional Volatility")
plt.xlabel("Date")
plt.ylabel("Volatility")
plt.legend()
plt.show()
🎀 Pg No. 121 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
data = sunspots.load_pandas().data['SUNACTIVITY']
print(model.summary())
innovations = model.resid
innovations.head(10)
🎀 Pg No. 122 🎀
🎀 Rehmah Ahmed Batki | MSC DSAI 2 - L010 | 40778240010 🎀
plt.figure(figsize=(10, 4))
plt.plot(innovations)
plt.axhline(0, linestyle='--', color='black')
plt.title("Innovations from AR(1) Model (Sunspots)")
plt.xlabel("Date")
plt.ylabel("Innovations")
plt.legend()
plt.show()
🎀 Pg No. 123 🎀