| Machine Learning Trong Giao Dịch Định Lượng

Được viết bởi thanhdt vào ngày 09/12/2025 lúc 18:51 | 35 lượt xem

Machine Learning Trong Giao Dịch Định Lượng: Dự Đoán Xu Hướng, Phân Loại Nến, Giảm Nhiễu Chiến Lược

https://media.licdn.com/dms/image/v2/D5612AQGq3JgGVJjRFA/article-cover_image-shrink_720_1280/article-cover_image-shrink_720_1280/0/1706093871874?e=2147483647&t=m4J2MkRa_XZ1tBoXpp3xJGrsvgrzA7h61A9FJD01OI0&v=beta&utm_source=chatgpt.com
https://d2908q01vomqb2.cloudfront.net/f1f836cb4ea6efb2a0b1b99f41ad8b103eff4b59/2020/12/22/ML-558-1.jpg?utm_source=chatgpt.com

Machine Learning (ML) đang trở thành một trong những công cụ tạo lợi thế lớn nhất trong giao dịch định lượng.
Khác với indicator truyền thống (EMA, RSI, MACD), ML có khả năng:

  • Nhận diện mô hình giá không nhìn thấy bằng mắt
  • Phân loại xu hướng chính xác hơn
  • Giảm nhiễu từ thị trường
  • Dự đoán breakout
  • Tạo tín hiệu “thông minh” hơn

Bài này giúp bạn xây dựng một pipeline ML hoàn chỉnh:

  1. Thu thập dữ liệu
  2. Feature Engineering
  3. Labeling (Tạo nhãn: tăng/giảm/sideway)
  4. Training Model (RF, XGBoost, LSTM)
  5. Backtest chiến lược ML
  6. Đánh giá mô hình
  7. Kết nối mô hình vào Bot Auto Trading

1. Tại sao Machine Learning phù hợp giao dịch định lượng?

https://wallstreetmojocms.recurpro.in/uploads/Machine_Learning_in_Trading_a0ea83da9c.jpg?utm_source=chatgpt.com
https://www.quantifiedstrategies.com/wp-content/uploads/2024/09/AI-Trading-Strategies-for-Beginners.png?utm_source=chatgpt.com
https://www.future-processing.com/blog/wp-content/uploads/2024/02/ML-in-finance-2.jpg?utm_source=chatgpt.com

ML mạnh ở 3 điểm:

  • Xử lý được dữ liệu lớn: hàng triệu nến trong vài giây
  • Không dựa vào cảm xúc: hoàn toàn khách quan
  • Phát hiện pattern mà indicator không bắt được

Ví dụ ML có thể phát hiện:

  • Xu hướng yếu → mạnh
  • Breakout giả → thật
  • Nến đảo chiều có xác suất cao
  • Mô hình giá phức tạp như Wyckoff/SMC

2. Pipeline Machine Learning trong trading

https://miro.medium.com/v2/resize%3Afit%3A1400/1%2AmxhjANt41NhFFbhvqIkUaw.png?utm_source=chatgpt.com
https://developer-blogs.nvidia.com/wp-content/uploads/2023/02/ml-workflow-udacity-625x337.png?utm_source=chatgpt.com
https://public.bnbstatic.com/image/cms/blog/20221129/34017821-0bdc-4300-b478-6856a1c0f863?utm_source=chatgpt.com

Pipeline chuẩn:

Dữ liệu → Feature Engineering → Label → Train ML Model → Backtest → Deploy → Bot

3. Thu thập dữ liệu cho ML

Dữ liệu cần:

  • OHLCV
  • Volume
  • ATR
  • Volatility
  • Orderbook (nếu cần)
  • Funding Rate (Crypto)
  • Open Interest

Ví dụ thu thập bằng ccxt:

bars = exchange.fetch_ohlcv('BTC/USDT', '5m', limit=5000)
df = pd.DataFrame(bars, columns=['time','open','high','low','close','volume'])
df['time'] = pd.to_datetime(df['time'], unit='ms')

4. Feature Engineering – Tạo đặc trưng mạnh cho ML

