Skip to content

Instantly share code, notes, and snippets.

@HansUXdev
Last active January 22, 2024 22:25
Show Gist options
  • Save HansUXdev/b52ddfaa647672b9a4aca39e3737dc30 to your computer and use it in GitHub Desktop.
Save HansUXdev/b52ddfaa647672b9a4aca39e3737dc30 to your computer and use it in GitHub Desktop.
FinancialForecasting.py
# Import necessary libraries
import numpy as np
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error
from statsmodels.tsa.holtwinters import ExponentialSmoothing
# Data Acquisition
stock_data = yf.download('AAPL', start='2022-01-01', end='2024-01-01')
stock_data.sort_index(ascending=True, inplace=True)
# Ensure proper DatetimeIndex with frequency for time series analysis
stock_data.index = pd.to_datetime(stock_data.index)
stock_data = stock_data.asfreq('B', method='ffill')
# Calculate rolling averages
stock_data['7_day_avg'] = stock_data['Close'].rolling(window=7, min_periods=1).mean()
stock_data['30_day_avg'] = stock_data['Close'].rolling(window=30, min_periods=1).mean()
# Split the data into training and test sets
split_date = pd.to_datetime('2023-10-01')
train = stock_data[:split_date]
test = stock_data[split_date:]
# Prepare the training and test data for Linear Regression
X_train_lr = train[['7_day_avg', '30_day_avg']]
y_train_lr = train['Close']
X_test_lr = test[['7_day_avg', '30_day_avg']]
# Fit a linear regression model
model_lr = LinearRegression()
model_lr.fit(X_train_lr, y_train_lr)
# Create copies of the test DataFrame to avoid SettingWithCopyWarning
test_lr = test.copy()
test_es = test.copy()
# Fit a linear regression model
model_lr = LinearRegression()
model_lr.fit(X_train_lr, y_train_lr)
# Predict the closing price for the test set using linear regression
test_lr['Close_Predicted_LR'] = model_lr.predict(X_test_lr)
# Exponential Smoothing model with trend and seasonality
es_model = ExponentialSmoothing(train['Close'], trend='add', seasonal='add', seasonal_periods=12)
fit_es_model = es_model.fit()
# Forecast the closing price for the test set using exponential smoothing
test_es['Close_Predicted_ES'] = fit_es_model.forecast(len(test_es))
# Calculate performance metrics for exponential smoothing
mae_es = mean_absolute_error(test_es['Close'], test_es['Close_Predicted_ES'])
mse_es = mean_squared_error(test_es['Close'], test_es['Close_Predicted_ES'])
rmse_es = np.sqrt(mse_es)
# Print performance metrics for exponential smoothing
print("\nExponential Smoothing Metrics:")
print(f"Mean Absolute Error (MAE): {mae_es:.2f}")
print(f"Mean Squared Error (MSE): {mse_es:.2f}")
print(f"Root Mean Squared Error (RMSE): {rmse_es:.2f}")
# Visualization of linear regression predictions
plt.figure(figsize=(12, 6))
plt.plot(train.index, train['Close'], label='Train Data')
plt.plot(test_lr.index, test_lr['Close'], label='Actual Test Data')
plt.plot(test_lr.index, test_lr['Close_Predicted_LR'], label='Predicted Test Data (LR)', linestyle='--')
plt.title('TCBI Linear Regression Forecasting')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.show()
# Print performance metrics for linear regression
print("\nLinear Regression Metrics:")
print(f"Mean Absolute Error (MAE): {mae_lr:.2f}")
print(f"Mean Squared Error (MSE): {mse_lr:.2f}")
print(f"Root Mean Squared Error (RMSE): {rmse_lr:.2f}")
# Visualization of exponential smoothing predictions
plt.figure(figsize=(12, 6))
plt.plot(train.index, train['Close'], label='Train Data')
plt.plot(test_es.index, test_es['Close'], label='Actual Test Data')
plt.plot(test_es.index, test_es['Close_Predicted_ES'], label='Predicted Test Data (ES)', linestyle='--')
plt.title('TCBI Exponential Smoothing Forecasting')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment