This document provides comprehensive troubleshooting information for common issues encountered when using AmpyFin.
Before diving into specific issues, run through this checklist:
- Are all environment variables set correctly?
- Is MongoDB running and accessible?
- Are API keys valid and have proper permissions?
- Is TA-Lib properly installed?
- Are all Python dependencies installed?
- Is the system running during market hours (for live trading)?
Problem: Microsoft Visual C++ 14.0 is required error
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools"Solution:
- Download pre-built wheel from cgohlke/talib-build
- Install the appropriate wheel for your Python version:
pip install TA_Lib-0.4.24-cp39-cp39-win_amd64.whlAlternative Solution:
- Install Visual Studio Build Tools
- Install TA-Lib from source:
pip install TA-LibProblem: clang: error: unsupported option '-fopenmp'
clang: error: unsupported option '-fopenmp'Solution:
- Install TA-Lib using Homebrew:
brew install ta-lib
pip install TA-Lib- If using conda:
conda install -c conda-forge ta-libProblem: fatal error: ta-lib/ta_defs.h: No such file or directory
fatal error: ta-lib/ta_defs.h: No such file or directorySolution:
- Install TA-Lib development libraries:
# Ubuntu/Debian
sudo apt-get install libta-lib-dev
# CentOS/RHEL
sudo yum install ta-lib-devel
# Then install Python package
pip install TA-LibERROR: pip's dependency resolver does not currently take into account all the packages that are installedSolution:
- Create a virtual environment:
python -m venv ampyfin_env
source ampyfin_env/bin/activate # Linux/Mac
# or
ampyfin_env\Scripts\activate # Windows- Install dependencies:
pip install -r requirements.txtERROR: Could not find a version that satisfies the requirementSolution:
- Update pip:
pip install --upgrade pip- Install specific versions:
pip install pandas==1.5.3 numpy==1.24.3[error]: Missing required environment variables: API_KEY, API_SECRETSolution:
- Create
.envfile in project root:
API_KEY=your_alpaca_api_key
API_SECRET=your_alpaca_secret_key
BASE_URL=https://paper-api.alpaca.markets
WANDB_API_KEY=your_wandb_api_key
MONGO_URL=your_mongodb_connection_string- Verify variables are loaded:
from config import API_KEY, API_SECRET
print(f"API_KEY loaded: {bool(API_KEY)}")alpaca.common.exceptions.APIError: 401 UnauthorizedSolution:
- Verify API keys in Alpaca dashboard
- Check key permissions (trading enabled)
- Ensure using correct environment (paper vs live)
- Test API connection:
from alpaca.trading.client import TradingClient
from config import API_KEY, API_SECRET, BASE_URL
try:
client = TradingClient(API_KEY, API_SECRET, paper=True)
account = client.get_account()
print("API connection successful")
except Exception as e:
print(f"API connection failed: {e}")pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 61] Connection refusedSolution:
- Local MongoDB:
# Start MongoDB service
sudo systemctl start mongod # Linux
brew services start mongodb-community # macOS
net start MongoDB # Windows-
MongoDB Atlas:
- Check connection string format
- Verify IP whitelist
- Check username/password
-
Test connection:
from pymongo import MongoClient
from config import MONGO_URL
try:
client = MongoClient(MONGO_URL)
client.admin.command('ping')
print("MongoDB connection successful")
except Exception as e:
print(f"MongoDB connection failed: {e}")pymongo.errors.OperationFailure: Authentication failedSolution:
- Verify username and password
- Check database permissions
- Ensure user has read/write access
- Test with MongoDB Compass or mongo shell
No buy/sell signals generated for any tickerDebugging Steps:
- Check if market is open:
from utilities.ranking_trading_utils import market_status
print(f"Market status: {market_status()}")- Verify data availability:
from strategies.talib_indicators import get_data
data = get_data("AAPL", mongo_client, period="1mo")
print(f"Data shape: {data.shape}")
print(f"Latest data: {data.tail()}")- Test individual strategies:
from strategies.talib_indicators import RSI_indicator
signal = RSI_indicator("AAPL", data)
print(f"RSI signal: {signal}")ValueError: Input contains NaN, infinity or a value too large for dtype('float64')Solution:
- Check data quality:
import pandas as pd
print(f"NaN values: {data.isnull().sum()}")
print(f"Infinite values: {np.isinf(data).sum()}")- Clean data:
# Remove NaN values
data = data.dropna()
# Replace infinite values
data = data.replace([np.inf, -np.inf], np.nan).dropna()- Add data validation to strategies:
def safe_strategy(data):
if data.isnull().any().any():
return "Hold"
if np.isinf(data).any().any():
return "Hold"
# Continue with strategy logicalpaca.common.exceptions.APIError: 422 Insufficient buying powerSolution:
- Check account balance:
account = trading_client.get_account()
print(f"Cash: ${float(account.cash)}")
print(f"Buying power: ${float(account.buying_power)}")- Adjust position sizes:
# Reduce trade size
max_investment = min(account_cash * 0.1, 1000) # 10% or $1000 max- Check margin requirements:
# Ensure sufficient margin
if account_cash < required_margin:
return "Hold" # Skip tradealpaca.common.exceptions.APIError: 422 Order rejectedSolution:
- Check order parameters:
# Validate order parameters
if quantity <= 0:
return None
if price <= 0:
return None- Check market hours:
from alpaca.trading.client import TradingClient
clock = trading_client.get_clock()
print(f"Market open: {clock.is_open}")- Use appropriate order types:
# Use market orders for immediate execution
order = trading_client.submit_order(
symbol=symbol,
qty=quantity,
side=side,
type="market", # Market order
time_in_force="day"
)No data available for ticker: XYZSolution:
- Check ticker validity:
import yfinance as yf
ticker = yf.Ticker("XYZ")
info = ticker.info
if not info:
print("Invalid ticker symbol")- Try alternative data sources:
# Use different period
data = stock.history(period="6mo") # Instead of "1y"
# Use different interval
data = stock.history(period="1y", interval="1d") # Daily instead of minute- Handle missing data gracefully:
def get_data_with_fallback(ticker, mongo_client):
try:
data = get_data(ticker, mongo_client)
if data.empty:
# Try yfinance directly
stock = yf.Ticker(ticker)
data = stock.history(period="1y")
return data
except Exception as e:
print(f"Failed to get data for {ticker}: {e}")
return NoneMongoDB and Alpaca positions are out of syncSolution:
- Use sync utility:
from utilities.alpaca_utils.sync_alpaca import sync_positions
sync_positions()- Manual sync:
# Get Alpaca positions
alpaca_positions = trading_client.get_all_positions()
# Update MongoDB
for position in alpaca_positions:
db.assets_quantities.update_one(
{"symbol": position.symbol},
{"$set": {"quantity": float(position.qty)}},
upsert=True
)MemoryError: Unable to allocate arraySolution:
- Monitor memory usage:
import psutil
import os
def get_memory_usage():
process = psutil.Process(os.getpid())
return process.memory_info().rss / 1024 / 1024 # MB
print(f"Memory usage: {get_memory_usage():.2f} MB")- Optimize data processing:
# Process data in chunks
chunk_size = 1000
for chunk in pd.read_csv('large_file.csv', chunksize=chunk_size):
process_chunk(chunk)- Clear unused variables:
import gc
# After processing large datasets
del large_dataframe
gc.collect()Strategy execution taking too longSolution:
- Use vectorized operations:
# Instead of loops
for i in range(len(data)):
if data.iloc[i]['close'] > data.iloc[i]['sma']:
signals[i] = 'Buy'
# Use vectorized operations
signals = np.where(data['close'] > data['sma'], 'Buy', 'Sell')- Cache frequently used data:
from functools import lru_cache
@lru_cache(maxsize=128)
def get_cached_data(ticker, period):
return get_data(ticker, mongo_client, period)- Parallel processing:
from concurrent.futures import ThreadPoolExecutor
def process_tickers_parallel(tickers):
with ThreadPoolExecutor(max_workers=4) as executor:
results = executor.map(process_ticker, tickers)
return list(results)No detailed error information availableSolution:
- Enable debug logging:
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)- Enable specific logger:
logging.getLogger('alpaca').setLevel(logging.DEBUG)
logging.getLogger('pymongo').setLevel(logging.DEBUG)- Use structured logging:
import structlog
logger = structlog.get_logger()
logger.info("Processing ticker", ticker="AAPL", signal="Buy")Unhandled exception causing system crashSolution:
- Add comprehensive error handling:
def safe_execute(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
logger.error(f"Error in {func.__name__}: {e}", exc_info=True)
return None- Use try-except blocks:
try:
result = risky_operation()
except SpecificException as e:
logger.error(f"Specific error: {e}")
handle_specific_error(e)
except Exception as e:
logger.error(f"Unexpected error: {e}")
handle_generic_error(e)System appears to be running but no trades executedSolution:
- Implement health checks:
def system_health_check():
checks = {
'mongodb': check_mongodb_connection(),
'alpaca': check_alpaca_connection(),
'data': check_data_availability(),
'strategies': check_strategy_execution()
}
for check, status in checks.items():
if not status:
logger.error(f"Health check failed: {check}")
return all(checks.values())- Monitor key metrics:
def monitor_system_metrics():
metrics = {
'cpu_usage': psutil.cpu_percent(),
'memory_usage': psutil.virtual_memory().percent,
'disk_usage': psutil.disk_usage('/').percent,
'api_calls': get_api_call_count(),
'trades_executed': get_trade_count()
}
logger.info("System metrics", **metrics)
return metricsSystem issues not being reportedSolution:
- Set up alerts:
def send_alert(message, level="ERROR"):
if level == "ERROR":
# Send email/SMS notification
send_notification(message)
# Log to file
logger.error(message)
# Send to monitoring service
send_to_monitoring_service(message)- Implement circuit breakers:
class CircuitBreaker:
def __init__(self, failure_threshold=5, timeout=60):
self.failure_threshold = failure_threshold
self.timeout = timeout
self.failure_count = 0
self.last_failure_time = None
self.state = "CLOSED" # CLOSED, OPEN, HALF_OPEN
def call(self, func, *args, **kwargs):
if self.state == "OPEN":
if time.time() - self.last_failure_time > self.timeout:
self.state = "HALF_OPEN"
else:
raise Exception("Circuit breaker is OPEN")
try:
result = func(*args, **kwargs)
self.on_success()
return result
except Exception as e:
self.on_failure()
raise eWhen reporting issues, include:
- Error messages: Complete error traceback
- Configuration: Relevant config parameters
- Log files: System and application logs
- Environment: OS, Python version, package versions
- Steps to reproduce: Detailed reproduction steps
# Python version
python --version
# Package versions
pip list
# System resources
top # Linux/Mac
tasklist # Windows
# Disk space
df -h # Linux/Mac
dir # Windows# MongoDB status
mongosh --eval "db.runCommand('ping')"
# MongoDB collections
mongosh --eval "db.getCollectionNames()"
# SQLite database info
sqlite3 dbs/databases/price_data.db ".schema"# Test API connectivity
curl -I https://paper-api.alpaca.markets/v2/account
# Test MongoDB connectivity
telnet your-mongodb-host 27017- GitHub Issues: Report bugs and feature requests
- Discussions: Ask questions and share experiences
- Documentation: Check existing documentation first
- Code Review: Review similar issues and solutions
Remember to always test solutions in a safe environment (paper trading) before applying to live trading systems.