Skip to main content

2 posts tagged with "LSTM"

View All Tags

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:

Tổng hợp các kỹ thuật dự đoán giá cổ phiếu

· 3 min read

Dự đoán giá cổ phiếu là một trong những bài toán quan trọng trong tài chính. Dưới đây là các phương pháp phổ biến giúp dự đoán xu hướng giá cổ phiếu:

1. Hồi quy tuyến tính (Linear Regression)

Hồi quy tuyến tính là phương pháp cơ bản giúp dự đoán giá cổ phiếu dựa trên mối quan hệ tuyến tính giữa các biến đầu vào.

📌 Ưu điểm: Đơn giản, dễ hiểu, dễ triển khai.
⚠️ Nhược điểm: Không hiệu quả với dữ liệu phi tuyến tính.

import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Lấy dữ liệu cổ phiếu
df = yf.download("AAPL", start="2020-01-01", end="2024-01-01")

# Chuẩn bị dữ liệu
df['Date'] = np.arange(len(df)) # Chuyển ngày thành số
X = df[['Date']]
y = df['Close']

# Huấn luyện mô hình hồi quy tuyến tính
model = LinearRegression()
model.fit(X, y)

# Dự đoán giá
df['Predicted'] = model.predict(X)

# Vẽ biểu đồ
plt.figure(figsize=(10,5))
plt.plot(df.index, df['Close'], label="Giá thực tế")
plt.plot(df.index, df['Predicted'], label="Dự đoán", linestyle='dashed')
plt.legend()
plt.title("Dự đoán giá cổ phiếu AAPL bằng Linear Regression")
plt.show()

2. ARIMA (AutoRegressive Integrated Moving Average)

ARIMA là mô hình dự đoán thời gian dựa trên dữ liệu lịch sử.

📌 Ưu điểm: Hiệu quả với dữ liệu có xu hướng và mùa vụ.
⚠️ Nhược điểm: Yêu cầu kiểm tra tính dừng của dữ liệu.

from statsmodels.tsa.arima.model import ARIMA

# Huấn luyện mô hình ARIMA
model = ARIMA(df['Close'], order=(5,1,0))
model_fit = model.fit()

# Dự đoán giá
df['ARIMA_Predicted'] = model_fit.predict(start=0, end=len(df)-1)

# Vẽ biểu đồ
plt.figure(figsize=(10,5))
plt.plot(df.index, df['Close'], label="Giá thực tế")
plt.plot(df.index, df['ARIMA_Predicted'], label="Dự đoán ARIMA", linestyle='dashed')
plt.legend()
plt.title("Dự đoán giá cổ phiếu AAPL bằng ARIMA")
plt.show()

3. LSTM (Long Short-Term Memory)

LSTM là mô hình mạng nơ-ron giúp xử lý dữ liệu chuỗi thời gian phức tạp.

📌 Ưu điểm: Xử lý dữ liệu dài hạn tốt.
⚠️ Nhược điểm: Cần nhiều dữ liệu và thời gian huấn luyện dài.

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

# Chuẩn bị dữ liệu cho LSTM
data = df['Close'].values.reshape(-1,1)
data = data / np.max(data) # Chuẩn hóa dữ liệu

# Tạo mô hình LSTM
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(10,1)),
LSTM(50, return_sequences=False),
Dense(1)
])

model.compile(optimizer='adam', loss='mse')
# Huấn luyện mô hình (đơn giản hóa, không đầy đủ)
# model.fit(X_train, y_train, epochs=50, batch_size=16)

# Dự đoán (giả lập)
df['LSTM_Predicted'] = df['Close'].shift(-1)

# Vẽ biểu đồ
plt.figure(figsize=(10,5))
plt.plot(df.index, df['Close'], label="Giá thực tế")
plt.plot(df.index, df['LSTM_Predicted'], label="Dự đoán LSTM", linestyle='dashed')
plt.legend()
plt.title("Dự đoán giá cổ phiếu AAPL bằng LSTM")
plt.show()

Kết luận

  • Hồi quy tuyến tính: Phù hợp với dữ liệu đơn giản, có quan hệ tuyến tính.
  • ARIMA: Hiệu quả với dữ liệu có xu hướng hoặc mùa vụ.
  • LSTM: Mạnh mẽ, phù hợp với dữ liệu chuỗi thời gian dài hạn.

👉 Mỗi phương pháp có ưu và nhược điểm riêng, tùy vào đặc điểm dữ liệu mà chọn mô hình phù hợp.

📌 Nếu bạn quan tâm đến Machine Learning và Phân tích dữ liệu tài chính, hãy tiếp tục theo dõi các bài viết tiếp theo! 🚀