Rozumiem, że chcesz, abym wygenerował gotowy plik notebooka w formacie .ipynb. Oto, co mogę zrobić — stworzę plik notebooka z treścią, którą wcześniej dostarczyłeś.
Krok 1: Przygotowanie pliku .ipynb
Poniżej znajdziesz zawartość całego notebooka w formacie .ipynb. Możesz skopiować tę zawartość do pliku o nazwie Advanced_Stock_Pattern_Prediction_LSTM_Attention.ipynb lub pobrać go bezpośrednio.
Krok 2: Skrypt do generowania notebooka
Wklej poniższy kod do swojego lokalnego środowiska Python lub do nowego notebooka i uruchom, aby stworzyć plik:
import json
notebook_content = {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Advanced Stock Pattern Prediction using LSTM with the Attention Mechanism in TensorFlow: A Step by Step Guide\n",
"\n",
"## Authors: Dr. Ernesto Lee"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Introduction\n",
"In the rapidly evolving world of financial markets, accurate predictions are akin to a holy grail. As we seek more sophisticated techniques to interpret market trends, machine learning emerges as a beacon of hope. Among various machine learning models, Long Short-Term Memory (LSTM) networks have gained significant attention. When combined with the attention mechanism, these models become even more powerful, especially in analyzing time-series data like stock prices. This article delves into the intriguing world of LSTM networks paired with attention mechanisms, focusing on predicting the pattern of the next four candles in the stock price of Apple Inc. (AAPL), utilizing data from Yahoo Finance (yfinance)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Section 1: Understanding LSTM and Attention in Financial Modelling\n",
"\n",
"### The Basics of LSTM Networks\n",
"LSTM networks are a type of Recurrent Neural Network (RNN) specially designed to remember and process sequences of data over long periods. LSTMs consist of three gates: input, forget, and output gates, which manage the flow of information and mitigate the issue of vanishing gradients.\n",
"\n",
"In the context of financial markets, the capability to remember long-term dependencies is invaluable. Stock prices are influenced not only by recent trends but also by historical patterns, which LSTM networks adeptly capture."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Attention Mechanism: Enhancing LSTM\n",
"The attention mechanism allows the model to focus on specific parts of the input sequence, enhancing context understanding. Incorporating attention into LSTM networks creates a model that can weight important historical data points more heavily for improved predictions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The Relevance in Financial Pattern Prediction\n",
"By combining LSTM with attention mechanisms, we obtain a robust model for financial pattern prediction. Traditional models often fall short in capturing the complexity of financial markets, while LSTMs combined with attention excel in this area."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Section 2: Setting Up Your Environment\n",
"\n",
"To begin building our LSTM model with attention for predicting AAPL stock patterns, we need to set up our coding environment in Google Colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install tensorflow -qqq\n",
"!pip install keras -qqq\n",
"!pip install yfinance -qqq"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Setting Up the Environment\n",
"After installation, we can import the libraries into our Python environment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"import keras\n",
"import yfinance as yf\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Check TensorFlow version\n",
"print(\"TensorFlow Version: \", tf.__version__)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Section 3: Data Acquisition from yfinance\n",
"\n",
"### Fetching Historical Data\n",
"To analyze AAPL stock patterns, we need historical stock price data. Here’s where yfinance comes into play."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Fetch AAPL data\n",
"aapl_data = yf.download('AAPL', start='2020-01-01', end='2024-01-01')\n",
"\n",
"# Display the first few rows of the dataframe\n",
"aapl_data.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The Importance of Data Preprocessing and Feature Selection\n",
"Preprocessing involves cleaning the data and making it suitable for the model. This includes handling missing values and normalizing or scaling data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Checking for missing values\n",
"aapl_data.isnull().sum()\n",
"\n",
"# Filling missing values, if any\n",
"aapl_data.fillna(method='ffill', inplace=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Normalization\n",
"Normalization is a technique used to change the values of numeric columns in the dataset to a common scale.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.preprocessing import MinMaxScaler\n",
"\n",
"scaler = MinMaxScaler(feature_range=(0,1))\n",
"aapl_data_scaled = scaler.fit_transform(aapl_data['Close'].values.reshape(-1,1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Creating Sequences\n",
"LSTM models require input to be in a sequence format. We transform the data into sequences for the model to learn from."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X = []\n",
"y = []\n",
"\n",
"for i in range(60, len(aapl_data_scaled)):\n",
" X.append(aapl_data_scaled[i-60:i, 0])\n",
" y.append(aapl_data_scaled[i, 0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Train-Test Split\n",
"Split the data into training and testing sets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"train_size = int(len(X) * 0.8)\n",
"test_size = len(X) - train_size\n",
"\n",
"X_train, X_test = X[:train_size], X[train_size:]\n",
"y_train, y_test = y[:train_size], y[train_size:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Reshaping Data for LSTM\n",
"Reshape our data into a 3D format as required by LSTM layers."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X_train, y_train = np.array(X_train), np.array(y_train)\n",
"X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Section 4: Building the LSTM with Attention Model\n",
"### Constructing the Model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from keras.models import Sequential\n",
"from keras.layers import LSTM, Dense, Dropout, AdditiveAttention, Permute, Reshape, Multiply\n",
"\n",
"model = Sequential()\n",
"\n",
"# Adding LSTM layers with return_sequences=True\n",
"model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))\n",
"model.add(LSTM(units=50, return_sequences=True))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Integrating the Attention Mechanism\n",
"The attention mechanism enhances the model’s ability to focus on relevant time steps."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Adding self-attention mechanism\n",
"attention = AdditiveAttention(name='attention_weight')\n",
"# Permute and reshape for compatibility\n",
"model.add(Permute((2, 1))) \n",
"model.add(Reshape((-1, X_train.shape[1])))\n",
"attention_result = attention([model.output, model.output])\n",
"multiply_layer = Multiply()([model.output, attention_result])\n",
"# Return to original shape\n",
"model.add(Permute((2, 1))) \n",
"model.add(Reshape((-1, 50)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Optimizing the Model\n",
"To enhance the model's performance and reduce overfitting, we include Dropout and Batch Normalization."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from keras.layers import BatchNormalization\n",
"\n",
"# Adding Dropout and Batch Normalization\n",
"model.add(Dropout(0.2))\n",
"model.add(BatchNormalization())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Model Compilation\n",
"Compile the model with an optimizer and loss function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model.compile(optimizer='adam', loss='mean_squared_error')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Model Summary\n",
"View the summary of the model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Section 5: Training the Model\n",
"Now that our LSTM model with attention is built, it’s time to train it using our prepared training set."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Assuming X_train and y_train are already defined and preprocessed\n",
"history = model.fit(X_train, y_train, epochs=100, batch_size=25, validation_split=0.2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Section 6: Evaluating Model Performance\n",
"After training the model, the next step is to evaluate its performance using the test set."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Convert X_test and y_test to Numpy arrays if they are not already\n",
"X_test = np.array(X_test)\n",
"y_test = np.array(y_test)\n",
"\n",
"# Ensure X_test is reshaped similarly to how X_train was reshaped\n",
"X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))\n",
"\n",
"# Now evaluate the model on the test data\n",
"test_loss = model.evaluate(X_test, y_test)\n",
"print(\"Test Loss: \", test_loss)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Performance Metrics\n",
"In addition to the loss, other metrics can provide more insights into the model's performance."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
"\n",
"# Making predictions\n",
"y_pred = model.predict(X_test)\n",
"\n",
"# Calculating MAE and RMSE\n",
"mae = mean_absolute_error(y_test, y_pred)\n",
"rmse = mean_squared_error(y_test, y_pred, squared=False)\n",
"\n",
"print(\"Mean Absolute Error: \", mae)\n",
"print(\"Root Mean Square Error: \", rmse)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Section 7: Predicting the Next 4 Candles\n",
"Having trained and evaluated our LSTM model with an attention mechanism, the final step is to utilize it for predicting the next 4 candles (days) of AAPL stock prices."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Fetching the latest 60 days of AAPL stock data\n",
"data = yf.download('AAPL', period='60d', interval='1d')\n",
"# Selecting the 'Close' price and converting to numpy array\n",
"closing_prices = data['Close'].values\n",
"# Scaling the data\n",
"scaler = MinMaxScaler(feature_range=(0,1))\n",
"scaled_data = scaler.fit_transform(closing_prices.reshape(-1,1))\n",
"# Since we need the last 60 days to predict the next day, we reshape the data accordingly\n",
"X_latest = np.array([scaled_data[-60:].reshape(60)])\n",
"# Reshaping the data for the model (adding batch dimension)\n",
"X_latest = np.reshape(X_latest, (X_latest.shape[0], X_latest.shape[1], 1))\n",
"# Making predictions for the next 4 candles\n",
"predicted_stock_price = model.predict(X_latest)\n",
"predicted_stock_price = scaler.inverse_transform(predicted_stock_price)\n",
"print(\"Predicted Stock Prices for the next 4 days: \", predicted_stock_price)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Visualization of Predictions\n",
"Comparing the predicted values with actual stock prices visually can be very insightful."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install mplfinance -qqq\n",
"import pandas as pd\n",
"import mplfinance as mpf\n",
"import matplotlib.dates as mpl_dates\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Assuming 'data' is your DataFrame with the fetched AAPL stock data\n",
"# Make sure it contains Open, High, Low, Close, and Volume columns\n",
"# Creating a list of dates for the predictions\n",
"last_date = data.index[-1]\n",
"next_day = last_date + pd.Timedelta(days=1)\n",
"prediction_dates = pd.date_range(start=next_day, periods=4)\n",
"# Overlaying the predicted data\n",
"plt.figure(figsize=(10,6))\n",
"plt.plot(predictions_df.index, predictions_df['Close'], linestyle='dashed', marker='o', color='red')\n",
"plt.title(\"AAPL Stock Price with Predicted Next 4 Days\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Conclusion\n",
"In this guide, we explored the complex task of using LSTM networks with an attention mechanism for stock price prediction, specifically for Apple Inc. (AAPL). Key points include:\n",
"- LSTM’s ability to capture long-term dependencies in time-series data.\n",
"- The added advantage of the attention mechanism in focusing on relevant data points.\n",
"- The detailed process of building, training, and evaluating the LSTM model."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### References\n",
"- TensorFlow Documentation: https://www.tensorflow.org/\n",
"- Keras API Reference: https://keras.io/api/\n",
"- Yahoo Finance (yfinance) for Stock Data: https://pypi.org/project/yfinance/\n",
"- Pandas Documentation: https://pandas.pydata.org/\n",
"- Matplotlib for Visualization: https://matplotlib.org/"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
# Save the notebook content to a .ipynb file
with open('Advanced_Stock_Pattern_Prediction_LSTM_Attention.ipynb', 'w') as f:
json.dump(notebook_content, f)
Krok 3: Uruchomienie
Po uruchomieniu powyższego kodu, plik Advanced_Stock_Pattern_Prediction_LSTM_Attention.ipynb zostanie utworzony w bieżącym katalogu roboczym.
Krok 4: Przesyłanie do Google Colab
Możesz teraz przesłać ten plik do Google Colab, aby zacząć pracować nad modelem LSTM z mechanizmem uwagi.
Czy chcesz, abym stworzył plik bezpośrednio dla Ciebie? Jeśli tak, możesz przekazać mi mniej więcej informacje, w jaki sposób chcesz uzyskać dostęp do pliku!