| Pandas Cho Tài Chính: Phân Tích Cổ Phiếu VnIndex Trong 30 Phút

Pandas là thư viện Python số 1 cho phân tích dữ liệu tài chính. Bài viết này hướng dẫn bạn từng bước phân tích cổ phiếu VnIndex trong 30 phút thực hành.

Cài Đặt

pip install pandas numpy matplotlib vnstock

Bước 1: Tải Dữ Liệu Cổ Phiếu Việt Nam

from vnstock import stock_historical_data
import pandas as pd

df = stock_historical_data("VNM", "2023-01-01", "2026-06-01", "1D", "stock")
df.index = pd.to_datetime(df['time'])
df = df[['open','high','low','close','volume']]
print(df.tail(5))

Bước 2: Thống Kê Cơ Bản

df['daily_return'] = df['close'].pct_change() * 100
print(df['daily_return'].describe())
print(f"Lợi nhuận TB/ngày: {df['daily_return'].mean():.2f}%")
print(f"Ngày tăng mạnh nhất: {df['daily_return'].max():.2f}%")

Bước 3: Tính Chỉ Báo Kỹ Thuật

# Moving Averages
df['SMA20'] = df['close'].rolling(20).mean()
df['EMA50'] = df['close'].ewm(span=50).mean()

# RSI 14
delta = df['close'].diff()
gain = delta.clip(lower=0).rolling(14).mean()
loss = (-delta.clip(upper=0)).rolling(14).mean()
df['RSI'] = 100 - (100 / (1 + gain/loss))

# MACD
df['MACD'] = df['close'].ewm(span=12).mean() - df['close'].ewm(span=26).mean()
df['MACD_signal'] = df['MACD'].ewm(span=9).mean()

# Bollinger Bands
df['BB_mid'] = df['close'].rolling(20).mean()
bb_std = df['close'].rolling(20).std()
df['BB_upper'] = df['BB_mid'] + 2 * bb_std
df['BB_lower'] = df['BB_mid'] - 2 * bb_std

Bước 4: Tạo Tín Hiệu Mua/Bán (Golden Cross)

df['signal'] = 0
df.loc[(df['SMA20'] > df['EMA50']) & (df['SMA20'].shift(1) <= df['EMA50'].shift(1)), 'signal'] = 1
df.loc[(df['SMA20'] < df['EMA50']) & (df['SMA20'].shift(1) >= df['EMA50'].shift(1)), 'signal'] = -1
print(f"Tín hiệu Mua: {(df['signal']==1).sum()}, Bán: {(df['signal']==-1).sum()}")

Bước 5: Backtest Nhanh

capital = 100_000_000
shares = 0
for i in range(len(df)):
    price = df['close'].iloc[i]
    sig = df['signal'].iloc[i]
    if sig == 1 and shares == 0:
        shares = int(capital * 0.95 / price)
        capital -= shares * price
    elif sig == -1 and shares > 0:
        capital += shares * price
        shares = 0

final = capital + shares * df['close'].iloc[-1]
print(f"Lợi nhuận: {(final/100_000_000 - 1)*100:.1f}%")

Tóm Tắt — 30 Phút Với Pandas Bạn Đã:

  • ✅ Tải dữ liệu cổ phiếu VN thật
  • ✅ Tính SMA, EMA, RSI, MACD, Bollinger Bands
  • ✅ Tạo tín hiệu Golden Cross tự động
  • ✅ Backtest và tính lợi nhuận

Đây là nền tảng để xây bot trading thực sự — chỉ cần thêm module kết nối API sàn giao dịch.


📌 Muốn ứng dụng Python vào phân tích và giao dịch tài chính thực chiến?
Khóa Python Fintech — Phân Tích Dữ Liệu Lớn & Tự Động Hóa Giao Dịch tại Hướng Nghiệp Dữ Liệu giúp bạn dùng Python với dữ liệu VnIndex, Binance API thật — không dạy lý thuyết hàn lâm.
📞 Hotline/Zalo: 0927 909 257

admin

admin

Biên tập viên, Hướng Nghiệp Dữ Liệu
713 Bài viết
15.4k Người theo dõi
120k+ Lượt đọc

Biên tập viên nội dung tại Hướng Nghiệp Dữ Liệu, phụ trách tổng hợp và biên soạn các bài viết về lập trình Python, dữ liệu và công nghệ.