Dự Đoán Giá Cổ Phiếu với Python: Hồi Quy Tuyến Tính, ARIMA, LSTM
· 4 min read
1. Giới thiệu
Dự đoán giá cổ phiếu là một trong những ứng dụng phổ biến của Machine Learning trong tài chính. Trong bài viết này, chúng ta sẽ khám phá ba mô hình chính:
- Hồi quy tuyến tính (Linear Regression)
- ARIMA (AutoRegressive Integrated Moving Average)
- LSTM (Long Short-Term Memory - Mạng neuron hồi tiếp)
2. Cách lấy dữ liệu cổ phiếu từ yfinance
Chúng ta sẽ sử dụng thư viện yfinance
để lấy dữ liệu giá cổ phiếu từ Yahoo Finance.
Cài đặt thư viện
pip install yfinance pandas numpy matplotlib scikit-learn tensorflow
Lấy dữ liệu cổ phiếu
import yfinance as yf
# Lấy dữ liệu cổ phiếu của Apple (AAPL) trong 5 năm
stock_data = yf.download("AAPL", start="2018-01-01", end="2023-01-01")
# Hiển thị 5 dòng dữ liệu đầu tiên
print(stock_data.head())
3. Mô hình Hồi Quy Tuyến Tính
Hồi quy tuyến tính là mô hình cơ bản nhất để dự đoán giá cổ phiếu dựa trên xu hướng lịch sử.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Chuẩn bị dữ liệu
stock_data['Date'] = stock_data.index
stock_data['Date'] = stock_data['Date'].map(pd.Timestamp.toordinal)
X = stock_data[['Date']]
y = stock_data['Close']
# Chia dữ liệu thành tập train/test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Huấn luyện mô hình
model = LinearRegression()
model.fit(X_train, y_train)
# Dự đoán
y_pred = model.predict(X_test)
# Vẽ biểu đồ
plt.figure(figsize=(10,5))
plt.scatter(X_test, y_test, color='blue', label='Thực tế')
plt.plot(X_test, y_pred, color='red', label='Dự đoán')
plt.xlabel("Ngày")
plt.ylabel("Giá đóng cửa")
plt.title("Dự đoán giá cổ phiếu bằng Linear Regression")
plt.legend()
plt.show()
4. Mô hình ARIMA
ARIMA là mô hình thống kê phổ biến trong phân tích chuỗi thời gian.
from statsmodels.tsa.arima.model import ARIMA
# Xây dựng mô hình ARIMA
model_arima = ARIMA(y, order=(5,1,0))
model_arima_fit = model_arima.fit()
# Dự đoán giá cổ phiếu
forecast = model_arima_fit.forecast(steps=30)
# Hiển thị kết quả
plt.figure(figsize=(10,5))
plt.plot(y, label="Thực tế")
plt.plot(range(len(y), len(y)+30), forecast, label="Dự đoán", color='red')
plt.legend()
plt.title("Dự đoán giá cổ phiếu bằng ARIMA")
plt.show()
5. Mô hình LSTM
LSTM là một loại mạng nơ-ron hồi tiếp (RNN) rất hiệu quả trong dự đoán chuỗi thời gian.
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
# Tiền xử lý dữ liệu
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(y.values.reshape(-1,1))
# Chia dữ liệu thành train/test
train_size = int(len(scaled_data) * 0.8)
train_data, test_data = scaled_data[:train_size], scaled_data[train_size:]
# Chuẩn bị dữ liệu cho LSTM
def create_dataset(dataset, time_step=10):
X_data, Y_data = [], []
for i in range(len(dataset) - time_step - 1):
X_data.append(dataset[i:(i+time_step), 0])
Y_data.append(dataset[i + time_step, 0])
return np.array(X_data), np.array(Y_data)
time_step = 10
X_train, y_train = create_dataset(train_data, time_step)
X_test, y_test = create_dataset(test_data, time_step)
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
# Xây dựng mô hình LSTM
model_lstm = Sequential([
LSTM(50, return_sequences=True, input_shape=(time_step,1)),
LSTM(50, return_sequences=False),
Dense(25),
Dense(1)
])
# Biên dịch và huấn luyện mô hình
model_lstm.compile(optimizer='adam', loss='mean_squared_error')
model_lstm.fit(X_train, y_train, epochs=50, batch_size=32)
# Dự đoán
predictions = model_lstm.predict(X_test)
# Chuyển dữ liệu về giá trị ban đầu
predictions = scaler.inverse_transform(predictions.reshape(-1,1))
# Hiển thị kết quả
plt.figure(figsize=(10,5))
plt.plot(y, label="Thực tế")
plt.plot(range(train_size+time_step+1, len(y)), predictions, label="Dự đoán LSTM", color='red')
plt.legend()
plt.title("Dự đoán giá cổ phiếu bằng LSTM")
plt.show()
6. Kết luận
Chúng ta đã khám phá ba mô hình phổ biến trong dự đoán giá cổ phiếu:
- Hồi quy tuyến tính: Đơn giản nhưng ít hiệu quả với dữ liệu phi tuyến.
- ARIMA: Tốt cho chuỗi thời gian nhưng hạn chế với dữ liệu phi tuyến.
- LSTM: Mạnh mẽ nhưng cần nhiều dữ liệu và thời gian huấn luyện.
Bạn có thể thử nghiệm thêm với các mô hình khác để cải thiện độ chính xác. 🚀
📢 Xem thêm: