A Python library for algorithmic trading and financial analysis with AI/ML capabilities
Project description
MeridianAlgo - Enhanced Trading Library with AI/ML
A comprehensive Python library for algorithmic trading and financial analysis, now enhanced with advanced AI and machine learning capabilities.
🚀 New Features in v0.2.0
- ML Predictor: Advanced machine learning models for stock price prediction
- AI Analyzer: AI-powered market sentiment and regime analysis
- Ensemble Models: Multiple ML models working together for better accuracy
- GPU Support: Automatic detection and optimization for NVIDIA, AMD, Intel, and Apple GPUs
- Enhanced Technical Analysis: 17+ technical indicators with ML integration
📦 Installation
Basic Installation
pip install meridianalgo
With ML Support
pip install meridianalgo[ml]
Full Installation (with visualization)
pip install meridianalgo[ml,visualization]
🔧 Quick Start
Traditional Trading Features
from meridianalgo import TradingEngine, BacktestEngine, Indicators
# Initialize trading engine
engine = TradingEngine(paper_trading=True)
engine.connect()
# Place orders
order = engine.place_order("AAPL", "buy", 10, "market")
print(f"Order placed: {order}")
# Calculate technical indicators
prices = [100, 102, 101, 103, 105, 104, 106]
sma = Indicators.sma(prices, period=5)
rsi = Indicators.rsi(prices, period=14)
New ML Features
from meridianalgo import MLPredictor, AIAnalyzer, EnsembleModels
import yfinance as yf
# ML-based price prediction
predictor = MLPredictor()
# Simple prediction (no ML dependencies required)
result = predictor.predict_simple("AAPL", days=60, forecast_days=5)
print(f"Predictions: {result['predictions']}")
print(f"Confidence: {result['confidence']}%")
# Advanced ML prediction (requires PyTorch)
ml_result = predictor.predict_ml("AAPL", days=60, epochs=20)
print(f"ML Predictions: {ml_result['predictions']}")
# AI-powered market analysis
analyzer = AIAnalyzer()
data = yf.Ticker("AAPL").history(period="3mo")
analysis = analyzer.comprehensive_analysis(data, "AAPL")
print(f"Market Sentiment: {analysis['sentiment_analysis']['sentiment']}")
print(f"Market Regime: {analysis['market_regime']['regime']}")
print(f"Overall Score: {analysis['overall_score']}")
# Ensemble models for enhanced accuracy
ensemble = EnsembleModels()
data_with_indicators = predictor.calculate_technical_indicators(data)
X, y = ensemble.prepare_ensemble_data(data_with_indicators)
# Train ensemble
training_results = ensemble.train_ensemble(X, y, epochs=15, verbose=True)
print(f"Training completed: {training_results}")
# Make ensemble predictions
predictions = ensemble.predict_ensemble(X, forecast_days=5)
print(f"Ensemble predictions: {predictions['ensemble_predictions']}")
print(f"Confidence: {predictions['confidence']}%")
🧠 AI/ML Features
MLPredictor
- Simple Prediction: Statistical ensemble methods (no ML dependencies)
- Advanced ML: Neural networks with PyTorch
- Technical Indicators: 14+ indicators automatically calculated
- Multi-GPU Support: CUDA, MPS, DirectML, XPU
AIAnalyzer
- Market Sentiment: Bullish/bearish/neutral analysis
- Market Regime: Trending, ranging, volatile detection
- Support/Resistance: Automatic level identification
- Volume Analysis: Volume profile and patterns
- AI Insights: Optional integration with Gemini AI
EnsembleModels
- Multiple Models: Linear Regression, Random Forest, Neural Networks
- Automatic Weighting: Performance-based model combination
- Confidence Scoring: Prediction reliability assessment
- Hardware Optimization: GPU acceleration when available
📊 Traditional Features
TradingEngine
- Paper and live trading support
- Position management
- Order execution
- P&L calculation
BacktestEngine
- Strategy backtesting
- Performance metrics
- Equity curve analysis
- Trade history
Indicators
- 15+ technical indicators
- Moving averages (SMA, EMA)
- Oscillators (RSI, Stochastic, Williams %R)
- Trend indicators (MACD, Bollinger Bands)
- Volume indicators
TradeUtils
- Position sizing
- Risk management
- Performance calculations
- Trade validation
🖥️ Hardware Acceleration
Automatic detection and optimization for:
- NVIDIA GPUs: CUDA support
- AMD GPUs: ROCm (Linux) / DirectML (Windows)
- Intel Arc GPUs: XPU support
- Apple Silicon: MPS acceleration
- CPU: Multi-threaded fallback
📈 Example: Complete ML Trading Workflow
import yfinance as yf
from meridianalgo import MLPredictor, AIAnalyzer, BacktestEngine
# 1. Fetch data
symbol = "AAPL"
data = yf.Ticker(symbol).history(period="1y")
# 2. AI Analysis
analyzer = AIAnalyzer()
analysis = analyzer.comprehensive_analysis(data, symbol)
print(f"Market Analysis: {analysis['sentiment_analysis']['sentiment']}")
# 3. ML Prediction
predictor = MLPredictor()
predictions = predictor.predict_ml(symbol, days=90, epochs=25)
print(f"5-day forecast: {predictions['predictions']}")
# 4. Create trading strategy based on ML predictions
def ml_strategy(row, positions, capital, predictions_data):
# Simple strategy: buy if prediction is higher than current price
current_price = row['close']
if predictions_data and len(predictions_data) > 0:
predicted_price = predictions_data[0] # Next day prediction
if predicted_price > current_price * 1.02: # 2% threshold
return {'symbol': 'AAPL', 'action': 'buy', 'quantity': 10}
elif predicted_price < current_price * 0.98: # -2% threshold
return {'symbol': 'AAPL', 'action': 'sell', 'quantity': 10}
return None
# 5. Backtest the strategy
backtest = BacktestEngine(initial_capital=10000)
backtest.load_data(data.reset_index().rename(columns={
'Date': 'timestamp', 'Open': 'open', 'High': 'high',
'Low': 'low', 'Close': 'close', 'Volume': 'volume'
}))
results = backtest.run_backtest(ml_strategy, predictions_data=predictions['predictions'])
print(f"Backtest Results: {results}")
🔧 Configuration
Environment Variables
# Optional: Enable AI insights
export GEMINI_API_KEY="your_gemini_api_key"
GPU Setup
The library automatically detects available hardware. For optimal performance:
- NVIDIA: Install CUDA toolkit
- AMD: Install ROCm (Linux) or DirectML (Windows)
- Intel: Install Intel Extension for PyTorch
- Apple: macOS 12.3+ with Apple Silicon
📚 Documentation
🤝 Contributing
Contributions are welcome! Please read our Contributing Guide for details.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆕 What's New in v0.2.0
- Added ML-based price prediction with ensemble models
- Integrated AI-powered market analysis
- GPU acceleration support for major vendors
- Enhanced technical indicators with ML integration
- Comprehensive backtesting with ML strategies
- Optional AI insights via Gemini API
- Improved performance and reliability
🔮 Roadmap
- Deep learning models (LSTM, Transformer)
- Reinforcement learning for strategy optimization
- Real-time data streaming
- Advanced portfolio optimization
- Options and derivatives support
- Multi-asset backtesting
Made with ❤️ by MeridianAlgo
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file meridianalgo-0.2.0.tar.gz.
File metadata
- Download URL: meridianalgo-0.2.0.tar.gz
- Upload date:
- Size: 24.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9db509717302c063f488296fd4a85c778a7e3daad2b208077ab2529a30be4e8e
|
|
| MD5 |
39626a62fe5805a868c8b86f2535e8af
|
|
| BLAKE2b-256 |
02209ed43294e281bea5183f13587efae795fcc6cae1b1c712a6cde8c03c727f
|
File details
Details for the file meridianalgo-0.2.0-py3-none-any.whl.
File metadata
- Download URL: meridianalgo-0.2.0-py3-none-any.whl
- Upload date:
- Size: 24.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
03ddb72146b7a82f17fc41ad9e6abbc2b7e24b30b6b495d2c576c81d9b6f7de6
|
|
| MD5 |
0e2bcc209e18b54780835cde3ea0a6a5
|
|
| BLAKE2b-256 |
c2b19594848c9fc0e0541a3cc3463641ea80ea02c7e5d98373ec4d150037889b
|