import numpy as np
import matplotlib.pyplot as plt
from pandas_datareader import info as pdr
import yfinance as yf
from datetime import datetime, timedelta
import tensorflow as tf
import xgboost as xgb
from sklearn.metrics import mean_squared_error
# Assure yfinance overrides
yf.pdr_override()
# Get the stock quote
df = pdr.get_data_yahoo(‘AMD’, start=’2022-04-01′, end=datetime.now())
# Create a model new dataframe with solely the ‘Shut’ column
info = df.filter([‘Close’])
# Convert the dataframe to a numpy array
dataset = info.values
# Get the number of rows to teach the model on
training_data_len = int(np.ceil(len(dataset) * .95))
# Scale the knowledge using TensorFlow Normalization
normalizer = tf.keras.layers.Normalization()
normalizer.adapt(dataset)
scaled_data = normalizer(dataset)
# Create the teaching info set
train_data = scaled_data[:training_data_len]
# Create the testing info set
test_data = scaled_data[training_data_len – 60:]
# Lower up the knowledge into x_train and y_train info models
x_train = []
y_train = []
for i in differ(60, len(train_data)):
x_train.append(train_data[i-60:i])
y_train.append(train_data[i])
# Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
# Lower up the knowledge into x_test and y_test info models
x_test = []
y_test = dataset[training_data_len:]
for i in differ(60, len(test_data)):
x_test.append(test_data[i-60:i])
# Convert the x_test to a numpy array
x_test = np.array(x_test)
# Reshape the knowledge for XGBoost
x_train = x_train.reshape((x_train.type[0], x_train.type[1]))
x_test = x_test.reshape((x_test.type[0], x_test.type[1]))
# Follow the XGBoost model
model = xgb.XGBRegressor(aim=’reg:squarederror’, n_estimators=1000)
model.match(x_train, y_train)
# Get the model’s predicted worth values
predictions = model.predict(x_test)
predictions = predictions.reshape(-1, 1)
predictions = normalizer.suggest.numpy() + predictions * normalizer.variance.numpy() ** 0.5
# Get the muse suggest squared error (RMSE)
rmse = np.sqrt(mean_squared_error(y_test, predictions))
print(‘RMSE: ‘, rmse)
# Predict the next 10 days
last_60_days = scaled_data[-60:].numpy() # Convert to numpy array
next_10_days = []
for i in differ(10):
X_test = last_60_days[-60:].reshape(1, -1)
pred_price = model.predict(X_test)
pred_price = normalizer.suggest.numpy() + pred_price * normalizer.variance.numpy() ** 0.5
next_10_days.append(pred_price[0])
last_60_days = np.append(last_60_days, pred_price).reshape(-1, 1)[-60:]
# Create a dataframe for the next 10 days
last_date = df.index[-1]
future_dates = [last_date + timedelta(days=i) for i in range(1, 11)]
future_predictions = pd.DataFrame(info={‘Date’: future_dates, ‘Shut’: next_10_days})
future_predictions.set_index(‘Date’, inplace=True)
# Create dataframes for plotting and saving
follow = info[:training_data_len]
respectable = info[training_data_len:]
respectable[‘Predictions’] = predictions
# Save to Excel
with pd.ExcelWriter(‘stock_predictions_xgboost.xlsx’) as writer:
follow.to_excel(writer, sheet_name=’Follow’)
respectable.to_excel(writer, sheet_name=’Validation’)
future_predictions.to_excel(writer, sheet_name=’Future’)
# Plot the knowledge
plt.decide(figsize=(16, 6))
plt.title(‘Model’)
plt.xlabel(‘Date’, fontsize=18)
plt.ylabel(‘Shut Price USD ($)’, fontsize=18)
plt.plot(follow[‘Close’])
plt.plot(respectable[[‘Close’, ‘Predictions’]])
plt.plot(future_predictions[‘Close’], marker=’o’, linestyle=’dashed’, color=’crimson’)
plt.legend([‘Train’, ‘Val’, ‘Predictions’, ‘Future’], loc=’lower correct’)
plt.current()