一、介紹
????????在瞬息萬變的金融市場(chǎng)中,準(zhǔn)確的預(yù)測(cè)就像圣杯一樣。當(dāng)我們尋求更復(fù)雜的技術(shù)來解釋市場(chǎng)趨勢(shì)時(shí),機(jī)器學(xué)習(xí)成為希望的燈塔。在各種機(jī)器學(xué)習(xí)模型中,長(zhǎng)短期記憶(LSTM)網(wǎng)絡(luò)受到了極大的關(guān)注。當(dāng)與注意力機(jī)制相結(jié)合時(shí),這些模型變得更加強(qiáng)大,尤其是在分析股票價(jià)格等時(shí)間序列數(shù)據(jù)時(shí)。本文深入探討了LSTM網(wǎng)絡(luò)與注意力機(jī)制相結(jié)合的有趣世界,重點(diǎn)利用雅虎財(cái)經(jīng)(yfinance)的數(shù)據(jù)預(yù)測(cè)蘋果公司(AAPL)股價(jià)接下來的四根蠟燭的模式。所有數(shù)據(jù)都在這里。
二、第 1 部分:了解 LSTM 和財(cái)務(wù)建模中的注意
2.1 LSTM 網(wǎng)絡(luò)的基礎(chǔ)知識(shí)
????????LSTM 網(wǎng)絡(luò)是一種遞歸神經(jīng)網(wǎng)絡(luò) (RNN),專門設(shè)計(jì)用于長(zhǎng)時(shí)間記憶和處理數(shù)據(jù)序列。LSTM 與傳統(tǒng) RNN 的區(qū)別在于它們能夠長(zhǎng)時(shí)間保存信息,這要?dú)w功于其獨(dú)特的結(jié)構(gòu),包括三個(gè)門:輸入門、忘記門和輸出門。這些門協(xié)同管理信息流,決定保留什么和丟棄什么,從而緩解梯度消失的問題——這是標(biāo)準(zhǔn) RNN 中的常見問題。
????????在金融市場(chǎng)的背景下,這種記住和利用長(zhǎng)期依賴關(guān)系的能力是無價(jià)的。例如,股票價(jià)格不僅受到近期趨勢(shì)的影響,還受到隨著時(shí)間的推移建立的模式的影響。LSTM 網(wǎng)絡(luò)能夠熟練地捕獲這些時(shí)間依賴關(guān)系,使其成為金融時(shí)間序列分析的理想選擇。
2.2 注意機(jī)制:增強(qiáng)LSTM
????????注意力機(jī)制最初在自然語言處理領(lǐng)域普及,現(xiàn)已進(jìn)入包括金融在內(nèi)的其他各個(gè)領(lǐng)域。它基于一個(gè)簡(jiǎn)單而深刻的概念:并非輸入序列的所有部分都同樣重要。通過允許模型專注于輸入序列的特定部分而忽略其他部分,注意力機(jī)制增強(qiáng)了模型的上下文理解能力。
????????將注意力整合到 LSTM 網(wǎng)絡(luò)中會(huì)產(chǎn)生更集中和上下文感知的模型。在預(yù)測(cè)股票價(jià)格時(shí),某些歷史數(shù)據(jù)點(diǎn)可能比其他數(shù)據(jù)點(diǎn)更相關(guān)。注意力機(jī)制使 LSTM 能夠更嚴(yán)格地權(quán)衡這些點(diǎn),從而做出更準(zhǔn)確和細(xì)致的預(yù)測(cè)。
2.3 金融模式預(yù)測(cè)的相關(guān)性
????????LSTM與注意力機(jī)制的結(jié)合為金融模式預(yù)測(cè)創(chuàng)造了一個(gè)強(qiáng)大的模型。金融市場(chǎng)是一個(gè)復(fù)雜的適應(yīng)性系統(tǒng),受多種因素影響,并表現(xiàn)出非線性特征。傳統(tǒng)模型往往無法捕捉到這種復(fù)雜性。然而,LSTM網(wǎng)絡(luò),特別是當(dāng)與注意力機(jī)制相結(jié)合時(shí),善于解開這些模式,提供對(duì)未來股票走勢(shì)的更深入理解和更準(zhǔn)確的預(yù)測(cè)。
????????當(dāng)我們繼續(xù)構(gòu)建和實(shí)施具有注意力機(jī)制的 LSTM 來預(yù)測(cè) AAPL 股票接下來的四根蠟燭時(shí),我們深入研究了一個(gè)復(fù)雜的財(cái)務(wù)分析領(lǐng)域,該領(lǐng)域有望徹底改變我們?nèi)绾谓忉尯蛻?yīng)對(duì)不斷變化的股票市場(chǎng)動(dòng)態(tài)。
三、第 2 部分:設(shè)置環(huán)境
????????要開始構(gòu)建我們的 LSTM 模型并注意預(yù)測(cè) AAPL 股票模式,第一步是在 Google Colab 中設(shè)置我們的編碼環(huán)境。Google Colab 提供基于云的服務(wù),提供免費(fèi)的 Jupyter 筆記本環(huán)境,支持 GPU,非常適合運(yùn)行深度學(xué)習(xí)模型。
!pip install tensorflow -qqq
!pip install keras -qqq
!pip install yfinance -qqq
3.1 設(shè)置環(huán)境
????????安裝后,我們可以將這些庫導(dǎo)入到我們的 Python 環(huán)境中。運(yùn)行以下代碼:
import tensorflow as tf
import keras
import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Check TensorFlow version
print("TensorFlow Version: ", tf.__version__)
????????此代碼不僅導(dǎo)入庫,還檢查 TensorFlow 版本以確保所有內(nèi)容都是最新的。
3.2 yfinance的數(shù)據(jù)采集
2.2.1 獲取歷史數(shù)據(jù)
????????要分析 AAPL 股票模式,我們需要?dú)v史股價(jià)數(shù)據(jù)。這就是 yfinance 發(fā)揮作用的地方。該庫旨在從雅虎財(cái)經(jīng)獲取歷史市場(chǎng)數(shù)據(jù)。
3.2.2. 數(shù)據(jù)下載代碼
在 Colab 筆記本中運(yùn)行以下代碼以下載 AAPL 的歷史數(shù)據(jù):
# Fetch AAPL data
aapl_data = yf.download('AAPL', start='2020-01-01', end='2024-01-01')
# Display the first few rows of the dataframe
aapl_data.head()
????????此腳本獲取 Apple Inc. 從 2020 年 1 月 1 日到 2024 年 1 月 1 日的每日股價(jià)。您可以根據(jù)自己的喜好調(diào)整開始日期和結(jié)束日期。
3.3 數(shù)據(jù)預(yù)處理和特征選擇的重要性
????????獲取數(shù)據(jù)后,預(yù)處理和特征選擇變得至關(guān)重要。預(yù)處理涉及清理數(shù)據(jù)并使其適合模型。這包括處理缺失值、規(guī)范化或縮放數(shù)據(jù),以及可能創(chuàng)建其他特征,如移動(dòng)平均值或百分比變化,以幫助模型更有效地學(xué)習(xí)。
????????特征選擇是關(guān)于選擇對(duì)預(yù)測(cè)變量貢獻(xiàn)最大的正確特征集。對(duì)于股票價(jià)格預(yù)測(cè),通常使用開盤價(jià)、收盤價(jià)、最高價(jià)、最低價(jià)和成交量等特征。選擇提供相關(guān)信息的特征以防止模型從噪聲中學(xué)習(xí)非常重要。
在接下來的章節(jié)中,我們將對(duì)這些數(shù)據(jù)進(jìn)行預(yù)處理,并使用注意力層構(gòu)建 LSTM 模型以開始進(jìn)行預(yù)測(cè)。
四、第 3 部分:數(shù)據(jù)預(yù)處理和準(zhǔn)備
????????在構(gòu)建 LSTM 模型之前,第一個(gè)關(guān)鍵步驟是準(zhǔn)備我們的數(shù)據(jù)集。本節(jié)介紹了數(shù)據(jù)預(yù)處理的基本階段,以使 yfinance 的 AAPL 股票數(shù)據(jù)為我們的 LSTM 模型做好準(zhǔn)備。
4.1 數(shù)據(jù)清理
????????股票市場(chǎng)數(shù)據(jù)集通常包含異常或缺失值。處理這些問題以防止預(yù)測(cè)不準(zhǔn)確至關(guān)重要。
- 識(shí)別缺失值:檢查數(shù)據(jù)集中是否有任何缺失數(shù)據(jù)。如果有,您可以選擇使用正向填充或向后填充等方法填充它們,或者完全刪除這些行。
# Checking for missing values
aapl_data.isnull().sum()
# Filling missing values, if any
aapl_data.fillna(method='ffill', inplace=True)
- 處理異常:有時(shí),由于數(shù)據(jù)收集中的故障,數(shù)據(jù)集包含錯(cuò)誤的值。如果您發(fā)現(xiàn)任何異常情況(例如不切實(shí)際的股價(jià)極端飆升),則應(yīng)糾正或刪除它們。
4.2 功能選擇
????????在股票市場(chǎng)數(shù)據(jù)中,各種特征都可能具有影響力。通常使用“開盤價(jià)”、“最高價(jià)”、“最低價(jià)”、“收盤價(jià)”和“成交量”。
- 決定功能:對(duì)于我們的模型,我們將使用“收盤價(jià)”,但您可以嘗試使用其他功能,例如“開盤價(jià)”、“最高價(jià)”、“最低價(jià)”和“成交量”。
4.3 正常化
????????歸一化是一種用于將數(shù)據(jù)集中數(shù)值列的值更改為通用比例的技術(shù),而不會(huì)扭曲值范圍的差異。
- 應(yīng)用最小-最大縮放:這將縮放數(shù)據(jù)集,使所有輸入要素都位于 0 和 1 之間。
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0,1))
aapl_data_scaled = scaler.fit_transform(aapl_data['Close'].values.reshape(-1,1))
4.4 創(chuàng)建序列
LSTM 模型要求輸入采用序列格式。我們將數(shù)據(jù)轉(zhuǎn)換為序列,供模型學(xué)習(xí)。
- 定義序列長(zhǎng)度:選擇序列長(zhǎng)度(如 60 天)。這意味著,對(duì)于每個(gè)樣本,模型將查看過去 60 天的數(shù)據(jù)以做出預(yù)測(cè)。
X = []
y = []
for i in range(60, len(aapl_data_scaled)):
X.append(aapl_data_scaled[i-60:i, 0])
y.append(aapl_data_scaled[i, 0])
4.5 訓(xùn)練-測(cè)試拆分
將數(shù)據(jù)拆分為訓(xùn)練集和測(cè)試集,以正確評(píng)估模型的性能。
- 定義拆分率:通常,80% 的數(shù)據(jù)用于訓(xùn)練,20% 用于測(cè)試。
train_size = int(len(X) * 0.8)
test_size = len(X) - train_size
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]
4.6 重塑 LSTM 的數(shù)據(jù)
????????最后,我們需要將數(shù)據(jù)重塑為 LSTM 圖層所需的 3D 格式。[samples, time steps, features]
- 重塑數(shù)據(jù):
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))
在下一節(jié)中,我們將利用這些預(yù)處理的數(shù)據(jù)來構(gòu)建和訓(xùn)練具有注意力機(jī)制的 LSTM 模型。
五、第 4 部分:使用注意力模型構(gòu)建 LSTM
在本節(jié)中,我們將深入探討 LSTM 模型的構(gòu)建,該模型具有額外的注意力機(jī)制,專為預(yù)測(cè) AAPL 股票模式而量身定制。這需要 TensorFlow 和 Keras,它們應(yīng)該已經(jīng)在 Colab 環(huán)境中設(shè)置好了。
5.1 創(chuàng)建 LSTM 圖層
????????我們的 LSTM 模型將由多個(gè)層組成,包括用于處理時(shí)間序列數(shù)據(jù)的 LSTM 層?;窘Y(jié)構(gòu)如下:
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout, AdditiveAttention, Permute, Reshape, Multiply
model = Sequential()
# Adding LSTM layers with return_sequences=True
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(units=50, return_sequences=True))
在此模型中,表示每個(gè) LSTM 層中的神經(jīng)元數(shù)。 units
return_sequences=True
在第一層中至關(guān)重要,以確保輸出包含序列,這對(duì)于堆疊 LSTM 層至關(guān)重要。當(dāng)我們?yōu)樽⒁饬訙?zhǔn)備數(shù)據(jù)時(shí),最終的 LSTM 層不會(huì)返回序列。
5.2 整合注意力機(jī)制
????????可以添加注意力機(jī)制來增強(qiáng)模型關(guān)注相關(guān)時(shí)間步長(zhǎng)的能力:
# Adding self-attention mechanism
# The attention mechanism
attention = AdditiveAttention(name='attention_weight')
# Permute and reshape for compatibility
model.add(Permute((2, 1)))
model.add(Reshape((-1, X_train.shape[1])))
attention_result = attention([model.output, model.output])
multiply_layer = Multiply()([model.output, attention_result])
# Return to original shape
model.add(Permute((2, 1)))
model.add(Reshape((-1, 50)))
# Adding a Flatten layer before the final Dense layer
model.add(tf.keras.layers.Flatten())
# Final Dense layer
model.add(Dense(1))
# Compile the model
# model.compile(optimizer='adam', loss='mean_squared_error')
# Train the model
# history = model.fit(X_train, y_train, epochs=100, batch_size=25, validation_split=0.2)
????????此自定義層計(jì)算輸入序列的加權(quán)總和,使模型能夠更加關(guān)注某些時(shí)間步長(zhǎng)。
5.3 優(yōu)化模型
????????為了提高模型的性能并降低過擬合的風(fēng)險(xiǎn),我們包括了 Dropout 和 Batch Normalization。
from keras.layers import BatchNormalization
# Adding Dropout and Batch Normalization
model.add(Dropout(0.2))
model.add(BatchNormalization())
????????在訓(xùn)練期間,每次更新時(shí),Dropout 都會(huì)將一部分輸入單位隨機(jī)設(shè)置為 0,從而有助于防止過擬合,而批量歸一化則穩(wěn)定了學(xué)習(xí)過程。
5.4 模型編譯
????????最后,我們使用適合回歸任務(wù)的優(yōu)化器和損失函數(shù)編譯模型。
model.compile(optimizer='adam', loss='mean_squared_error')
??adam
優(yōu)化器通常是遞歸神經(jīng)網(wǎng)絡(luò)的不錯(cuò)選擇,而均方誤差可以很好地用作像我們這樣的回歸任務(wù)的損失函數(shù)。
5.5 模型摘要
查看模型的摘要以了解其結(jié)構(gòu)和參數(shù)數(shù)是有益的。
model.summary()
六、第 5 部分:訓(xùn)練模型
????????現(xiàn)在,我們的 LSTM 模型已經(jīng)構(gòu)建好了,是時(shí)候使用我們準(zhǔn)備好的訓(xùn)練集來訓(xùn)練它了。此過程涉及將訓(xùn)練數(shù)據(jù)提供給模型并讓它學(xué)習(xí)進(jìn)行預(yù)測(cè)。
6.1 培訓(xùn)代碼
????????使用以下代碼使用 X_train
和 y_train
訓(xùn)練模型:
# Assuming X_train and y_train are already defined and preprocessed
history = model.fit(X_train, y_train, epochs=100, batch_size=25, validation_split=0.2)
????????在這里,我們訓(xùn)練 100 個(gè) epoch 的模型,批處理大小為 25。該參數(shù)保留了一部分訓(xùn)練數(shù)據(jù)進(jìn)行驗(yàn)證,validation_split
使我們能夠在訓(xùn)練期間監(jiān)控模型在看不見的數(shù)據(jù)上的性能。
6.2 過擬合以及如何避免過擬合
????????當(dāng)模型學(xué)習(xí)特定于訓(xùn)練數(shù)據(jù)的模式時(shí),就會(huì)發(fā)生過擬合,這些模式不會(huì)泛化到新數(shù)據(jù)。以下是避免過度擬合的方法:
- 驗(yàn)證集:使用驗(yàn)證集(正如我們?cè)谟?xùn)練代碼中所做的那樣)有助于監(jiān)控模型在看不見的數(shù)據(jù)上的性能。
- 提前停止:當(dāng)模型在驗(yàn)證集上的性能開始下降時(shí),此技術(shù)將停止訓(xùn)練。在 Keras 中實(shí)現(xiàn)提前停止很簡(jiǎn)單:
from keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='val_loss', patience=10)
history = model.fit(X_train, y_train, epochs=100, batch_size=25, validation_split=0.2, callbacks=[early_stopping])
- 在這里,如果驗(yàn)證損失連續(xù) 10 個(gè)周期沒有改善,則表示訓(xùn)練將停止。
patience=10
- 正則化技術(shù):像 Dropout 和 Batch Normalization 這樣的技術(shù)已經(jīng)包含在我們的模型中,也有助于減少過擬合。
可選:這些是更多回調(diào)
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard, CSVLogger
# Callback to save the model periodically
model_checkpoint = ModelCheckpoint('best_model.h5', save_best_only=True, monitor='val_loss')
# Callback to reduce learning rate when a metric has stopped improving
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5)
# Callback for TensorBoard
tensorboard = TensorBoard(log_dir='./logs')
# Callback to log details to a CSV file
csv_logger = CSVLogger('training_log.csv')
# Combining all callbacks
callbacks_list = [early_stopping, model_checkpoint, reduce_lr, tensorboard, csv_logger]
# Fit the model with the callbacks
history = model.fit(X_train, y_train, epochs=100, batch_size=25, validation_split=0.2, callbacks=callbacks_list)
七、第 6 部分:評(píng)估模型性能
????????訓(xùn)練模型后,下一步是使用測(cè)試集評(píng)估其性能。這將使我們了解我們的模型可以很好地推廣到新的、看不見的數(shù)據(jù)。
7.1 使用測(cè)試集進(jìn)行評(píng)估
????????為了評(píng)估模型,我們首先需要準(zhǔn)備測(cè)試數(shù)據(jù)X_test
(),就像我們對(duì)訓(xùn)練數(shù)據(jù)所做的那樣。然后,我們可以使用模型的函數(shù):???????evaluate
# Convert X_test and y_test to Numpy arrays if they are not already
X_test = np.array(X_test)
y_test = np.array(y_test)
# Ensure X_test is reshaped similarly to how X_train was reshaped
# This depends on how you preprocessed the training data
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# Now evaluate the model on the test data
test_loss = model.evaluate(X_test, y_test)
print("Test Loss: ", test_loss)
7.2 性能指標(biāo)
????????除了損失之外,其他指標(biāo)還可以提供對(duì)模型性能的更多見解。對(duì)于像我們這樣的回歸任務(wù),常見指標(biāo)包括:
- 平均絕對(duì)誤差 (MAE):它測(cè)量一組預(yù)測(cè)中誤差的平均幅度,而不考慮其方向。
- 均方根誤差 (RMSE):這是預(yù)測(cè)和實(shí)際觀測(cè)值之間平方差平均值的平方根。
為了計(jì)算這些指標(biāo),我們可以使用我們的模型進(jìn)行預(yù)測(cè),并將它們與實(shí)際值進(jìn)行比較:
from sklearn.metrics import mean_absolute_error, mean_squared_error
# Making predictions
y_pred = model.predict(X_test)
# Calculating MAE and RMSE
mae = mean_absolute_error(y_test, y_pred)
rmse = mean_squared_error(y_test, y_pred, squared=False)
print("Mean Absolute Error: ", mae)
print("Root Mean Square Error: ", rmse)
型:
- 平均絕對(duì)誤差 (MAE):0.0724(大約)
- 均方根誤差 (RMSE):0.0753(近似值)
????????MAE 和 RMSE 都是回歸模型預(yù)測(cè)準(zhǔn)確性的度量。以下是他們所指出的:
????????MAE 測(cè)量一組預(yù)測(cè)中誤差的平均幅度,而不考慮其方向。它是預(yù)測(cè)和實(shí)際觀察之間絕對(duì)差異的檢驗(yàn)樣本的平均值,其中所有個(gè)體差異的權(quán)重相等。MAE 為 0.0724 意味著平均而言,模型的預(yù)測(cè)值與實(shí)際值相差約 0.0724 個(gè)單位。
????????RMSE 是一種二次評(píng)分規(guī)則,也測(cè)量誤差的平均幅度。它是預(yù)測(cè)值和實(shí)際觀測(cè)值之間差值平方值的平方根。RMSE對(duì)大誤差的權(quán)重相對(duì)較高。這意味著當(dāng)大錯(cuò)誤特別不受歡迎時(shí),RMSE 應(yīng)該更有用。RMSE 為 0.0753 意味著當(dāng)誤差越大受到懲罰時(shí),模型的預(yù)測(cè)平均與實(shí)際值相差 0.0753 個(gè)單位。
????????這些指標(biāo)將幫助您了解模型的準(zhǔn)確性以及需要改進(jìn)的地方。通過分析這些指標(biāo),您可以就進(jìn)一步調(diào)整模型或更改方法做出明智的決策。
????????在下一節(jié)中,我們將討論如何使用該模型進(jìn)行實(shí)際的庫存模式預(yù)測(cè),以及將此模型部署到實(shí)際應(yīng)用中的實(shí)際注意事項(xiàng)。
八、第 7 部分:預(yù)測(cè)接下來的 4 根蠟燭
????????在用注意力機(jī)制訓(xùn)練和評(píng)估了我們的 LSTM 模型后,最后一步是利用它來預(yù)測(cè) AAPL 股價(jià)接下來的 4 根蠟燭(天)。
8.1 做出預(yù)測(cè)
????????為了預(yù)測(cè)未來的股票價(jià)格,我們需要為模型提供最新的數(shù)據(jù)點(diǎn)。假設(shè)我們準(zhǔn)備了最近 60 天的數(shù)據(jù),格式與 : 相同,并且我們想要預(yù)測(cè)第二天的價(jià)格:X_train
import yfinance as yf
import numpy as np
from sklearn.preprocessing import MinMaxScaler
# Fetching the latest 60 days of AAPL stock data
data = yf.download('AAPL', period='60d', interval='1d')
# Selecting the 'Close' price and converting to numpy array
closing_prices = data['Close'].values
# Scaling the data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(closing_prices.reshape(-1,1))
# Since we need the last 60 days to predict the next day, we reshape the data accordingly
X_latest = np.array([scaled_data[-60:].reshape(60)])
# Reshaping the data for the model (adding batch dimension)
X_latest = np.reshape(X_latest, (X_latest.shape[0], X_latest.shape[1], 1))
# Making predictions for the next 4 candles
predicted_stock_price = model.predict(X_latest)
predicted_stock_price = scaler.inverse_transform(predicted_stock_price)
print("Predicted Stock Prices for the next 4 days: ", predicted_stock_price)
????????讓我們預(yù)測(cè)未來 4 天的價(jià)格:
import yfinance as yf
import numpy as np
from sklearn.preprocessing import MinMaxScaler
# Fetch the latest 60 days of AAPL stock data
data = yf.download('AAPL', period='60d', interval='1d')
# Select 'Close' price and scale it
closing_prices = data['Close'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(closing_prices)
# Predict the next 4 days iteratively
predicted_prices = []
current_batch = scaled_data[-60:].reshape(1, 60, 1) # Most recent 60 days
for i in range(4): # Predicting 4 days
# Get the prediction (next day)
next_prediction = model.predict(current_batch)
# Reshape the prediction to fit the batch dimension
next_prediction_reshaped = next_prediction.reshape(1, 1, 1)
# Append the prediction to the batch used for predicting
current_batch = np.append(current_batch[:, 1:, :], next_prediction_reshaped, axis=1)
# Inverse transform the prediction to the original price scale
predicted_prices.append(scaler.inverse_transform(next_prediction)[0, 0])
print("Predicted Stock Prices for the next 4 days: ", predicted_prices)
8.2 預(yù)測(cè)的可視化
????????直觀地將預(yù)測(cè)值與實(shí)際股票價(jià)格進(jìn)行比較可能會(huì)非常有見地。以下是將預(yù)測(cè)股價(jià)與實(shí)際數(shù)據(jù)進(jìn)行對(duì)比的代碼:
!pip install mplfinance -qqq
import pandas as pd
import mplfinance as mpf
import matplotlib.dates as mpl_dates
import matplotlib.pyplot as plt
# Assuming 'data' is your DataFrame with the fetched AAPL stock data
# Make sure it contains Open, High, Low, Close, and Volume columns
# Creating a list of dates for the predictions
last_date = data.index[-1]
next_day = last_date + pd.Timedelta(days=1)
prediction_dates = pd.date_range(start=next_day, periods=4)
# Assuming 'predicted_prices' is your list of predicted prices for the next 4 days
predictions_df = pd.DataFrame(index=prediction_dates, data=predicted_prices, columns=['Close'])
# Plotting the actual data with mplfinance
mpf.plot(data, type='candle', style='charles', volume=True)
# Overlaying the predicted data
plt.figure(figsize=(10,6))
plt.plot(predictions_df.index, predictions_df['Close'], linestyle='dashed', marker='o', color='red')
plt.title("AAPL Stock Price with Predicted Next 4 Days")
plt.show()
8.3 預(yù)測(cè)的最終視覺對(duì)象:
import pandas as pd
import mplfinance as mpf
import matplotlib.dates as mpl_dates
import matplotlib.pyplot as plt
# Fetch the latest 60 days of AAPL stock data
data = yf.download('AAPL', period='64d', interval='1d') # Fetch 64 days to display last 60 days in the chart
# Select 'Close' price and scale it
closing_prices = data['Close'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(closing_prices)
# Predict the next 4 days iteratively
predicted_prices = []
current_batch = scaled_data[-60:].reshape(1, 60, 1) # Most recent 60 days
for i in range(4): # Predicting 4 days
next_prediction = model.predict(current_batch)
next_prediction_reshaped = next_prediction.reshape(1, 1, 1)
current_batch = np.append(current_batch[:, 1:, :], next_prediction_reshaped, axis=1)
predicted_prices.append(scaler.inverse_transform(next_prediction)[0, 0])
# Creating a list of dates for the predictions
last_date = data.index[-1]
next_day = last_date + pd.Timedelta(days=1)
prediction_dates = pd.date_range(start=next_day, periods=4)
# Adding predictions to the DataFrame
predicted_data = pd.DataFrame(index=prediction_dates, data=predicted_prices, columns=['Close'])
# Combining both actual and predicted data
combined_data = pd.concat([data['Close'], predicted_data['Close']])
combined_data = combined_data[-64:] # Last 60 days of actual data + 4 days of predictions
# Plotting the actual data
plt.figure(figsize=(10,6))
plt.plot(data.index[-60:], data['Close'][-60:], linestyle='-', marker='o', color='blue', label='Actual Data')
# Plotting the predicted data
plt.plot(prediction_dates, predicted_prices, linestyle='-', marker='o', color='red', label='Predicted Data')
plt.title("AAPL Stock Price: Last 60 Days and Next 4 Days Predicted")
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()
九、結(jié)論
????????在本指南中,我們探討了將 LSTM 網(wǎng)絡(luò)與注意力機(jī)制用于股價(jià)預(yù)測(cè)的復(fù)雜而迷人的任務(wù),特別是針對(duì) Apple Inc. (AAPL)。關(guān)鍵點(diǎn)包括:文章來源:http://www.zghlxwxcb.cn/news/detail-854688.html
- LSTM 捕獲時(shí)間序列數(shù)據(jù)中長(zhǎng)期依賴關(guān)系的能力。
- 注意力機(jī)制在關(guān)注相關(guān)數(shù)據(jù)點(diǎn)方面的額外優(yōu)勢(shì)。
- 構(gòu)建、訓(xùn)練和評(píng)估 LSTM 模型的詳細(xì)過程。
????????雖然具有注意力的 LSTM 模型功能強(qiáng)大,但它們也有局限性:文章來源地址http://www.zghlxwxcb.cn/news/detail-854688.html
- 假設(shè)歷史模式將以類似的方式重演可能會(huì)有問題,尤其是在動(dòng)蕩的市場(chǎng)中。
- 歷史價(jià)格數(shù)據(jù)中沒有捕捉到的外部因素,如市場(chǎng)新聞和全球事件,可以顯著影響股價(jià)。
到了這里,關(guān)于使用 LSTM 和 TensorFlow 中的注意力機(jī)制進(jìn)行高級(jí)股票形態(tài)預(yù)測(cè):Apple Inc. (AAPL) 數(shù)據(jù)分步指南的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!