https://i.ytimg.com/vi/FUB1KlhqH58/hq720.jpg?rs=AOn4CLAlf2pe40iQwWh6QRLAw9zhIED_sg&sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD&utm_source=chatgpt.com
https://media.licdn.com/dms/image/v2/D4E22AQGOsjtnps1S4w/feedshare-shrink_1280/B4EZmmJ2MYHcAs-/0/1759429224188?e=2147483647&t=HCb6KOArsw-5MLnXkw8huKHzv-FjWo5xoiUfRcK9ZDk&v=beta&utm_source=chatgpt.com
https://www.researchgate.net/publication/383660285/figure/fig2/AS%3A11431281275086372%401725282702035/Dataset-and-Technical-Indicators.jpg?utm_source=chatgpt.com

Các nhóm feature quan trọng:

(1) Technical Indicators

  • EMA (20, 50, 200)
  • RSI
  • MACD
  • Bollinger Bands
  • ATR
  • ADX
  • CCI

(2) Statistical Features

  • Rolling mean
  • Rolling std
  • Z-score
  • Kurtosis
  • Skewness

(3) Price Action Features

  • Wick ratio
  • Candle body size
  • Volume spike
  • Trend angle
  • Orderblock / Support/Resistance zone

(4) Volatility Features

  • ATR
  • True Range
  • Historical volatility

(5) Orderbook Features (nâng cao)

  • Bid/Ask imbalance
  • Liquidity delta
  • Volume profile

Ví dụ Feature Engineering:

df['return'] = df['close'].pct_change()
df['ema20'] = df['close'].ewm(span=20).mean()
df['atr'] = ta.ATR(df['high'], df['low'], df['close'])
df['rsi'] = ta.RSI(df['close'])

5. Tạo nhãn (Labeling) – Tăng / Giảm / Sideway

3 cách gán nhãn phổ biến:

(1) Future Return Labeling

Dự đoán giá 1 nến sau sẽ tăng hay giảm.

df['future_return'] = df['close'].shift(-1) - df['close']
df['label'] = (df['future_return'] > 0).astype(int)

(2) Trend Classification

  • 1 = Uptrend
  • 0 = Sideway
  • -1 = Downtrend

(3) Triple Barrier Method (được các quỹ lớn dùng)

https://substackcdn.com/image/fetch/%24s_%218j09%21%2Cf_auto%2Cq_auto%3Agood%2Cfl_progressive%3Asteep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd3f141f9-7d21-4f04-ac18-4debd1d207a3_1321x734.heic?utm_source=chatgpt.com
https://pubs.acs.org/cms/10.1021/acsmeasuresciau.4c00007/asset/images/large/tg4c00007_0012.jpeg?utm_source=chatgpt.com
https://user-images.githubusercontent.com/44833308/172560332-825bbd68-445d-4d35-a4b5-ac2d9fb74140.png?utm_source=chatgpt.com

Cài đặt ranh giới:

  • Upper barrier = TP
  • Lower barrier = SL
  • Vertical barrier = Time limit

Mô hình rất chính xác để phân loại:

  • Buy
  • Sell
  • Do nothing

6. Các mô hình ML mạnh dùng trong trading

https://i.ytimg.com/vi/t8sYlaCHu7I/maxresdefault.jpg?utm_source=chatgpt.com
https://d1rwhvwstyk9gu.cloudfront.net/2023/07/Decision-trees-and-limitation.png?utm_source=chatgpt.com
https://user-images.githubusercontent.com/45107198/65030726-4deca700-d940-11e9-8364-7dfdeb28f3d9.png?utm_source=chatgpt.com
Mô hìnhƯu điểmNhược điểm
Random ForestDễ dùng, mạnh, ít overfitKhông mô hình chuỗi
XGBoostDự đoán tốt, mạnh trong KaggleDễ overfit nếu dữ liệu bẩn
CatBoostRất tốt cho dữ liệu time seriesHuấn luyện lâu
LSTM / GRUHiểu chuỗi giá rất tốtCần GPU
TransformerSức mạnh AI hiện đạiRất nặng, khó deploy

7. Huấn luyện mô hình

Ví dụ Random Forest:

