Skip to content

Importing Data

Hướng dẫn import dữ liệu từ nhiều nguồn khác nhau vào QuantConnect cho backtest và live trading.

Các Phương Pháp Import

Phương phápDùng khiVí dụ
Custom Data (PythonData)Dữ liệu không có sẵn trên QCVN30F, dữ liệu CSV riêng
ObjectStoreLưu ML models, parameters, cacheModel huấn luyện sẵn
API call in OnDataDữ liệu real-time từ bên ngoàiNews API, sentiment API
Lean Data DownloadTải dữ liệu từ QC về locallean data download

ObjectStore

python
# Lưu model
model_bytes = pickle.dumps(trained_model)
self.ObjectStore.Save("model.pkl", model_bytes)

# Đọc model
if self.ObjectStore.ContainsKey("model.pkl"):
    model_bytes = self.ObjectStore.Read("model.pkl")
    model = pickle.loads(model_bytes)

# Lưu kết quả
self.ObjectStore.Save("results.csv", "date,pnl,sharpe\n2024-01-01,1000,1.5")

API Data trong OnData

python
class MyAPIAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2024, 1, 1)
        self.SetCash(100000)
        # Schedule job mỗi giờ
        self.Schedule.On(self.DateRules.EveryDay(),
                         self.TimeRules.Every(timedelta(hours=1)),
                         self.CallExternalAPI)

    def CallExternalAPI(self):
        import requests
        response = requests.get("https://api.example.com/data")
        if response.status_code == 200:
            self.api_data = response.json()
            self.Debug(f"API data: {self.api_data}")

Import CSV cho Backtest

python
# Python script bên ngoài: convert CSV → định dạng LEAN
import pandas as pd

# Đọc CSV VN30F
df = pd.read_csv("vn30f_2026.csv")
df['timestamp'] = pd.to_datetime(df['timestamp'])

# Sắp xếp và lưu theo ngày cho LEAN
for date, group in df.groupby(df['timestamp'].dt.date):
    date_str = date.strftime("%Y%m%d")
    group.to_csv(f"data/vn30f/{date_str}.csv",
                 index=False, header=False)

Powered by dautu.tech