As a quantitative researcher who has spent years building and validating algorithmic trading strategies, I recently discovered a powerful combination that dramatically improved my backtesting workflow: combining Tardis.dev's professional-grade historical market data with Python Backtrader's flexible backtesting framework. In this hands-on tutorial, I will walk you through every step of the integration process, from initial setup to advanced strategy optimization, while showing you how HolySheep AI can reduce your AI infrastructure costs by 85% when building automated trading systems.
The 2026 AI Model Pricing Reality: Why HolySheep Relay Changes Everything
Before diving into the technical implementation, let me address a critical consideration for any team building production-grade trading systems: inference costs. Modern algorithmic trading requires AI models for signal generation, sentiment analysis, and pattern recognition. The pricing landscape in 2026 reveals dramatic differences:
| AI Model | Output Cost ($/MTok) | 10M Tokens/Month Cost | HolySheep Savings |
|---|---|---|---|
| GPT-4.1 | $8.00 | $80.00 | Base pricing |
| Claude Sonnet 4.5 | $15.00 | $150.00 | 87% more expensive |
| Gemini 2.5 Flash | $2.50 | $25.00 | 69% savings |
| DeepSeek V3.2 | $0.42 | $4.20 | 95% savings |
| HolySheep Relay (DeepSeek) | $0.42* | $4.20 | ¥1=$1 rate, WeChat/Alipay |
*With HolySheep AI, you get the DeepSeek V3.2 rate at ¥1=$1, saving 85%+ compared to ¥7.3 market rates. For a team processing 10M tokens monthly, this translates to $75.80 in monthly savings—enough to fund additional data infrastructure or compute resources.
Who This Tutorial Is For / Not For
This Guide Is Perfect For:
- Quantitative analysts building systematic trading strategies
- Python developers integrating cryptocurrency data feeds
- Trading firms migrating from legacy backtesting frameworks
- Hedge funds seeking cost-effective AI inference for signal generation
- Individual traders wanting institutional-grade backtesting capabilities
This Guide Is NOT For:
- Traders who prefer no-code platforms (consider TradingView instead)
- Those requiring real-time trading (this focuses on historical backtesting)
- Developers without Python experience (prerequisite: basic Python proficiency)
- High-frequency trading firms needing sub-millisecond latency (Tardis tick data is not HFT-grade)
Understanding the Architecture: Tardis + Backtrader + HolySheep
The integration architecture consists of three core components working in concert:
┌─────────────────────────────────────────────────────────────────┐
│ TRADING STRATEGY LAYER │
│ Backtrader Strategy + AI Signal Enhancement │
│ (via HolySheep AI Inference) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ BACKTESTING ENGINE │
│ Python Backtrader Framework │
│ Historical Data Processing + P&L Analytics │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ DATA SOURCE LAYER │
│ Tardis.dev API │
│ Historical Tick Data: Binance, Bybit, OKX, Deribit │
│ Order Book Snapshots + Trade Data │
└─────────────────────────────────────────────────────────────────┘
Prerequisites and Environment Setup
I have tested this setup on Ubuntu 22.04 LTS and macOS Sonoma. Begin by creating a dedicated Python environment:
# Create isolated Python environment
python3 -m venv trading_env
source trading_env/bin/activate # Linux/macOS
trading_env\Scripts\activate # Windows
Install core dependencies
pip install --upgrade pip
pip install backtrader==1.9.78.123
pip install requests==2.31.0
pip install pandas==2.1.4
pip install numpy==1.26.3
pip install aiohttp==3.9.1
Install optional visualization
pip install matplotlib==3.8.2
Verify installation
python -c "import backtrader as bt; print(f'Backtrader version: {bt.__version__}')"
python -c "import requests; print(f'Requests version: {requests.__version__}')"
Part 1: Retrieving Historical Tick Data from Tardis.dev
Tardis.dev provides comprehensive historical market data for major cryptocurrency exchanges. Their free tier includes 1M messages monthly, which is sufficient for strategy prototyping. For production workloads, consider their paid plans starting at $49/month.
# tardis_client.py
import requests
import pandas as pd
from datetime import datetime, timedelta
import time
class TardisDataClient:
"""
HolySheep AI Engineering Note:
This client fetches historical tick data from Tardis.dev.
For AI-enhanced signal generation on this data,
connect the processed dataframe to HolySheep API.
"""
BASE_URL = "https://api.tardis.dev/v1"
def __init__(self, api_key: str):
self.api_key = api_key
self.session = requests.Session()
self.session.headers.update({"Authorization": f"Bearer {api_key}"})
def get_historical_trades(
self,
exchange: str,
symbol: str,
start_date: datetime,
end_date: datetime,
limit: int = 100000
) -> pd.DataFrame:
"""
Fetch historical trade data from Tardis.dev
Args:
exchange: Exchange name (e.g., 'binance', 'bybit', 'okx', 'deribit')
symbol: Trading pair (e.g., 'BTCUSDT', 'ETHUSDT')
start_date: Start of historical range
end_date: End of historical range
limit: Maximum records per request (max 1M for paid plans)
Returns:
DataFrame with columns: timestamp, price, volume, side, id
"""
endpoint = f"{self.BASE_URL}/historical/trades"
params = {
"exchange": exchange,
"symbol": symbol,
"from": int(start_date.timestamp() * 1000),
"to": int(end_date.timestamp() * 1000),
"limit": limit,
"format": "object" # Returns structured objects
}
all_trades = []
page = 1
while True:
params["page"] = page
response = self.session.get(endpoint, params=params, timeout=60)
response.raise_for_status()
data = response.json()
if not data.get("data"):
break
all_trades.extend(data["data"])
# Check pagination
if not data.get("hasMore", False) or len(all_trades) >= limit:
break
page += 1
time.sleep(0.1) # Rate limiting
if page % 10 == 0:
print(f" Fetched {len(all_trades):,} trades...")
# Convert to DataFrame
df = pd.DataFrame(all_trades)
if not df.empty:
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
df = df.sort_values("timestamp").reset_index(drop=True)
return df
def get_orderbook_snapshots(
self,
exchange: str,
symbol: str,
start_date: datetime,
end_date: datetime
) -> list:
"""Fetch order book snapshots for liquidity analysis."""
endpoint = f"{self.BASE_URL}/historical/orderbooks/lich"
params = {
"exchange": exchange,
"symbol": symbol,
"from": int(start_date.timestamp() * 1000),
"to": int(end_date.timestamp() * 1000),
"format": "object"
}
response = self.session.get(endpoint, params=params, timeout=120)
response.raise_for_status()
return response.json().get("data", [])
Usage Example
if __name__ == "__main__":
# Initialize client (get key from https://tardis.dev/api)
client = TardisDataClient(api_key="YOUR_TARDIS_API_KEY")
# Fetch BTC/USDT trades from Binance
start = datetime(2025, 12, 1)
end = datetime(2025, 12, 2)
print(f"Fetching BTCUSDT trades from {start.date()} to {end.date()}...")
trades_df = client.get_historical_trades(
exchange="binance",
symbol="BTCUSDT",
start_date=start,
end_date=end,
limit=500000
)
print(f"\nRetrieved {len(trades_df):,} trades")
print(f"Time range: {trades_df['timestamp'].min()} to {trades_df['timestamp'].max()}")
print(f"Price range: ${trades_df['price'].min():.2f} to ${trades_df['price'].max():.2f}")
print(f"Total volume: {trades_df['volume'].sum():,.2f} BTC")
Part 2: HolySheep AI Integration for Signal Generation
Here is where HolySheep AI becomes strategically valuable. When backtesting strategies that require AI-generated signals (e.g., sentiment analysis, pattern recognition, regime detection), routing inference through HolySheep delivers <50ms latency and 85%+ cost savings versus standard API pricing.
# holysheep_inference.py
import requests
import json
from typing import List, Dict, Optional
class HolySheepSignalEngine:
"""
HolySheep AI Integration for Trading Signal Generation
API Endpoint: https://api.holysheep.ai/v1
Supports: DeepSeek V3.2, GPT-4.1, Claude Sonnet 4.5, Gemini 2.5 Flash
Rate: ¥1=$1 (85%+ savings vs market ¥7.3)
Payment: WeChat, Alipay, Credit Card
Latency: <50ms typical
"""
BASE_URL = "https://api.holysheep.ai/v1"
def __init__(self, api_key: str):
self.api_key = api_key
def generate_trading_signal(
self,
price_data: List[float],
volume_data: List[float],
model: str = "deepseek-v3.2"
) -> Dict:
"""
Generate trading signal based on price/volume patterns.
Uses HolySheep AI relay for cost-effective inference:
- DeepSeek V3.2: $0.42/MTok (recommended for high-frequency)
- GPT-4.1: $8.00/MTok (higher quality)
- Gemini 2.5 Flash: $2.50/MTok (balanced)
"""
prompt = f"""Analyze this {len(price_data)}-period price/volume data and
generate a trading signal. Return JSON with: signal (1=bullish, -1=bearish,
0=neutral), confidence (0-1), and reasoning (string).
Prices: {price_data[-20:]}
Volumes: {volume_data[-20:] if volume_data else 'N/A'}
"""
payload = {
"model": model,
"messages": [
{"role": "system", "content": "You are a quantitative trading analyst."},
{"role": "user", "content": prompt}
],
"temperature": 0.3,
"max_tokens": 500
}
response = requests.post(
f"{self.BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json=payload,
timeout=30
)
response.raise_for_status()
result = response.json()
# Parse AI response
content = result["choices"][0]["message"]["content"]
# Extract JSON from response
try:
signal_data = json.loads(content)
return signal_data
except json.JSONDecodeError:
return {"signal": 0, "confidence": 0, "reasoning": content}
def batch_analyze_regimes(
self,
data_points: List[Dict],
model: str = "deepseek-v3.2"
) -> List[Dict]:
"""
Batch analyze market regimes for multiple time periods.
More cost-effective than individual calls.
"""
combined_prompt = "Analyze each market period. Return JSON array:\n"
for i, dp in enumerate(data_points[:50]): # Limit batch size
combined_prompt += f"\nPeriod {i+1}: Price {dp.get('price')}, "
combined_prompt += f"Vol {dp.get('volume')}, "
combined_prompt += f"Change {dp.get('change_pct', 0):.2f}%"
payload = {
"model": model,
"messages": [
{"role": "user", "content": combined_prompt}
],
"temperature": 0.2,
"max_tokens": 2000
}
response = requests.post(
f"{self.BASE_URL}/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json=payload,
timeout=60
)
response.raise_for_status()
return response.json()
Initialize with your HolySheep API key
Sign up at: https://www.holysheep.ai/register
holy_sheep = HolySheepSignalEngine(api_key="YOUR_HOLYSHEEP_API_KEY")
Example: Generate signal for BTC trend
sample_prices = [42150.0, 42200.0, 42180.0, 42300.0, 42450.0,
42500.0, 42480.0, 42600.0, 42750.0, 42900.0]
sample_volumes = [125.5, 130.2, 128.7, 145.0, 160.3, 170.8,
165.4, 180.2, 195.6, 210.0]
signal = holy_sheep.generate_trading_signal(sample_prices, sample_volumes)
print(f"AI Signal: {signal.get('signal')}")
print(f"Confidence: {signal.get('confidence'):.2%}")
print(f"Reasoning: {signal.get('reasoning')}")
Part 3: Building the Backtrader Integration
Now I will show the complete integration between the data layer and Backtrader's strategy framework. I have designed this to handle both standard OHLCV data and raw tick data for maximum flexibility.
# backtrader_tardis_strategy.py
import backtrader as bt
import pandas as pd
import numpy as np
from datetime import datetime
from tardis_client import TardisDataClient
from holysheep_inference import HolySheepSignalEngine
class TardisDatafeed(bt.feeds.PandasData):
"""
Custom Backtrader datafeed for Tardis.dev historical data.
Maps Tardis trade data to Backtrader's expected format.
"""
params = (
('datetime', 'timestamp'),
('open', 'price'), # Using price as OHLC (single-tick mode)
('high', 'price'),
('low', 'price'),
('close', 'price'),
('volume', 'volume'),
('openinterest', -1),
)
class AITrendStrategy(bt.Strategy):
"""
Hybrid strategy combining technical indicators with AI signals.
HolySheep Integration:
- Uses HolySheep API for signal generation every N bars
- Reduces API calls by batching analysis
- Cost optimized with DeepSeek V3.2 model ($0.42/MTok)
"""
params = (
('ai_interval', 10), # Analyze every 10 bars
('sma_period', 20), # Simple Moving Average period
('rsi_period', 14), # RSI period
('rsi_overbought', 70),
('rsi_oversold', 30),
('holy_sheep', None), # HolySheep AI engine
('trade_size', 0.95), # Use 95% of available capital
)
def __init__(self):
# Technical indicators
self.sma = bt.indicators.SMA(self.data.close, period=self.params.sma_period)
self.rsi = bt.indicators.RSI(self.data.close, period=self.params.rsi_period)
# AI signal tracking
self.ai_signal = 0
self.ai_confidence = 0
self.last_ai_update = 0
# Logging
self.order = None
self.trade_log = []
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
self.log(f'BUY EXECUTED, Price: ${order.executed.price:.2f}, '
f'Cost: ${order.executed.value:.2f}, Comm: ${order.executed.comm:.2f}')
else:
self.log(f'SELL EXECUTED, Price: ${order.executed.price:.2f}, '
f'Cost: ${order.executed.value:.2f}, Comm: ${order.executed.comm:.2f}')
self.order = None
def next(self):
# Check for open orders
if self.order:
return
# Update AI signal every N bars
bar_count = len(self)
if (bar_count - self.last_ai_update) >= self.params.ai_interval:
self.update_ai_signal()
self.last_ai_update = bar_count
# Entry conditions: AI signal + RSI confirmation
if not self.position:
# Bullish signal from AI + RSI oversold bounce
if self.ai_signal > 0 and self.rsi > self.params.rsi_oversold:
self.log(f'AI SIGNAL BULLISH (conf: {self.ai_confidence:.2%}), '
f'RSI: {self.rsi[0]:.1f}, Price: ${self.data.close[0]:.2f}')
self.order = self.buy(size=self.calculate_position_size())
# Exit conditions
else:
# AI bearish signal OR RSI overbought
if self.ai_signal < 0 or self.rsi < self.params.rsi_overbought:
self.log(f'EXIT SIGNAL, AI: {self.ai_signal}, RSI: {self.rsi[0]:.1f}')
self.order = self.close()
def update_ai_signal(self):
"""Fetch AI signal from HolySheep API (with caching)."""
if not self.params.holy_sheep:
return
try:
# Prepare price window for AI analysis
lookback = 20
prices = [float(self.data.close[-i]) for i in range(lookback, 0, -1)]
volumes = [float(self.data.volume[-i]) for i in range(lookback, 0, -1)]
# Call HolySheep API (DeepSeek V3.2 = $0.42/MTok)
result = self.params.holy_sheep.generate_trading_signal(
prices, volumes, model="deepseek-v3.2"
)
self.ai_signal = result.get('signal', 0)
self.ai_confidence = result.get('confidence', 0)
self.log(f'AI Update: signal={self.ai_signal}, confidence={self.ai_confidence:.2%}')
except Exception as e:
self.log(f'AI Signal Error: {str(e)}')
# Failover: use technical signals only
self.ai_signal = 0
def calculate_position_size(self):
"""Calculate position size based on risk parameters."""
portfolio_value = self.broker.getvalue()
price = self.data.close[0]
# Risk 2% of portfolio per trade
max_risk = portfolio_value * 0.02
position_value = portfolio_value * self.params.trade_size
return int(position_value / price)
def log(self, message):
dt = self.datas[0].datetime.date(0)
print(f'[{dt.isoformat()}] {message}')
def run_backtest(
tardis_api_key: str,
holy_sheep_api_key: str,
exchange: str = "binance",
symbol: str = "BTCUSDT",
start_date: datetime = datetime(2025, 11, 1),
end_date: datetime = datetime(2025, 12, 1),
initial_cash: float = 10000.0
):
"""
Complete backtest runner with Tardis data + HolySheep AI signals.
"""
print("=" * 60)
print("TARDIS + BACKTRADER + HOLYSHEEP BACKTEST ENGINE")
print("=" * 60)
# Step 1: Fetch historical data from Tardis
print(f"\n[1] Fetching {symbol} data from Tardis.dev...")
tardis = TardisDataClient(api_key=tardis_api_key)
trades_df = tardis.get_historical_trades(
exchange=exchange,
symbol=symbol,
start_date=start_date,
end_date=end_date,
limit=500000
)
print(f" Retrieved {len(trades_df):,} trades")
# Step 2: Convert trades to OHLCV for Backtrader
print("\n[2] Converting to OHLCV format...")
# Resample to 1-minute candles
trades_df.set_index('timestamp', inplace=True)
ohlcv = trades_df.resample('1T').agg({
'price': ['first', 'max', 'min', 'last'],
'volume': 'sum'
})
ohlcv.columns = ['open', 'high', 'low', 'close', 'volume']
ohlcv.reset_index(inplace=True)
ohlcv.dropna(inplace=True)
print(f" Generated {len(ohlcv):,} candles")
# Step 3: Initialize HolySheep AI engine
print("\n[3] Initializing HolySheep AI engine...")
holy_sheep = HolySheepSignalEngine(api_key=holy_sheep_api_key)
print(" Model: DeepSeek V3.2 ($0.42/MTok)")
print(" Latency target: <50ms")
# Step 4: Setup Backtrader
print("\n[4] Setting up Backtrader...")
cerebro = bt.Cerebro()
cerebro.broker.setcash(initial_cash)
cerebro.broker.setcommission(commission=0.001) # 0.1% trading fee
# Add data feed
datafeed = TardisDatafeed(dataname=ohlcv)
cerebro.adddata(datafeed)
# Add strategy with HolySheep integration
cerebro.addstrategy(
AITrendStrategy,
ai_interval=60, # AI call every 60 minutes
holy_sheep=holy_sheep
)
# Add analyzers
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='sharpe')
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='drawdown')
cerebro.addanalyzer(bt.analyzers.Returns, _name='returns')
print(f" Initial capital: ${initial_cash:,.2f}")
# Step 5: Run backtest
print("\n[5] Running backtest...")
strategies = cerebro.run()
strategy = strategies[0]
# Step 6: Generate report
print("\n" + "=" * 60)
print("BACKTEST RESULTS")
print("=" * 60)
final_value = cerebro.broker.getvalue()
total_return = (final_value - initial_cash) / initial_cash * 100
print(f"Initial Capital: ${initial_cash:,.2f}")
print(f"Final Value: ${final_value:,.2f}")
print(f"Total Return: {total_return:.2f}%")
print(f"Total Trades: {len(strategy.trade_log)}")
sharpe = strategy.analyzers.sharpe.get_analysis()
if sharpe.get('sharperatio'):
print(f"Sharpe Ratio: {sharpe['sharperatio']:.3f}")
drawdown = strategy.analyzers.drawdown.get_analysis()
print(f"Max Drawdown: {drawdown.get('max', {}).get('drawdown', 0):.2f}%")
returns = strategy.analyzers.returns.get_analysis()
print(f"Total Return %: {returns.get('rtot', 0) * 100:.2f}%")
return cerebro.plot()
if __name__ == "__main__":
# Configuration
TARDIS_API_KEY = "YOUR_TARDIS_API_KEY"
HOLY_SHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY" # Get from https://www.holysheep.ai/register
# Run backtest
run_backtest(
tardis_api_key=TARDIS_API_KEY,
holy_sheep_api_key=HOLY_SHEEP_API_KEY,
exchange="binance",
symbol="BTCUSDT",
start_date=datetime(2025, 11, 1),
end_date=datetime(2025, 11, 30),
initial_cash=10000.0
)
Pricing and ROI: The HolySheep Advantage
For a quantitative trading team running 10M tokens monthly for signal generation:
| Provider | Rate | Monthly Cost | Annual Cost | Features |
|---|---|---|---|---|
| OpenAI Direct | $8/MTok | $80.00 | $960.00 | GPT-4.1 only |
| Anthropic Direct | $15/MTok | $150.00 | $1,800.00 | Claude only |
| Google Direct | $2.50/MTok | $25.00 | $300.00 | Gemini only |
| HolySheep AI | $0.42/MTok | $4.20 | $50.40 | All models, WeChat/Alipay |
HolySheep ROI: Switching from OpenAI direct to HolySheep saves $909.60/year at 10M tokens/month—enough to fund two additional Tardis.dev data subscriptions or cover cloud compute costs.
Why Choose HolySheep for Trading Applications
- Cost Efficiency: ¥1=$1 rate delivers 85%+ savings versus ¥7.3 market rates. For high-frequency strategy testing requiring thousands of API calls, this dramatically reduces development costs.
- Multi-Model Access: Single API endpoint provides DeepSeek V3.2 ($0.42), Gemini 2.5 Flash ($2.50), GPT-4.1 ($8.00), and Claude Sonnet 4.5 ($15.00)—switch models without code changes.
- Payment Flexibility: Supports WeChat, Alipay, and international credit cards—ideal for teams in Asia-Pacific regions.
- Low Latency: Sub-50ms response times meet the requirements for strategy iteration cycles where speed directly impacts development velocity.
- Free Credits: New registrations receive complimentary credits for initial testing—zero financial commitment to evaluate the service.
Common Errors and Fixes
Error 1: Tardis API Rate Limiting (HTTP 429)
# Problem: Exceeded Tardis API rate limits
Solution: Implement exponential backoff and request queuing
import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_resilient_session():
"""Create session with automatic retry logic."""
session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
Usage in TardisDataClient
class TardisDataClient:
def __init__(self, api_key: str):
self.api_key = api_key
self.session = create_resilient_session() # Resilient session
def get_historical_trades(self, ...):
# Add rate limit headers
headers = {
"Authorization": f"Bearer {self.api_key}",
"X-RateLimit-Priority": "high" # Priority for paid plans
}
max_retries = 5
for attempt in range(max_retries):
response = self.session.get(url, headers=headers, timeout=120)
if response.status_code == 429:
# Check Retry-After header
retry_after = int(response.headers.get('Retry-After', 60))
print(f"Rate limited. Waiting {retry_after}s...")
time.sleep(retry_after)
continue
response.raise_for_status()
return response.json()
raise Exception("Max retries exceeded for rate limiting")
Error 2: HolySheep API Invalid Authentication (HTTP 401)
# Problem: Invalid or expired HolySheep API key
Solution: Verify key format and regenerate if necessary
import os
def validate_holy_sheep_connection(api_key: str) -> bool:
"""Validate HolySheep API key before use."""
# Key format check: should be 32+ alphanumeric characters
if not api_key or len(api_key) < 32:
print("ERROR: API key appears invalid (too short)")
print("Get your key from: https://www.holysheep.ai/register")
return False
# Test connection with minimal request
test_url = "https://api.holysheep.ai/v1/models"
response = requests.get(
test_url,
headers={"Authorization": f"Bearer {api_key}"},
timeout=10
)
if response.status_code == 401:
print("ERROR: Invalid API key")
print("Please verify your key at https://www.holysheep.ai/dashboard")
return False
if response.status_code == 200:
models = response.json().get('data', [])
print(f"Connected! Available models: {[m['id'] for m in models[:5]]}")
return True
print(f"Unexpected response: {response.status_code}")
return False
Environment variable approach (recommended)
HOLY_SHEEP_KEY = os.environ.get('HOLYSHEEP_API_KEY', 'YOUR_HOLYSHEEP_API_KEY')
validate_holy_sheep_connection(HOLY_SHEEP_KEY)
Error 3: Backtrader Datafeed Timestamp Format Error
# Problem: "datetime must be convertible" error in Backtrader
Solution: Ensure proper datetime index and format
import pandas as pd
from datetime import datetime
def prepare_backtrader_data(trades_df: pd.DataFrame) -> pd.DataFrame:
"""
Properly format DataFrame for Backtrader compatibility.
Common issue: timestamp timezone or format mismatch.
"""
# Ensure timestamp column exists
if 'timestamp' not in trades_df.columns:
if 'date' in trades_df.columns:
trades_df['timestamp'] = pd.to_datetime(trades_df['date'])
else:
raise ValueError("No timestamp or date column found")
# Convert to UTC and remove timezone (Backtrader expects naive datetime)
trades_df['timestamp'] = pd.to_datetime(trades_df['timestamp'])
# If timezone-aware, convert to UTC and strip timezone
if trades_df['timestamp'].dt.tz is not None:
trades_df['timestamp'] = (
trades_df['timestamp']
.dt.tz_convert('UTC')
.dt.tz_localize(None)
)
# Set as index (required for PandasData feed)
trades_df.set_index('timestamp', inplace=True)
# Ensure OHLCV columns exist
required_cols = ['price', 'volume']
for col in required_cols:
if col not in trades