Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse

NodeBB

  1. Home
  2. Tutorial
  3. Bài 20 — Kiến trúc FreqAI

Bài 20 — Kiến trúc FreqAI

Scheduled Pinned Locked Moved Tutorial
1 Posts 1 Posters 30 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • W
    W
    wuquang
    wrote on last edited by
    #1

    Bài này mở đầu Phần 5 về machine learning. FreqAI là lớp ML tích hợp sẵn trong Freqtrade: bạn khai báo feature và target trong chiến lược, chọn một model, và FreqAI lo phần còn lại. Nó tạo dataset, chia train/test, chuẩn hóa, loại outlier, huấn luyện lại định kỳ theo cửa sổ trượt, rồi trả dự đoán về dataframe để dùng trong populate_entry_trend. Bài này đi qua kiến trúc, cấu hình, và một chiến lược LightGBM tối thiểu cho futures.

    Mục tiêu

    • Hiểu vòng đời huấn luyện của FreqAI ở backtest và live.
    • Viết feature trong các hàm feature_engineering_* và target trong set_freqai_targets.
    • Đọc các cột FreqAI trả về: dự đoán, do_predict, DI_values, thống kê target.
    • Chạy backtest FreqAI với LightGBMRegressor, và tránh các lỗi rò rỉ dữ liệu.

    Cài đặt

    source ~/freqtrade/.venv/bin/activate
    pip install -r requirements-freqai.txt
    PyTorch và reinforcement learning cần thêm requirements-freqai-rl.txt (Bài 23–24); file này nặng hơn nhiều.

    Vòng đời huấn luyện

    Khi backtest, FreqAI mô phỏng việc huấn luyện lại định kỳ bằng cửa sổ trượt:

    1. Huấn luyện model trên train_period_days ngày dữ liệu.
    2. Dùng model đó dự đoán cho backtest_period_days ngày tiếp theo.
    3. Trượt cả hai cửa sổ thêm backtest_period_days ngày, huấn luyện model mới, lặp lại đến hết --timerange.

    Ví dụ --timerange một năm với backtest_period_days: 7 nghĩa là khoảng 52 model cho mỗi cặp. Đây chính là walk-forward (Bài 10), được FreqAI làm sẵn.

    Khi dry-run hoặc live, FreqAI huấn luyện ở luồng riêng, xoay vòng qua các cặp, luôn dùng model mới nhất. live_retrain_hours đặt khoảng nghỉ tối thiểu giữa hai lần huấn luyện; expiration_hours từ chối dự đoán từ model quá cũ.

    identifier là tên của một "phiên" model. Model và dự đoán được lưu trong user_data/models/<identifier>/. Giữ nguyên identifier thì backtest lần sau tái sử dụng model và dự đoán đã có, nhanh hơn rất nhiều. Đổi feature, target hay model thì phải đổi identifier (hoặc xóa thư mục cũ), nếu không FreqAI sẽ dùng lại model cũ.

    Cấu hình

    Lưu thành user_data/config-freqai.json, nạp sau config.json:

    {
    "max_open_trades": 3,
    "exchange": {
    "pair_whitelist": ["BTC/USDT:USDT", "ETH/USDT:USDT", "SOL/USDT:USDT"]
    },
    "freqai": {
    "enabled": true,
    "identifier": "lgbm-v1",
    "purge_old_models": 2,
    "train_period_days": 60,
    "backtest_period_days": 7,
    "live_retrain_hours": 6,
    "expiration_hours": 12,
    "fit_live_predictions_candles": 300,
    "feature_parameters": {
    "include_timeframes": ["1h", "4h"],
    "include_corr_pairlist": ["BTC/USDT:USDT", "ETH/USDT:USDT"],
    "label_period_candles": 12,
    "include_shifted_candles": 2,
    "indicator_periods_candles": [10, 20],
    "DI_threshold": 0.9,
    "use_SVM_to_remove_outliers": true,
    "principal_component_analysis": false
    },
    "data_split_parameters": {
    "test_size": 0.25,
    "shuffle": false
    },
    "model_training_parameters": {
    "n_estimators": 400,
    "learning_rate": 0.03,
    "num_leaves": 31,
    "verbose": -1
    }
    }
    }

    Khóa Ý nghĩa
    train_period_days, backtest_period_days Cửa sổ huấn luyện và chu kỳ huấn luyện lại
    identifier Tên phiên model; đổi khi đổi feature, target, model
    purge_old_models Giữ N model gần nhất mỗi cặp; 0 là không xóa
    live_retrain_hours, expiration_hours Nhịp huấn luyện lại và tuổi tối đa của model khi live
    fit_live_predictions_candles Dùng N dự đoán gần nhất để tính thống kê target khi live (xem phần ngưỡng động)
    include_timeframes Mỗi feature được tính trên từng khung này
    include_corr_pairlist Mỗi feature được tính thêm trên các cặp tham chiếu này
    include_shifted_candles Thêm bản trễ 1..N nến của mỗi feature
    indicator_periods_candles Các chu kỳ truyền vào feature_engineering_expand_all
    label_period_candles Tầm nhìn của target (số nến tương lai)
    DI_threshold, use_SVM_to_remove_outliers Phát hiện điểm dữ liệu lạ (Bài 21)
    data_split_parameters Truyền cho train_test_split của scikit-learn
    model_training_parameters Truyền thẳng cho thư viện model (ở đây là LightGBM)

    shuffle: false là bắt buộc với dữ liệu chuỗi thời gian. Trộn ngẫu nhiên khiến tập test nằm xen giữa tập train; các nến gần nhau rất giống nhau, nên điểm test đẹp một cách giả tạo.

    Số feature nhân lên rất nhanh. Với 7 feature trong expand_all: 7 × 2 chu kỳ × 2 khung × 3 (gốc + 2 bản trễ) × 3 (cặp hiện tại + 2 cặp tham chiếu) = 252 feature, chưa kể feature từ expand_basic và standard. Thêm một khung hay một cặp tham chiếu làm số feature tăng theo cấp số nhân, cùng thời gian huấn luyện và nguy cơ overfit.

    Feature: ba hàm, một quy ước tên

    Hàm Được nhân theo Dùng cho
    feature_engineering_expand_all(dataframe, period, **kwargs) Chu kỳ × khung × bản trễ × cặp tham chiếu Chỉ báo có tham số chu kỳ
    feature_engineering_expand_basic(dataframe, **kwargs) Khung × bản trễ × cặp tham chiếu Feature không có chu kỳ
    feature_engineering_standard(dataframe, **kwargs) Không nhân Feature chung: giờ trong ngày, thứ trong tuần
    • Cột bắt đầu bằng % là feature. FreqAI xóa các cột này khỏi dataframe trả về chiến lược để tiết kiệm bộ nhớ.
    • Cột bắt đầu bằng %% cũng là feature, nhưng được giữ lại để vẽ biểu đồ. Tên cuối cùng có thêm chu kỳ, cặp, khung, ví dụ %%-rsi-period_10_ETH/USDT:USDT_1h. In dataframe.columns sau self.freqai.start() để xem tên thật.
    • Feature phải được khai báo trong các hàm feature_engineering_*. Khai báo trong populate_indicators sẽ làm FreqAI hỏng khi chạy live.
    • Khi backtest, feature được tính một lần trên toàn bộ dữ liệu, nên mọi quy tắc chống lookahead của Bài 5 đều áp dụng: không shift âm, không chuẩn hóa bằng thống kê toàn chuỗi.

    Ưu tiên feature dừng (stationary). Ví dụ trong tài liệu Freqtrade dùng cả giá thô và khối lượng thô. Giá BTC năm 2024 và 2026 nằm ở các vùng khác hẳn nhau, nên model học được "giá 60.000 thì..." sẽ không áp dụng được về sau. Dùng tỷ lệ, khoảng cách tương đối, biến động chuẩn hóa thay cho giá trị tuyệt đối.

    Target

    def set_freqai_targets(self, dataframe: DataFrame, metadata: dict, **kwargs) -> DataFrame:
    n = self.freqai_info["feature_parameters"]["label_period_candles"]
    dataframe["&-fwd_ret"] = (
    dataframe["close"].shift(-n).rolling(n).mean() / dataframe["close"] - 1
    )
    return dataframe

    • Cột bắt đầu bằng & là target. Đây là nơi duy nhất được phép dùng shift âm, vì target là thứ model cần học dự đoán.
    • Target trên: trung bình giá đóng cửa của n nến tiếp theo so với giá hiện tại. Lấy trung bình thay vì một điểm giúp target bớt nhiễu.
    • Khi backtest, FreqAI gọi set_freqai_targets() riêng cho từng cửa sổ, để target không vượt quá dữ liệu mà cửa sổ đó được phép thấy.
    • Regressor cần target liên tục; classifier cần target dạng chuỗi (ví dụ "up"/"down") và khai báo self.freqai.class_names (Bài 21).

    Các cột FreqAI trả về

    Cột Ý nghĩa
    &-fwd_ret Dự đoán của model (cùng tên với target)
    &-fwd_ret_mean, &-fwd_ret_std Trung bình và độ lệch chuẩn của target trong lần huấn luyện gần nhất, hoặc của các dự đoán gần đây nếu đặt fit_live_predictions_candles
    do_predict 1: dự đoán đáng tin. Giảm dần (0, -1, -2) khi DI, SVM, DBSCAN coi điểm dữ liệu là outlier. 2: model đã hết hạn
    DI_values Dissimilarity Index: điểm dữ liệu hiện tại khác dữ liệu huấn luyện bao nhiêu; càng thấp càng đáng tin

    Ngưỡng động. Một dự đoán +0.4% lớn hay nhỏ phụ thuộc vào thị trường lúc đó. So với phân phối target bằng z-score:

    dataframe["long_th"] = dataframe["&-fwd_ret_mean"] + self.z_entry * dataframe["&-fwd_ret_std"]
    dataframe["short_th"] = dataframe["&-fwd_ret_mean"] - self.z_entry * dataframe["&-fwd_ret_std"]

    Chiến lược FreqaiLgbmFutures

    Lưu thành user_data/strategies/FreqaiLgbmFutures.py:

    import numpy as np
    from pandas import DataFrame
    import talib.abstract as ta

    from freqtrade.strategy import IStrategy

    class FreqaiLgbmFutures(IStrategy):
    """Bài 20: LightGBM dự đoán lợi nhuận trung bình 12 nến tới."""

    INTERFACE\_VERSION \= 3  
    timeframe \= "1h"  
    can\_short \= True  
    startup\_candle\_count \= 40            \# chu kỳ lớn nhất (20) x 2, theo khuyến nghị FreqAI
    
    minimal\_roi \= {}  
    stoploss \= \-0.05  
    process\_only\_new\_candles \= True  
    use\_exit\_signal \= True
    
    z\_entry \= 1.0  
    min\_edge \= 0.003                     \# dự đoán phải vượt chi phí giao dịch ước tính
    
    \# \---------- feature \----------  
    def feature\_engineering\_expand\_all(self, dataframe: DataFrame, period: int, \*\*kwargs) \-\> DataFrame:  
        dataframe\["%-rsi-period"\] \= ta.RSI(dataframe, timeperiod=period)  
        dataframe\["%-mfi-period"\] \= ta.MFI(dataframe, timeperiod=period)  
        dataframe\["%-adx-period"\] \= ta.ADX(dataframe, timeperiod=period)  
        dataframe\["%-roc-period"\] \= ta.ROC(dataframe, timeperiod=period)  
        dataframe\["%-natr-period"\] \= ta.NATR(dataframe, timeperiod=period)  
        dataframe\["%-ema\_dist-period"\] \= dataframe\["close"\] / ta.EMA(dataframe, timeperiod=period) \- 1  
        dataframe\["%-rel\_vol-period"\] \= dataframe\["volume"\] / dataframe\["volume"\].rolling(period).mean()  
        return dataframe
    
    def feature\_engineering\_expand\_basic(self, dataframe: DataFrame, \*\*kwargs) \-\> DataFrame:  
        dataframe\["%-ret\_1"\] \= dataframe\["close"\].pct\_change()  
        dataframe\["%-range"\] \= (dataframe\["high"\] \- dataframe\["low"\]) / dataframe\["close"\]  
        return dataframe
    
    def feature\_engineering\_standard(self, dataframe: DataFrame, \*\*kwargs) \-\> DataFrame:  
        dataframe\["%-day\_of\_week"\] \= (dataframe\["date"\].dt.dayofweek \+ 1\) / 7  
        dataframe\["%-hour\_of\_day"\] \= (dataframe\["date"\].dt.hour \+ 1\) / 25  
        return dataframe
    
    \# \---------- target \----------  
    def set\_freqai\_targets(self, dataframe: DataFrame, metadata: dict, \*\*kwargs) \-\> DataFrame:  
        n \= self.freqai\_info\["feature\_parameters"\]\["label\_period\_candles"\]  
        dataframe\["&-fwd\_ret"\] \= (  
            dataframe\["close"\].shift(-n).rolling(n).mean() / dataframe\["close"\] \- 1  
        )  
        return dataframe
    
    \# \---------- chiến lược \----------  
    def populate\_indicators(self, dataframe: DataFrame, metadata: dict) \-\> DataFrame:  
        dataframe \= self.freqai.start(dataframe, metadata, self)  
        dataframe\["long\_th"\] \= dataframe\["&-fwd\_ret\_mean"\] \+ self.z\_entry \* dataframe\["&-fwd\_ret\_std"\]  
        dataframe\["short\_th"\] \= dataframe\["&-fwd\_ret\_mean"\] \- self.z\_entry \* dataframe\["&-fwd\_ret\_std"\]  
        return dataframe
    
    def populate\_entry\_trend(self, dataframe: DataFrame, metadata: dict) \-\> DataFrame:  
        ok \= (dataframe\["do\_predict"\] \== 1\) & (dataframe\["volume"\] \> 0\)  
        pred \= dataframe\["&-fwd\_ret"\]
    
        dataframe.loc\[ok & (pred \> dataframe\["long\_th"\]) & (pred \> self.min\_edge),  
                      \["enter\_long", "enter\_tag"\]\] \= (1, "ml\_long")  
        dataframe.loc\[ok & (pred \< dataframe\["short\_th"\]) & (pred \< \-self.min\_edge),  
                      \["enter\_short", "enter\_tag"\]\] \= (1, "ml\_short")  
        return dataframe
    
    def populate\_exit\_trend(self, dataframe: DataFrame, metadata: dict) \-\> DataFrame:  
        pred \= dataframe\["&-fwd\_ret"\]  
        dataframe.loc\[pred \< 0, \["exit\_long", "exit\_tag"\]\] \= (1, "pred\_flip")  
        dataframe.loc\[pred \> 0, \["exit\_short", "exit\_tag"\]\] \= (1, "pred\_flip")  
        return dataframe  
    

    self.freqai.start() chỉ được gọi trong populate_indicators. Chiến lược không có leverage() nên dùng 1x; khi thử ML lần đầu, đừng cộng thêm rủi ro đòn bẩy.

    Chạy backtest

    FreqAI cần dữ liệu trước ngày bắt đầu backtest để huấn luyện model đầu tiên: lùi lại train_period_days cộng startup_candle_count nến của khung lớn nhất. Với cấu hình trên và backtest từ 1/1/2024: 60 ngày + 40 nến 4h (khoảng 7 ngày), tức dữ liệu từ khoảng cuối tháng 10/2023. Dữ liệu Bài 4 (từ 2023) đã đủ.

    freqtrade backtesting -c user_data/config.json -c user_data/config-freqai.json \
    --strategy FreqaiLgbmFutures --freqaimodel LightGBMRegressor \
    --timerange 20240101-20250101

    • Lần chạy đầu sẽ lâu: khoảng 52 lần huấn luyện cho mỗi cặp. Theo dõi log để thấy tiến độ, và dòng báo số điểm dữ liệu bị bỏ vì NaN; con số này nên là 0. Nếu không, tăng startup_candle_count.
    • Lần chạy sau với cùng identifier dùng lại model và dự đoán đã lưu, nên chỉ mất vài giây. Đây là lúc tinh chỉnh luật vào/ra (z_entry, min_edge), kể cả bằng hyperopt.
    • Đổi feature hay target: đổi identifier (ví dụ lgbm-v2), nếu không bạn sẽ đánh giá model cũ.

    Kiểm tra lookahead: lookahead-analysis hỗ trợ chiến lược FreqAI. Cột target được tạo trong set_freqai_targets() sẽ bị đánh dấu là lệch; tài liệu xác nhận đây là báo nhầm và có thể bỏ qua. Mọi cột feature bị đánh dấu thì phải sửa.

    freqtrade lookahead-analysis -c user_data/config.json -c user_data/config-freqai.json \
    --strategy FreqaiLgbmFutures --freqaimodel LightGBMRegressor \
    --timerange 20240301-20240601

    Hyperopt với FreqAI

    Được, nhưng có giới hạn: không tối ưu được tham số trong feature_engineering_* và set_freqai_targets, không dùng được --analyze-per-epoch. Cách hiệu quả là chỉ tối ưu ngưỡng vào/ra, vì FreqAI dùng lại dự đoán đã lưu:

    from freqtrade.strategy import DecimalParameter

    z_entry = DecimalParameter(0.5, 2.0, decimals=2, default=1.0, space="buy")
    # trong populate_indicators dùng self.z_entry.value thay cho self.z_entry
    Ngưỡng z-score được tính trong populate_indicators, nơi Bài 10 nói không được dùng .value. Với FreqAI, hãy chuyển phép tính long_th, short_th sang populate_entry_trend khi tối ưu tham số này.

    Lỗi thường gặp

    Triệu chứng Nguyên nhân Cách xử lý
    Đổi feature mà kết quả không đổi Dùng lại model và dự đoán của identifier cũ Đổi identifier hoặc xóa user_data/models/<identifier>
    Chạy live báo lỗi feature Feature khai báo trong populate_indicators Chuyển vào feature_engineering_*
    Log báo bỏ nhiều điểm vì NaN startup_candle_count quá nhỏ Nhân đôi chu kỳ lớn nhất
    Backtest báo thiếu dữ liệu Không có dữ liệu trước giai đoạn backtest cho cửa sổ huấn luyện đầu Tải thêm train_period_days + startup
    Hết RAM, huấn luyện rất lâu Quá nhiều feature do nhân khung × cặp × bản trễ Bớt khung, cặp tham chiếu, bản trễ
    Điểm test cao bất thường shuffle: true Đặt shuffle: false
    Rất ít lệnh do_predict thường khác 1, hoặc ngưỡng quá chặt Xem phân bố do_predict, DI_values; nới z_entry
    1 Reply Last reply
    0

    Hello! It looks like you're interested in this conversation, but you don't have an account yet.

    Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

    With your input, this post could be even better 💗

    Register Login
    Reply
    • Reply as topic
    Log in to reply
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes


    • Login

    • Don't have an account? Register

    • Login or register to search.
    Powered by NodeBB Contributors
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • World
    • Users
    • Groups