This is a great architectural question that depends on several factors. Let me break down the trade-offs to help you make the best decision for your use case.
Recommendation: Hybrid Approach with Caching Strategy
For most trading applications, I'd recommend a hybrid approach that combines both strategies based on data usage patterns and performance requirements.
Analysis of Each Approach
Storing in Azure Tables
Pros:
- Faster query performance for frequently accessed data
- Reduced API costs over time (Alpaca has rate limits)
- Offline capability - backtests can run without internet dependency
- Consistent performance - no network latency or API downtime issues
- Complex queries - can join data, aggregate across timeframes more easily
- Historical preservation - protects against data provider changes or outages
Cons:
- Storage costs accumulate over time (though Azure Tables are relatively cheap)
- Data synchronization complexity - need to keep data fresh and handle updates
- Initial setup overhead - ETL processes, data validation, schema management
- Potential data staleness if sync processes fail
Real-time API Requests
Pros:
- Always current data - no sync issues or stale data
- No storage costs for historical data
- Simpler architecture initially - no ETL pipelines to maintain
- Automatic data corrections - if provider fixes historical data, you get it automatically
Cons:
- API rate limits can bottleneck backtests (Alpaca: 200 requests/minute)
- Network dependency - backtests fail if API is down
- Slower performance for large backtests
- Cumulative API costs for repeated data requests
- Limited offline capability
Recommended Hybrid Strategy
Here's a practical approach that balances performance, cost, and complexity:
Tier 1: Cache Frequently Used Data
Store in Azure Tables:
- Popular stocks (S&P 500, user watchlists, frequently traded symbols)
- Recent data (last 2-5 years of daily/hourly data)
- Preprocessed data (technical indicators, adjusted prices)
Tier 2: On-Demand for Everything Else
Request via API:
- Obscure symbols rarely used in backtests
- Very old historical data (>5 years) unless specifically needed
- Intraday data for one-off analyses
Implementation Strategy
class DataManager:
def __init__(self):
self.cache_threshold_days = 30 # Cache data older than 30 days
self.popular_symbols = self.load_popular_symbols()
async def get_historical_data(self, symbol, start_date, end_date, timeframe):
# Check if symbol is in cache and data is available
cached_data = await self.get_from_cache(symbol, start_date, end_date, timeframe)
if self.is_cache_sufficient(cached_data, start_date, end_date):
return cached_data
# Fetch missing data from API
missing_ranges = self.identify_missing_ranges(cached_data, start_date, end_date)
api_data = await self.fetch_from_alpaca(symbol, missing_ranges, timeframe)
# Update cache with new data
await self.update_cache(symbol, api_data, timeframe)
# Combine and return complete dataset
return self.merge_data(cached_data, api_data)
Specific Recommendations for Your Use Case
For Backtesting:
- Cache daily/hourly data for your core universe of stocks
- Use API for intraday tick data or very specific date ranges
- Precompute common indicators (moving averages, RSI, etc.) and store them
For Live Trading:
- Always use real-time API for current prices and order execution
- Cache reference data (company info, sector classifications) that changes infrequently
Data Refresh Strategy:
- Daily batch job to update cached data after market close
- Incremental updates - only fetch new bars since last update
- Data validation - compare API data with cached data periodically
Cost Considerations
Azure Tables Storage Costs (rough estimates):
- 1 year of daily data for S&P 500: ~$2-5/month
- 5 years of hourly data for 100 stocks: ~$10-20/month
Alpaca API Considerations:
- Rate limits: 200 requests/minute for market data
- Data allowances: Check your plan's historical data limits
- Repeated requests: Costs add up for frequently run backtests
Implementation Priority
- Start simple: Begin with API-only approach to get your backtesting working
- Identify bottlenecks: Monitor which data requests are repeated most often
- Implement selective caching: Cache only the data that provides clear performance/cost benefits
- Scale gradually: Expand caching as your user base and data needs grow
Code Example for Hybrid Approach
class HybridDataProvider:
def __init__(self, alpaca_client, azure_table_client):
self.alpaca = alpaca_client
self.cache = azure_table_client
self.cache_policy = {
'daily': 90, # Cache daily data older than 90 days
'hourly': 30, # Cache hourly data older than 30 days
'minute': 7 # Cache minute data older than 7 days
}
async def get_bars(self, symbol, timeframe, start, end):
cache_cutoff = datetime.now() - timedelta(days=self.cache_policy[timeframe])
if end < cache_cutoff:
# All requested data should be cached
return await self.get_from_cache(symbol, timeframe, start, end)
elif start < cache_cutoff:
# Hybrid: some cached, some from API
cached_data = await self.get_from_cache(symbol, timeframe, start, cache_cutoff)
live_data = await self.alpaca.get_bars(symbol, timeframe, cache_cutoff, end)
return self.combine_data(cached_data, live_data)
else:
# All recent data, get from API
return await self.alpaca.get_bars(symbol, timeframe, start, end)
This hybrid approach gives you the best of both worlds: fast performance for common use cases while maintaining flexibility and data freshness where needed.