Introduction
Stock price prediction is a challenging task that has garnered significant attention in recent years. The ability to accurately predict stock prices can help investors make informed decisions and potentially lead to substantial financial gains. In this article, we will explore the implementation of a custom AI agent for real-time stock price prediction using Python and TensorFlow.
The AI agent will utilize a combination of technical indicators and machine learning algorithms to predict future stock prices. We will delve into the details of the implementation, including data preparation, model selection, and hyperparameter tuning. By the end of this article, you will have a solid understanding of how to build a custom AI agent for real-time stock price prediction using Python and TensorFlow.
Data Preparation
The first step in building our AI agent is to prepare the data. We will use historical stock price data, which can be obtained from various sources such as Yahoo Finance or Quandl. For this example, we will use the Yahoo Finance API to retrieve the historical stock price data for Apple (AAPL).
import yfinance as yf
import pandas as pd
# Retrieve historical stock price data for Apple (AAPL)
data = yf.download('AAPL', start='2010-01-01', end='2022-02-26')
# Convert data to pandas dataframe
df = pd.DataFrame(data)
# Print the first few rows of the dataframe
print(df.head())
Feature Engineering
Once we have the historical stock price data, we need to engineer features that can be used by our machine learning model to predict future stock prices. Some common technical indicators used in stock price prediction include:
- Moving Averages (MA)
- Relative Strength Index (RSI)
- Bollinger Bands (BB)
- Exponential Moving Average (EMA)
We will calculate these technical indicators and add them to our dataframe.
import numpy as np
# Calculate moving averages
df['MA_50'] = df['Close'].rolling(window=50).mean()
df['MA_200'] = df['Close'].rolling(window=200).mean()
# Calculate relative strength index (RSI)
delta = df['Close'].diff(1)
up, down = delta.copy(), delta.copy()
up[up < 0] = 0
down[down > 0] = 0
roll_up = up.rolling(window=14).mean()
roll_down = down.rolling(window=14).mean().abs()
RS = roll_up / roll_down
RSI = 100.0 - (100.0 / (1.0 + RS))
df['RSI'] = RSI
# Calculate bollinger bands
df['BB_Middle'] = df['Close'].rolling(window=20).mean()
df['BB_Upper'] = df['BB_Middle'] + 2*df['Close'].rolling(window=20).std()
df['BB_Lower'] = df['BB_Middle'] - 2*df['Close'].rolling(window=20).std()
# Calculate exponential moving average (EMA)
df['EMA_12'] = df['Close'].ewm(span=12, adjust=False).mean()
df['EMA_26'] = df['Close'].ewm(span=26, adjust=False).mean()
Model Selection
Now that we have our feature-engineered dataframe, we need to select a suitable machine learning model for predicting stock prices. Some popular models used in stock price prediction include:
- Linear Regression
- Decision Trees
- Random Forest
- Long Short-Term Memory (LSTM) Networks
For this example, we will use an LSTM network, which is well-suited for time-series forecasting tasks.
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
# Scale the data
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(df)
# Split the data into training and testing sets
train_size = int(len(scaled_data) * 0.8)
train_data, test_data = scaled_data[0:train_size, :], scaled_data[train_size - len(scaled_data):, :]
# Split the data into input (X) and output (y) variables
X_train = []
y_train = []
for i in range(60, len(train_data)):
X_train.append(train_data[i-60:i, 0])
y_train.append(train_data[i, 0])
X_train, y_train = np.array(X_train), np.array(y_train)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
# Build the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Train the model
model.fit(X_train, y_train, batch_size=1, epochs=1)
Hyperparameter Tuning
Hyperparameter tuning is an essential step in building a robust machine learning model. Some hyperparameters that can be tuned in our LSTM model include:
- Number of LSTM layers
- Number of units in each LSTM layer
- Activation function used in the LSTM layers
- Optimizer used to train the model
- Learning rate of the optimizer
We can use a grid search or random search to find the optimal combination of hyperparameters.
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import GridSearchCV
# Define the LSTM model architecture
def create_model(optimizer='adam'):
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
model.compile(optimizer=optimizer, loss='mean_squared_error')
return model
# Define the hyperparameter search space
optimizer = ['adam', 'rmsprop', 'sgd']
epochs = [1, 5, 10]
batch_size = [1, 5, 10]
# Perform grid search to find the optimal hyperparameters
model = KerasRegressor(build_fn=create_model)
grid = dict(optimizer=optimizer, epochs=epochs, batch_size=batch_size)
grid_search = GridSearchCV(estimator=model, param_grid=grid, cv=3)
grid_search_result = grid_search.fit(X_train, y_train)
# Print the optimal hyperparameters
print("Best: %f using %s" % (grid_search_result.best_score_, grid_search_result.best_params_))
Real-Time Stock Price Prediction
Now that we have built and trained our LSTM model, we can use it to make real-time stock price predictions. We can use the yfinance library to retrieve the latest stock price data and then use our model to predict the future stock price.
# Retrieve the latest stock price data
data = yf.download('AAPL', period='1d')
# Preprocess the data
scaled_data = scaler.transform(data)
# Make predictions using the LSTM model
predictions = model.predict(scaled_data)
# Print the predicted stock price
print(predictions)
Conclusion
In this article, we explored the implementation of a custom AI agent for real-time stock price prediction using Python and TensorFlow. We covered data preparation, feature engineering, model selection, hyperparameter tuning, and real-time stock price prediction. By following the steps outlined in this article, you can build your own custom AI agent for stock price prediction and start making informed investment decisions.
Remember to always use caution when investing in the stock market and to never invest more than you can afford to lose. Happy investing!
Top comments (0)