A Python library for algorithmic trading and financial analysis
Project description
MeridianAlgo
A comprehensive Python library for algorithmic trading and financial analysis. MeridianAlgo provides tools for backtesting trading strategies, calculating technical indicators, and managing trading operations.
Features
- Trading Engine: Live trading operations and position management
- Backtest Engine: Historical strategy testing with performance metrics
- Technical Indicators: Comprehensive collection of technical analysis indicators
- Utility Functions: Risk management and performance calculation tools
Installation
From PyPI (when published)
pip install meridianalgo
From Source
git clone https://github.com/MeridianAlgo/Packages.git
cd meridianalgo
pip install -e .
Quick Start
Basic Usage
import pandas as pd
from meridianalgo import TradingEngine, BacktestEngine, Indicators, TradeUtils
# Initialize trading engine
engine = TradingEngine(paper_trading=True)
engine.connect()
# Get account information
account_info = engine.get_account_info()
print(f"Account Balance: {account_info['balance']}")
# Place a trade
order = engine.place_order(
symbol="BTC/USD",
side="buy",
quantity=0.1,
order_type="market"
)
print(f"Order placed: {order}")
Backtesting a Strategy
# Load historical data
data = pd.read_csv('historical_data.csv')
data['timestamp'] = pd.to_datetime(data['timestamp'])
# Initialize backtest engine
backtest = BacktestEngine(initial_capital=10000)
# Load data
backtest.load_data(data)
# Define a simple moving average crossover strategy
def ma_crossover_strategy(row, positions, capital, fast_period=10, slow_period=20):
"""Simple moving average crossover strategy"""
if len(backtest.data) < slow_period:
return None
# Calculate moving averages
fast_ma = backtest.data['close'].rolling(fast_period).mean().iloc[-1]
slow_ma = backtest.data['close'].rolling(slow_period).mean().iloc[-1]
current_price = row['close']
# Buy signal: fast MA crosses above slow MA
if fast_ma > slow_ma and 'BTC/USD' not in positions:
quantity = capital * 0.1 / current_price # Use 10% of capital
return {
'symbol': 'BTC/USD',
'action': 'buy',
'quantity': quantity
}
# Sell signal: fast MA crosses below slow MA
elif fast_ma < slow_ma and 'BTC/USD' in positions:
return {
'symbol': 'BTC/USD',
'action': 'sell',
'quantity': positions['BTC/USD']['quantity']
}
return None
# Run backtest
results = backtest.run_backtest(ma_crossover_strategy)
print(f"Total Return: {results['total_return']:.2%}")
print(f"Sharpe Ratio: {results['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {results['max_drawdown']:.2%}")
Using Technical Indicators
# Calculate RSI
rsi = Indicators.rsi(data['close'], period=14)
# Calculate MACD
macd_line, signal_line, histogram = Indicators.macd(data['close'])
# Calculate Bollinger Bands
upper_band, middle_band, lower_band = Indicators.bollinger_bands(data['close'])
# Calculate Stochastic Oscillator
k_percent, d_percent = Indicators.stochastic(
data['high'],
data['low'],
data['close']
)
Risk Management
# Calculate position size based on risk
position_size = TradeUtils.calculate_position_size(
capital=10000,
risk_percent=2, # Risk 2% of capital
entry_price=50000,
stop_loss=48000
)
# Calculate risk-reward ratio
rr_ratio = TradeUtils.calculate_risk_reward_ratio(
entry_price=50000,
target_price=55000,
stop_loss=48000
)
# Calculate P&L
pnl = TradeUtils.calculate_pnl(
entry_price=50000,
exit_price=52000,
quantity=0.1,
side="long"
)
Documentation
For detailed documentation, visit https://meridianalgo.readthedocs.io/
API Reference
TradingEngine
Main class for live trading operations.
engine = TradingEngine(api_key="your_api_key", paper_trading=True)
Methods:
connect(): Connect to trading platformget_account_info(): Get account informationplace_order(): Place a trading orderget_positions(): Get current positionsget_trade_history(): Get trade historycalculate_pnl(): Calculate profit/loss
BacktestEngine
Class for backtesting trading strategies.
backtest = BacktestEngine(initial_capital=10000)
Methods:
load_data(): Load historical datarun_backtest(): Run backtest with strategyget_equity_curve(): Get equity curve dataget_trades(): Get trade data
Indicators
Static methods for technical analysis indicators.
Available Indicators:
sma(): Simple Moving Averageema(): Exponential Moving Averagersi(): Relative Strength Indexmacd(): MACDbollinger_bands(): Bollinger Bandsstochastic(): Stochastic Oscillatoratr(): Average True Rangewilliams_r(): Williams %Rcci(): Commodity Channel Index
TradeUtils
Utility functions for trading operations.
Available Functions:
calculate_position_size(): Calculate position size based on riskcalculate_risk_reward_ratio(): Calculate risk-reward ratiocalculate_pnl(): Calculate profit/losscalculate_sharpe_ratio(): Calculate Sharpe ratiocalculate_max_drawdown(): Calculate maximum drawdowncalculate_win_rate(): Calculate win rateformat_currency(): Format currency amountsvalidate_trade_params(): Validate trade parameters
Examples
See the examples/ directory for more detailed examples:
simple_strategy.py: Basic moving average strategyrsi_strategy.py: RSI-based trading strategyrisk_management.py: Risk management examplesperformance_analysis.py: Performance analysis examples
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Testing
Run the test suite:
pytest tests/
Run with coverage:
pytest --cov=meridianalgo tests/
License
This project is licensed under the MIT License - see the LICENSE file for details.
Disclaimer
This library is for educational and research purposes only. Trading involves substantial risk of loss and is not suitable for all investors. Past performance does not guarantee future results.
Support
- Documentation: https://meridianalgo.readthedocs.io/
- Issues: https://github.com/MeridianAlgo/Packages/issues
- Email: meridianalgo@gmail.com
Changelog
Version 0.1.0
- Initial release
- Basic trading engine functionality
- Backtesting engine with performance metrics
- Technical indicators collection
- Utility functions for risk management
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.1.1.tar.gz.
File metadata
- Download URL: meridianalgo-0.1.1.tar.gz
- Upload date:
- Size: 23.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0f29b33b2f0c31b6f2b9d609f2cbbfcfe7dc79f8b61143dfb7896192d5d263f3
|
|
| MD5 |
367da2548bfd47510efa8d018e066283
|
|
| BLAKE2b-256 |
abd14c59d0f1ef4109901797ae18b658195624aab30a05c8028cae20070888cf
|
File details
Details for the file meridianalgo-0.1.1-py3-none-any.whl.
File metadata
- Download URL: meridianalgo-0.1.1-py3-none-any.whl
- Upload date:
- Size: 12.8 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 |
ea28ebf3a9b6bbcdae4c7e06828e86cc9f75b9842408f25ca837f08a88ffc9f2
|
|
| MD5 |
242897a7db40c175014524b4592b6b63
|
|
| BLAKE2b-256 |
e689b1da6686b6aac8d9c2959a60c45955a3a2729bb381389fd0ab00318a9a69
|