Trong thị trường perpetual futures, funding rate là chỉ số quan trọng phản ánh cân bằng giữa long và short positions. Việc dự đoán funding rate không chỉ giúp trader né những khoản phí bất lợi mà còn là chiến lược sinh lời hiệu quả. Bài viết này sẽ hướng dẫn bạn cách xây dựng pipeline chuẩn bị dữ liệu hoàn chỉnh, từ việc thu thập đến xử lý, với chi phí API tối ưu nhất.
Mở đầu: Tại sao cần chuẩn bị dữ liệu Funding Rate?
Funding rate không phải con số ngẫu nhiên — nó phản ánh tâm lý thị trường, thanh khoản, và động thái của các quỹ lớn. Một mô hình dự đoán chính xác có thể:
- Giảm 30-50% chi phí funding cho portfolio perpetual futures
- Phát hiện sớm trend đảo chiều dựa trên divergence giữa funding thực tế và dự đoán
- Tạo tín hiệu arbitrage giữa các sàn có funding rate khác nhau
Bảng so sánh: HolySheep vs Các giải pháp thu thập dữ liệu
| Tiêu chí | HolySheep AI | API chính thức (OpenAI/Anthropic) | Relay services khác |
|---|---|---|---|
| Chi phí GPT-4o | $2.00/1M tokens | $15.00/1M tokens | $3-8/1M tokens |
| Chi phí Claude Sonnet | $3.50/1M tokens | $15.00/1M tokens | $6-12/1M tokens |
| Chi phí Gemini 2.5 Flash | $0.50/1M tokens | $2.50/1M tokens | $1-2/1M tokens |
| Độ trễ trung bình | <50ms | 200-800ms | 100-400ms |
| Thanh toán | WeChat/Alipay, USDT, Visa | Chỉ Visa quốc tế | Thẻ quốc tế |
| Tín dụng miễn phí | Có, khi đăng ký | $5 trial | Không hoặc rất ít |
| Rate limit | Nới lỏng, phù hợp batch | Chặt chẽ | Trung bình |
Với việc tiết kiệm 85%+ chi phí API, HolySheep là lựa chọn tối ưu cho các pipeline data-intensive như funding rate prediction.
Kiến trúc Pipeline Chuẩn bị Dữ liệu
1. Tổng quan Flow xử lý
┌─────────────────────────────────────────────────────────────────┐
│ FUNDING RATE PREDICTION PIPELINE │
├─────────────────────────────────────────────────────────────────┤
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Data Source │───▶│ Processing │───▶│ Feature Eng │ │
│ │ Collection │ │ & Cleaning │ │ & Selection │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Exchange API │ │ ML Model │ │
│ │ (Binance, │ │ Training │ │
│ │ OKX, Bybit) │ │ Pipeline │ │
│ └──────────────┘ └──────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Prediction │ │
│ │ & Backtest │ │
│ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
2. Cấu trúc thư mục dự án
funding_rate_prediction/
├── config/
│ ├── __init__.py
│ ├── settings.py # Cấu hình chung
│ └── api_endpoints.py # Định nghĩa API endpoints
├── data/
│ ├── raw/ # Dữ liệu thô từ exchange
│ ├── processed/ # Dữ liệu đã xử lý
│ └── features/ # Feature engineering output
├── src/
│ ├── collectors/ # Thu thập dữ liệu
│ ├── processors/ # Xử lý dữ liệu
│ ├── features/ # Feature engineering
│ └── models/ # Model training & prediction
├── notebooks/ # EDA notebooks
├── scripts/ # ETL scripts
└── requirements.txt
Thu thập dữ liệu Funding Rate từ Multiple Exchanges
# config/settings.py
import os
from dataclasses import dataclass
from typing import List
@dataclass
class APIConfig:
"""Cấu hình API cho HolySheep - Base URL và API Key"""
base_url: str = "https://api.holysheep.ai/v1"
api_key: str = "YOUR_HOLYSHEEP_API_KEY"
model: str = "gpt-4o" # Hoặc deepseek-v3.2 cho chi phí thấp hơn
temperature: float = 0.1
max_tokens: int = 2000
@dataclass
class ExchangeConfig:
"""Cấu hình các sàn giao dịch"""
binance_ws: str = "wss://stream.binance.com:9443/ws"
okx_ws: str = "wss://ws.okx.com:8443/ws/v5/public"
bybit_ws: str = "wss://stream.bybit.com/v5/public/spot"
funding_rate_endpoint: str = "/fapi/v1/premiumIndexSnapshot"
Cấu hình features cần thu thập
@dataclass
class FeatureConfig:
funding_rate_history: int = 720 # 30 ngày x 24 giờ
price_history: int = 1440 # 60 ngày x 24 giỉ
volume_history: int = 1440 # 60 ngày x 24 giờ
open_interest_history: int = 720
prediction_horizon: int = 8 # Dự đoán 8 giờ tới
lookback_window: int = 168 # 7 ngày lookback
Cấu hình tokens cho mỗi loại request
FEATURE_EXTRACTION_TOKENS = {
"symbol_analysis": 1500,
"pattern_detection": 800,
"sentiment_summary": 600,
"anomaly_report": 500,
}
# src/collectors/funding_rate_collector.py
import asyncio
import aiohttp
import pandas as pd
from datetime import datetime, timedelta
from typing import Dict, List, Optional
import logging
import time
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class FundingRateCollector:
"""
Thu thập dữ liệu funding rate từ nhiều sàn giao dịch
Hỗ trợ: Binance, OKX, Bybit, Deribit
"""
def __init__(self, exchanges: List[str] = ["binance", "okx", "bybit"]):
self.exchanges = exchanges
self.base_urls = {
"binance": "https://fapi.binance.com",
"okx": "https://www.okx.com",
"bybit": "https://api.bybit.com",
}
self.data_cache = {}
async def fetch_binance_funding_rate(
self,
symbol: str,
start_time: Optional[int] = None,
limit: int = 500
) -> pd.DataFrame:
"""Thu thập funding rate từ Binance Futures"""
endpoint = "/fapi/v1/fundingRate"
params = {
"symbol": symbol,
"limit": limit
}
if start_time:
params["startTime"] = start_time
url = f"{self.base_urls['binance']}{endpoint}"
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as response:
if response.status == 200:
data = await response.json()
df = pd.DataFrame(data)
df['fundingTime'] = pd.to_datetime(df['fundingTime'], unit='ms')
df['fundingRate'] = df['fundingRate'].astype(float)
df['exchange'] = 'binance'
logger.info(f"Binance: Lấy được {len(df)} records cho {symbol}")
return df
else:
logger.error(f"Binance API error: {response.status}")
return pd.DataFrame()
async def fetch_okx_funding_rate(
self,
inst_id: str,
after: Optional[str] = None,
limit: int = 100
) -> pd.DataFrame:
"""Thu thập funding rate từ OKX"""
endpoint = "/api/v5/market/funding-rate-history"
params = {
"instId": inst_id,
"limit": limit
}
if after:
params["after"] = after
url = f"{self.base_urls['okx']}{endpoint}"
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as response:
if response.status == 200:
data = await response.json()
if data.get("code") == "0":
records = data.get("data", [])
df = pd.DataFrame(records)
if not df.empty:
df['fundingTime'] = pd.to_datetime(
df['fundingTime'], unit='ms'
)
df['fundingRate'] = df['fundingRate'].astype(float)
df['exchange'] = 'okx'
logger.info(f"OKX: Lấy được {len(df)} records cho {inst_id}")
return df
return pd.DataFrame()
async def fetch_bybit_funding_rate(
self,
category: str = "linear",
symbol: Optional[str] = None,
limit: int = 200
) -> pd.DataFrame:
"""Thu thập funding rate từ Bybit"""
endpoint = "/v5/market/funding-rate-history"
params = {
"category": category,
"limit": limit
}
if symbol:
params["symbol"] = symbol
url = f"{self.base_urls['bybit']}{endpoint}"
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as response:
if response.status == 200:
data = await response.json()
if data.get("retCode") == 0:
records = data.get("result", {}).get("list", [])
df = pd.DataFrame(records)
if not df.empty:
df['fundingTime'] = pd.to_datetime(
df['fundingRateTimestamp'], unit='s'
)
df['fundingRate'] = df['fundingRate'].astype(float)
df['exchange'] = 'bybit'
logger.info(f"Bybit: Lấy được {len(df)} records")
return df
return pd.DataFrame()
async def collect_all_funding_rates(
self,
symbols: Dict[str, str],
lookback_hours: int = 720
) -> pd.DataFrame:
"""
Thu thập funding rate từ tất cả các sàn
symbols: dict mapping exchange -> list of symbols
"""
all_data = []
end_time = int(datetime.now().timestamp() * 1000)
start_time = int(
(datetime.now() - timedelta(hours=lookback_hours)).timestamp() * 1000
)
tasks = []
for exchange, symbol_list in symbols.items():
for symbol in symbol_list:
if exchange == "binance":
tasks.append(
self.fetch_binance_funding_rate(
symbol, start_time, limit=500
)
)
elif exchange == "okx":
tasks.append(
self.fetch_okx_funding_rate(symbol, limit=100)
)
elif exchange == "bybit":
tasks.append(
self.fetch_bybit_funding_rate(symbol=symbol, limit=200)
)
# Execute all tasks concurrently
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, pd.DataFrame) and not result.empty:
all_data.append(result)
if all_data:
combined_df = pd.concat(all_data, ignore_index=True)
logger.info(f"Tổng cộng: {len(combined_df)} funding rate records")
return combined_df
else:
return pd.DataFrame()
def enrich_with_market_data(
self,
funding_df: pd.DataFrame,
market_data: Dict
) -> pd.DataFrame:
"""Bổ sung thông tin thị trường vào funding rate data"""
df = funding_df.copy()
# Merge price data
if 'price' in market_data:
df['mark_price'] = df['symbol'].map(
market_data['price'].get('mark_price', {})
)
df['index_price'] = df['symbol'].map(
market_data['price'].get('index_price', {})
)
# Merge volume data
if 'volume' in market_data:
df['volume_24h'] = df['symbol'].map(
market_data['volume'].get('24h_volume', {})
)
# Merge open interest
if 'open_interest' in market_data:
df['open_interest'] = df['symbol'].map(
market_data['open_interest'].get('total_oi', {})
)
return df
Sử dụng
async def main():
collector = FundingRateCollector(exchanges=["binance", "okx", "bybit"])
symbols = {
"binance": ["BTCUSDT", "ETHUSDT", "BNBUSDT", "SOLUSDT"],
"okx": ["BTC-USDT-SWAP", "ETH-USDT-SWAP"],
"bybit": ["BTCUSDT", "ETHUSDT"]
}
funding_data = await collector.collect_all_funding_rates(
symbols, lookback_hours=720
)
if not funding_data.empty:
funding_data.to_parquet("data/raw/funding_rates_combined.parquet")
print(f"Đã lưu {len(funding_data)} records")
if __name__ == "__main__":
asyncio.run(main())
Xử lý và Feature Engineering cho Mô hình
# src/features/funding_feature_engineering.py
import pandas as pd
import numpy as np
from typing import List, Dict, Optional, Tuple
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
class FundingRateFeatureEngine:
"""
Feature engineering chuyên biệt cho funding rate prediction
Tạo ra các features phản ánh:
- Xu hướng funding rate
- Volatility patterns
- Cross-exchange arbitrage opportunities
- Market regime detection
"""
def __init__(self, prediction_horizon: int = 8):
self.prediction_horizon = prediction_horizon # Giờ
self.features_cache = {}
def create_temporal_features(self, df: pd.DataFrame) -> pd.DataFrame:
"""Tạo features từ thời gian"""
df = df.copy()
# Extract time components
df['hour'] = df['fundingTime'].dt.hour
df['day_of_week'] = df['fundingTime'].dt.dayofweek
df['day_of_month'] = df['fundingTime'].dt.day
df['month'] = df['fundingTime'].dt.month
# Cyclical encoding cho time features
df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)
df['dow_sin'] = np.sin(2 * np.pi * df['day_of_week'] / 7)
df['dow_cos'] = np.cos(2 * np.pi * df['day_of_week'] / 7)
# Funding happens at specific times: 00:00, 08:00, 16:00 UTC
df['is_funding_hour'] = df['hour'].isin([0, 8, 16]).astype(int)
df['hours_to_next_funding'] = df['hour'].apply(
lambda x: min(abs(x - 0), abs(x - 8), abs(x - 16),
24 - abs(x - 0), 24 - abs(x - 8), 24 - abs(x - 16))
)
return df
def create_lag_features(
self,
df: pd.DataFrame,
lags: List[int] = [1, 2, 3, 4, 8, 12, 24, 48, 72]
) -> pd.DataFrame:
"""Tạo lag features cho funding rate"""
df = df.copy()
df = df.sort_values(['symbol', 'exchange', 'fundingTime'])
# Lag features
for lag in lags:
df[f'funding_rate_lag_{lag}'] = df.groupby(
['symbol', 'exchange']
)['fundingRate'].shift(lag)
# Rolling statistics
windows = [4, 8, 12, 24, 48, 72, 168] # 4h, 8h, 12h, 1d, 2d, 3d, 7d
for window in windows:
grouped = df.groupby(['symbol', 'exchange'])['fundingRate']
df[f'funding_rate_ma_{window}'] = grouped.transform(
lambda x: x.rolling(window, min_periods=window//2).mean()
)
df[f'funding_rate_std_{window}'] = grouped.transform(
lambda x: x.rolling(window, min_periods=window//2).std()
)
df[f'funding_rate_min_{window}'] = grouped.transform(
lambda x: x.rolling(window, min_periods=window//2).min()
)
df[f'funding_rate_max_{window}'] = grouped.transform(
lambda x: x.rolling(window, min_periods=window//2).max()
)
return df
def create_momentum_features(self, df: pd.DataFrame) -> pd.DataFrame:
"""Tạo momentum và trend features"""
df = df.copy()
df = df.sort_values(['symbol', 'exchange', 'fundingTime'])
# Rate of change
for period in [1, 4, 8, 12, 24]:
df[f'funding_rate_roc_{period}'] = df.groupby(
['symbol', 'exchange']
)['fundingRate'].pct_change(period)
# Momentum
for period in [4, 8, 12, 24]:
df[f'funding_rate_momentum_{period}'] = df.groupby(
['symbol', 'exchange']
)['fundingRate'].transform(
lambda x: x - x.rolling(period).mean()
)
# Acceleration (đạo hàm bậc 2)
df['funding_rate_acceleration'] = df.groupby(
['symbol', 'exchange']
)['fundingRate'].diff().diff()
# Trend strength (ADX-like)
for window in [8, 12, 24]:
df[f'funding_trend_strength_{window}'] = df.groupby(
['symbol', 'exchange']
).apply(
lambda x: self._calculate_trend_strength(
x['fundingRate'], window
)
).reset_index(level=[0,1], drop=True)
return df
def _calculate_trend_strength(self, series: pd.Series, window: int) -> pd.Series:
"""Tính trend strength (simplified ADX)"""
result = pd.Series(index=series.index, dtype=float)
for i in range(window, len(series)):
window_data = series.iloc[i-window:i]
high = window_data.max()
low = window_data.min()
current = series.iloc[i]
if high != low:
# Vị trí tương đối trong range
result.iloc[i] = (current - low) / (high - low)
else:
result.iloc[i] = 0.5
return result
def create_cross_exchange_features(
self,
df: pd.DataFrame,
symbols: List[str]
) -> pd.DataFrame:
"""Tạo features so sánh giữa các sàn"""
df = df.copy()
# Pivot để so sánh funding rate giữa các sàn
pivot_df = df.pivot_table(
index='fundingTime',
columns='exchange',
values='fundingRate',
aggfunc='first'
)
exchanges = [col for col in pivot_df.columns if col in ['binance', 'okx', 'bybit']]
# Tính divergence giữa các sàn
for i, ex1 in enumerate(exchanges):
for ex2 in exchanges[i+1:]:
if ex1 in pivot_df.columns and ex2 in pivot_df.columns:
pivot_df[f'divergence_{ex1}_{ex2}'] = (
pivot_df[ex1] - pivot_df[ex2]
)
pivot_df[f'divergence_ratio_{ex1}_{ex2}'] = (
pivot_df[ex1] / (pivot_df[ex2] + 1e-8) - 1
)
# Funding rate trung bình cross-exchange
pivot_df['avg_funding_rate'] = pivot_df[exchanges].mean(axis=1)
pivot_df['max_funding_rate'] = pivot_df[exchanges].max(axis=1)
pivot_df['min_funding_rate'] = pivot_df[exchanges].min(axis=1)
pivot_df['funding_rate_spread'] = (
pivot_df['max_funding_rate'] - pivot_df['min_funding_rate']
)
# Merge back
df = df.merge(
pivot_df.reset_index(),
on='fundingTime',
how='left'
)
return df
def create_target_variable(
self,
df: pd.DataFrame,
prediction_horizon: int = 8
) -> pd.DataFrame:
"""Tạo biến mục tiêu cho prediction"""
df = df.copy()
df = df.sort_values(['symbol', 'exchange', 'fundingTime'])
# Target: funding rate tại t+prediction_horizon
df['target_funding_rate'] = df.groupby(
['symbol', 'exchange']
)['fundingRate'].shift(-prediction_horizon)
# Target: thay đổi funding rate
df['target_funding_change'] = df.groupby(
['symbol', 'exchange']
).apply(
lambda x: x['target_funding_rate'] - x['fundingRate']
).reset_index(level=[0,1], drop=True)
# Target: direction (up/down/same)
df['target_direction'] = np.sign(df['target_funding_change'])
# Binary target: có funding rate cao hơn không
threshold = df['fundingRate'].quantile(0.75)
df['target_high_funding'] = (
df['target_funding_rate'] > threshold
).astype(int)
return df
def create_all_features(
self,
df: pd.DataFrame,
symbols: List[str],
prediction_horizon: Optional[int] = None
) -> pd.DataFrame:
"""Tạo tất cả features"""
horizon = prediction_horizon or self.prediction_horizon
# Step 1: Temporal features
df = self.create_temporal_features(df)
# Step 2: Lag features
df = self.create_lag_features(df)
# Step 3: Momentum features
df = self.create_momentum_features(df)
# Step 4: Cross-exchange features
df = self.create_cross_exchange_features(df, symbols)
# Step 5: Target variable
df = self.create_target_variable(df, horizon)
# Drop rows with missing targets
df = df.dropna(subset=['target_funding_rate'])
return df
Sử dụng
if __name__ == "__main__":
# Load dữ liệu
df = pd.read_parquet("data/raw/funding_rates_combined.parquet")
# Khởi tạo feature engine
feature_engine = FundingRateFeatureEngine(prediction_horizon=8)
# Tạo features
symbols = df['symbol'].unique().tolist()
df_features = feature_engine.create_all_features(df, symbols)
# Lưu features
df_features.to_parquet("data/features/funding_features_v1.parquet")
print(f"Tạo thành công {len(df_features.columns)} features")
print(f"Số records: {len(df_features)}")
print(f"Features mới: {[c for c in df_features.columns if 'funding' in c.lower()][:10]}")
Sử dụng HolySheep AI cho Data Analysis và Pattern Detection
# src/processors/ai_analysis.py
import aiohttp
import json
import asyncio
from typing import Dict, List, Optional, Any
from dataclasses import dataclass
import pandas as pd
from datetime import datetime
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class HolySheepConfig:
"""Cấu hình HolySheep API"""
base_url: str = "https://api.holysheep.ai/v1"
api_key: str = "YOUR_HOLYSHEEP_API_KEY"
# Models với chi phí
models = {
"deepseek-v3.2": {
"cost_per_mtok": 0.42, # Chi phí rẻ nhất
"best_for": "Data analysis, pattern detection"
},
"gpt-4o": {
"cost_per_mtok": 8.00,
"best_for": "Complex reasoning, multi-step analysis"
},
"claude-sonnet-4.5": {
"cost_per_mtok": 15.00,
"best_for": "Long context analysis"
},
"gemini-2.5-flash": {
"cost_per_mtok": 2.50,
"best_for": "Fast inference, real-time analysis"
}
}
class HolySheepAIClient:
"""
Client để sử dụng HolySheep AI cho funding rate analysis
Chi phí tiết kiệm 85%+ so với API chính thức
"""
def __init__(self, api_key: str):
self.config = HolySheepConfig(api_key=api_key)
self.session = None
async def __aenter__(self):
self.session = aiohttp.ClientSession(
headers={
"Authorization": f"Bearer {self.config.api_key}",
"Content-Type": "application/json"
}
)
return self
async def __aexit__(self, *args):
if self.session:
await self.session.close()
async def chat_completion(
self,
messages: List[Dict[str, str]],
model: str = "deepseek-v3.2", # Model tiết kiệm nhất
temperature: float = 0.1,
max_tokens: int = 2000
) -> Dict[str, Any]:
"""Gọi HolySheep Chat Completion API"""
url = f"{self.config.base_url}/chat/completions"
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
"max_tokens": max_tokens
}
try:
async with self.session.post(url, json=payload) as response:
if response.status == 200:
result = await response.json()
usage = result.get("usage", {})
# Tính chi phí
cost = self._calculate_cost(model, usage)
return {
"content": result["choices"][0]["message"]["content"],
"usage": usage,
"cost_usd": cost,
"model": model
}
else:
error_text = await response.text()
logger.error(f"API Error {response.status}: {error_text}")
return {"error": error_text, "status": response.status}
except Exception as e:
logger.error(f"Request failed: {e}")
return {"error": str(e)}
def _calculate_cost(self, model: str, usage: Dict) -> float:
"""Tính chi phí dựa trên token usage"""
if model not in self.config.models:
model = "deepseek-v3.2" # Default
cost_per_mtok = self.config.models[model]["cost_per_mtok"]
total_tokens = usage.get("total_tokens", 0)
return (total_tokens / 1_000_000) * cost_per_mtok
async def analyze_funding_anomaly(
self,
symbol: str,
funding_history: List[Dict],
price_data: Dict
) -> Dict[str, Any]:
"""Phân tích anomaly trong funding rate sử dụng AI"""
prompt = f"""Analyze the following funding rate data for {symbol}:
Funding History (recent 24 hours):
{json.dumps(funding_history[-24:], indent=2)}
Price Data:
- Current Price: ${price_data.get('current_price', 'N/A')}
- 24h Change: {price_data.get('price_change_24h', 'N/A')}%
- 24h Volume: ${price_data.get('volume_24h', 'N/A')}
Please identify:
1. Any anomalies in funding rate patterns
2. Potential market manipulation signals
3. Correlation between price and funding rate
4. Trading recommendations
Respond in JSON format."""
messages = [
{"role": "system", "content": "You are a cryptocurrency analyst specializing in perpetual futures funding rates."},
{"role": "user", "content": prompt}
]
return await self.chat_completion(
messages,
model="deepseek-v3.2", # Đủ cho analysis
temperature=0.1,
max_tokens=1500
)
async def detect_funding_patterns(
self,
funding_df: pd.DataFrame,
symbols: List[str]
) -> Dict[str, Any]:
"""Phát hiện patterns trong funding rate data"""
# Tóm tắt data cho AI
summary = self._create_data_summary(funding_df, symbols)
prompt = f"""Analyze funding rate patterns across multiple exchanges for: {', '.join(symbols)}
Data Summary:
{summary}
Identify:
1. Seasonal patterns (time-of-day, day-of-week)
2. Cross-exchange arbitrage opportunities
3. Tokens with unusual funding rate behavior
4. Market regime changes
Respond in detailed JSON format."""
messages = [
{"role": "system", "content": "You are an expert in cryptocurrency perpetual futures markets and funding rate dynamics."},
{"role": "user", "content": prompt}
]
return await self.chat_completion(
messages,
model="deepseek-v3.2",
temperature=0.2,
max_tokens=2000
)
def _create_data_summary(self, df: pd.DataFrame, symbols: List[str]) -> str:
"""Tạo summary của data cho AI prompt"""
summary_parts = []
for symbol in symbols[:10]: # Limit để tiết kiệm tokens
symbol_data = df[df['symbol'] == symbol]
if not symbol_data.empty:
summary_parts.append(f"""
{symbol}:
- Avg Funding Rate: {symbol_data['fundingRate'].mean():.6f}
- Std Dev: {symbol_data['fundingRate'].std():.6f}
- Min: {symbol_data['fundingRate'].min():.6f}
- Max: {symbol_data['fundingRate'].max():.6f}
- Trend (7d): {symbol_data['fundingRate'].iloc[-168:].mean() if len(symbol_data) > 168 else 'N/A'}
""")
return "\n".join(summary_parts)
async def batch_analyze_symbols(
self,
symbols_data: Dict[str, Dict],
analysis_type: str = "anomaly"
) -> List[Dict[str, Any]]:
"""Batch analyze nhiều symbols để tiết kiệm chi phí"""
results = []
# Group thành batches đ