from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(
    n_estimators=300,
    max_depth=8,
    random_state=42
)

model.fit(X_train, y_train)
pred = model.predict(X_test)

8. Đánh giá mô hình

✔ Accuracy
✔ Precision
✔ Recall
✔ F1-score
✔ Confusion matrix

Nhưng quan trọng hơn là:

  • Profit Factor
  • Max Drawdown
  • Equity curve

ML model tốt nhưng không kiếm được tiền thì không dùng được.


9. Backtest chiến lược ML

https://www.ml4trading.io/static/home/img/parts/backtest.png?utm_source=chatgpt.com
https://www.quantifiedstrategies.com/wp-content/uploads/2024/03/what-is-an-equity-curve.png?utm_source=chatgpt.com
https://www.researchgate.net/publication/358872273/figure/fig6/AS%3A1128457136291874%401646056555141/Machine-learning-strategy-to-improve-the-evaluation-distribution.jpg?utm_source=chatgpt.com

Pipeline:

Predict → Generate Signal → Simulate Trades → Equity Curve → Metrics

Ví dụ tín hiệu ML:

df['signal'] = model.predict(X)
df['strategy_return'] = df['signal'].shift(1) * df['return']

10. Triển khai mô hình ML vào Bot Auto Trading

https://cdn.prod.website-files.com/660ef16a9e0687d9cc27474a/6625e0d9d9d453253f698e04_648a6e5ae681ee38e06d2bc7_fastapi_monitoring_tutorial.007-min.png?utm_source=chatgpt.com
https://tbis.io/wp-content/uploads/54179656629_d7b9a61537_o.jpg?utm_source=chatgpt.com
https://cloudxlab.com/blog/wp-content/uploads/2019/04/Machine-Learning-Model-Deployment.png?utm_source=chatgpt.com

FastAPI Endpoint:

@app.post("/ml-signal")
async def ml_signal(data: dict):
    features = extract_features(data)
    pred = model.predict([features])
    
    if pred == 1:
        signal = "long"
    else:
        signal = "short"

    await order_queue.put({
        "symbol": data["symbol"],
        "signal": signal,
        "confidence": data["confidence"],
        "strategy": "ml_model"
    })

    return {"signal": signal}

11. Kết hợp ML + Rule-based Strategy → Multi-Alpha System

Quỹ lớn hiện dùng mô hình:

  • 40% Trend
  • 30% Mean Reversion
  • 30% ML/AI

ML có thể dùng để:

  • Lọc tín hiệu nhiễu
  • Dự đoán breakout thật
  • Xác nhận xu hướng
  • Tối ưu vị thế

12. Sai lầm thường gặp khi dùng ML trong trading

https://fastercapital.com/i/Machine-learning--The-Rise-of-AI--Machine-Learning-in-Quantitative-Trading--Challenges-and-Pitfalls-in-Quantitative-Trading-with-AI.webp?utm_source=chatgpt.com
https://algotrading101.com/learn/wp-content/uploads/2019/07/overfitting-comics.jpg?utm_source=chatgpt.com
https://i.ytimg.com/vi/NsysK-bvvZk/hq720.jpg?rs=AOn4CLD5IWrIX89uAJshzwZNnwk6u-N2sA&sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD&utm_source=chatgpt.com
  1. Overfit mô hình → đẹp trong backtest, thua real
  2. Dùng quá nhiều feature
  3. Dữ liệu không làm sạch
  4. Không dùng labeling đúng cách
  5. Không kiểm tra overfitting
  6. Không kết hợp Risk Engine
  7. Không backtest pipeline ML đúng chuẩn

13. Kết luận

ML không phải “thuật toán thần thánh”, nhưng là vũ khí mạnh nhất trong bộ công cụ giao dịch định lượng.

Nhờ ML, bạn có thể:

  • Phát hiện mô hình ẩn
  • Dự đoán xu hướng
  • Giảm nhiễu
  • Tạo tín hiệu chất lượng hơn
  • Kết hợp với bot FastAPI để giao dịch tự động

Tương lai của bot trading = Rule-based Strategy + Machine Learning + Risk Engine.