# 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)
```bash
pip install meridianalgo
```
### From Source
```bash
git clone https://github.com/MeridianAlgo/Packages.git
cd meridianalgo
pip install -e .
```
## Quick Start
### Basic Usage
```python
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
```python
# 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
```python
# 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
```python
# 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, see the [GitHub README](https://github.com/MeridianAlgo/Packages#readme).
## API Reference
### TradingEngine
Main class for live trading operations.
```python
engine = TradingEngine(api_key="your_api_key", paper_trading=True)
```
**Methods:**
- `connect()`: Connect to trading platform
- `get_account_info()`: Get account information
- `place_order()`: Place a trading order
- `get_positions()`: Get current positions
- `get_trade_history()`: Get trade history
- `calculate_pnl()`: Calculate profit/loss
### BacktestEngine
Class for backtesting trading strategies.
```python
backtest = BacktestEngine(initial_capital=10000)
```
**Methods:**
- `load_data()`: Load historical data
- `run_backtest()`: Run backtest with strategy
- `get_equity_curve()`: Get equity curve data
- `get_trades()`: Get trade data
### Indicators
Static methods for technical analysis indicators.
**Available Indicators:**
- `sma()`: Simple Moving Average
- `ema()`: Exponential Moving Average
- `rsi()`: Relative Strength Index
- `macd()`: MACD
- `bollinger_bands()`: Bollinger Bands
- `stochastic()`: Stochastic Oscillator
- `atr()`: Average True Range
- `williams_r()`: Williams %R
- `cci()`: Commodity Channel Index
### TradeUtils
Utility functions for trading operations.
**Available Functions:**
- `calculate_position_size()`: Calculate position size based on risk
- `calculate_risk_reward_ratio()`: Calculate risk-reward ratio
- `calculate_pnl()`: Calculate profit/loss
- `calculate_sharpe_ratio()`: Calculate Sharpe ratio
- `calculate_max_drawdown()`: Calculate maximum drawdown
- `calculate_win_rate()`: Calculate win rate
- `format_currency()`: Format currency amounts
- `validate_trade_params()`: Validate trade parameters
## Examples
See the `examples/` directory for more detailed examples:
- `simple_strategy.py`: Basic moving average strategy
- `rsi_strategy.py`: RSI-based trading strategy
- `risk_management.py`: Risk management examples
- `performance_analysis.py`: Performance analysis examples
## Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## Testing
Run the test suite:
```bash
pytest tests/
```
Run with coverage:
```bash
pytest --cov=meridianalgo tests/
```
## License
This project is licensed under the MIT License - see the [LICENSE](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/](https://meridianalgo.readthedocs.io/)
- Issues: [https://github.com/MeridianAlgo/Packages/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
Raw data
{
"_id": null,
"home_page": "https://github.com/MeridianAlgo/Packages",
"name": "meridianalgo",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "trading, algorithmic, finance, backtesting, technical analysis",
"author": "Your Name",
"author_email": "meridianalgo@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/95/4d/6b6454a464f2c9c6469be7c6e58d81a4a922c99ee67ee54a576d1100e9b2/meridianalgo-0.1.3.tar.gz",
"platform": null,
"description": "# MeridianAlgo\r\n\r\nA comprehensive Python library for algorithmic trading and financial analysis. MeridianAlgo provides tools for backtesting trading strategies, calculating technical indicators, and managing trading operations.\r\n\r\n## Features\r\n\r\n- **Trading Engine**: Live trading operations and position management\r\n- **Backtest Engine**: Historical strategy testing with performance metrics\r\n- **Technical Indicators**: Comprehensive collection of technical analysis indicators\r\n- **Utility Functions**: Risk management and performance calculation tools\r\n\r\n## Installation\r\n\r\n### From PyPI (when published)\r\n```bash\r\npip install meridianalgo\r\n```\r\n\r\n### From Source\r\n```bash\r\ngit clone https://github.com/MeridianAlgo/Packages.git\r\ncd meridianalgo\r\npip install -e .\r\n```\r\n\r\n## Quick Start\r\n\r\n### Basic Usage\r\n\r\n```python\r\nimport pandas as pd\r\nfrom meridianalgo import TradingEngine, BacktestEngine, Indicators, TradeUtils\r\n\r\n# Initialize trading engine\r\nengine = TradingEngine(paper_trading=True)\r\nengine.connect()\r\n\r\n# Get account information\r\naccount_info = engine.get_account_info()\r\nprint(f\"Account Balance: {account_info['balance']}\")\r\n\r\n# Place a trade\r\norder = engine.place_order(\r\n symbol=\"BTC/USD\",\r\n side=\"buy\",\r\n quantity=0.1,\r\n order_type=\"market\"\r\n)\r\nprint(f\"Order placed: {order}\")\r\n```\r\n\r\n### Backtesting a Strategy\r\n\r\n```python\r\n# Load historical data\r\ndata = pd.read_csv('historical_data.csv')\r\ndata['timestamp'] = pd.to_datetime(data['timestamp'])\r\n\r\n# Initialize backtest engine\r\nbacktest = BacktestEngine(initial_capital=10000)\r\n\r\n# Load data\r\nbacktest.load_data(data)\r\n\r\n# Define a simple moving average crossover strategy\r\ndef ma_crossover_strategy(row, positions, capital, fast_period=10, slow_period=20):\r\n \"\"\"Simple moving average crossover strategy\"\"\"\r\n if len(backtest.data) < slow_period:\r\n return None\r\n \r\n # Calculate moving averages\r\n fast_ma = backtest.data['close'].rolling(fast_period).mean().iloc[-1]\r\n slow_ma = backtest.data['close'].rolling(slow_period).mean().iloc[-1]\r\n \r\n current_price = row['close']\r\n \r\n # Buy signal: fast MA crosses above slow MA\r\n if fast_ma > slow_ma and 'BTC/USD' not in positions:\r\n quantity = capital * 0.1 / current_price # Use 10% of capital\r\n return {\r\n 'symbol': 'BTC/USD',\r\n 'action': 'buy',\r\n 'quantity': quantity\r\n }\r\n \r\n # Sell signal: fast MA crosses below slow MA\r\n elif fast_ma < slow_ma and 'BTC/USD' in positions:\r\n return {\r\n 'symbol': 'BTC/USD',\r\n 'action': 'sell',\r\n 'quantity': positions['BTC/USD']['quantity']\r\n }\r\n \r\n return None\r\n\r\n# Run backtest\r\nresults = backtest.run_backtest(ma_crossover_strategy)\r\nprint(f\"Total Return: {results['total_return']:.2%}\")\r\nprint(f\"Sharpe Ratio: {results['sharpe_ratio']:.2f}\")\r\nprint(f\"Max Drawdown: {results['max_drawdown']:.2%}\")\r\n```\r\n\r\n### Using Technical Indicators\r\n\r\n```python\r\n# Calculate RSI\r\nrsi = Indicators.rsi(data['close'], period=14)\r\n\r\n# Calculate MACD\r\nmacd_line, signal_line, histogram = Indicators.macd(data['close'])\r\n\r\n# Calculate Bollinger Bands\r\nupper_band, middle_band, lower_band = Indicators.bollinger_bands(data['close'])\r\n\r\n# Calculate Stochastic Oscillator\r\nk_percent, d_percent = Indicators.stochastic(\r\n data['high'], \r\n data['low'], \r\n data['close']\r\n)\r\n```\r\n\r\n### Risk Management\r\n\r\n```python\r\n# Calculate position size based on risk\r\nposition_size = TradeUtils.calculate_position_size(\r\n capital=10000,\r\n risk_percent=2, # Risk 2% of capital\r\n entry_price=50000,\r\n stop_loss=48000\r\n)\r\n\r\n# Calculate risk-reward ratio\r\nrr_ratio = TradeUtils.calculate_risk_reward_ratio(\r\n entry_price=50000,\r\n target_price=55000,\r\n stop_loss=48000\r\n)\r\n\r\n# Calculate P&L\r\npnl = TradeUtils.calculate_pnl(\r\n entry_price=50000,\r\n exit_price=52000,\r\n quantity=0.1,\r\n side=\"long\"\r\n)\r\n```\r\n\r\n## Documentation\r\n\r\nFor detailed documentation, see the [GitHub README](https://github.com/MeridianAlgo/Packages#readme).\r\n\r\n## API Reference\r\n\r\n### TradingEngine\r\n\r\nMain class for live trading operations.\r\n\r\n```python\r\nengine = TradingEngine(api_key=\"your_api_key\", paper_trading=True)\r\n```\r\n\r\n**Methods:**\r\n- `connect()`: Connect to trading platform\r\n- `get_account_info()`: Get account information\r\n- `place_order()`: Place a trading order\r\n- `get_positions()`: Get current positions\r\n- `get_trade_history()`: Get trade history\r\n- `calculate_pnl()`: Calculate profit/loss\r\n\r\n### BacktestEngine\r\n\r\nClass for backtesting trading strategies.\r\n\r\n```python\r\nbacktest = BacktestEngine(initial_capital=10000)\r\n```\r\n\r\n**Methods:**\r\n- `load_data()`: Load historical data\r\n- `run_backtest()`: Run backtest with strategy\r\n- `get_equity_curve()`: Get equity curve data\r\n- `get_trades()`: Get trade data\r\n\r\n### Indicators\r\n\r\nStatic methods for technical analysis indicators.\r\n\r\n**Available Indicators:**\r\n- `sma()`: Simple Moving Average\r\n- `ema()`: Exponential Moving Average\r\n- `rsi()`: Relative Strength Index\r\n- `macd()`: MACD\r\n- `bollinger_bands()`: Bollinger Bands\r\n- `stochastic()`: Stochastic Oscillator\r\n- `atr()`: Average True Range\r\n- `williams_r()`: Williams %R\r\n- `cci()`: Commodity Channel Index\r\n\r\n### TradeUtils\r\n\r\nUtility functions for trading operations.\r\n\r\n**Available Functions:**\r\n- `calculate_position_size()`: Calculate position size based on risk\r\n- `calculate_risk_reward_ratio()`: Calculate risk-reward ratio\r\n- `calculate_pnl()`: Calculate profit/loss\r\n- `calculate_sharpe_ratio()`: Calculate Sharpe ratio\r\n- `calculate_max_drawdown()`: Calculate maximum drawdown\r\n- `calculate_win_rate()`: Calculate win rate\r\n- `format_currency()`: Format currency amounts\r\n- `validate_trade_params()`: Validate trade parameters\r\n\r\n## Examples\r\n\r\nSee the `examples/` directory for more detailed examples:\r\n\r\n- `simple_strategy.py`: Basic moving average strategy\r\n- `rsi_strategy.py`: RSI-based trading strategy\r\n- `risk_management.py`: Risk management examples\r\n- `performance_analysis.py`: Performance analysis examples\r\n\r\n## Contributing\r\n\r\n1. Fork the repository\r\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\r\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\r\n4. Push to the branch (`git push origin feature/amazing-feature`)\r\n5. Open a Pull Request\r\n\r\n## Testing\r\n\r\nRun the test suite:\r\n\r\n```bash\r\npytest tests/\r\n```\r\n\r\nRun with coverage:\r\n\r\n```bash\r\npytest --cov=meridianalgo tests/\r\n```\r\n\r\n## License\r\n\r\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\r\n\r\n## Disclaimer\r\n\r\nThis 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.\r\n\r\n## Support\r\n\r\n- Documentation: [https://meridianalgo.readthedocs.io/](https://meridianalgo.readthedocs.io/)\r\n- Issues: [https://github.com/MeridianAlgo/Packages/issues](https://github.com/MeridianAlgo/Packages/issues)\r\n- Email: meridianalgo@gmail.com\r\n\r\n## Changelog\r\n\r\n### Version 0.1.0\r\n- Initial release\r\n- Basic trading engine functionality\r\n- Backtesting engine with performance metrics\r\n- Technical indicators collection\r\n- Utility functions for risk management \r\n",
"bugtrack_url": null,
"license": null,
"summary": "A Python library for algorithmic trading and financial analysis",
"version": "0.1.3",
"project_urls": {
"Bug Reports": "https://github.com/MeridianAlgo/Packages/issues",
"Documentation": "https://github.com/MeridianAlgo/Packages#readme",
"Homepage": "https://github.com/MeridianAlgo/Packages",
"Source": "https://github.com/MeridianAlgo/Packages"
},
"split_keywords": [
"trading",
" algorithmic",
" finance",
" backtesting",
" technical analysis"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "7c52c51a2f0fc021636aa8cd855bd5d610fb8bafffbf24e4e701be6275a46313",
"md5": "a9a8727a81dbe79a92cdb421e4a51c66",
"sha256": "781b167e60b462ce49b214542dddf850959df7d928069281da41dc24c064d55c"
},
"downloads": -1,
"filename": "meridianalgo-0.1.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "a9a8727a81dbe79a92cdb421e4a51c66",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 12704,
"upload_time": "2025-07-14T01:43:56",
"upload_time_iso_8601": "2025-07-14T01:43:56.307904Z",
"url": "https://files.pythonhosted.org/packages/7c/52/c51a2f0fc021636aa8cd855bd5d610fb8bafffbf24e4e701be6275a46313/meridianalgo-0.1.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "954d6b6454a464f2c9c6469be7c6e58d81a4a922c99ee67ee54a576d1100e9b2",
"md5": "a466434ff5594bdf2285b7ec06b5fd3e",
"sha256": "49cd67f5ab7cdf9833e0fc6027138fbb1c3690f391a9ce3363b357ddad644f1d"
},
"downloads": -1,
"filename": "meridianalgo-0.1.3.tar.gz",
"has_sig": false,
"md5_digest": "a466434ff5594bdf2285b7ec06b5fd3e",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 21962,
"upload_time": "2025-07-14T01:43:57",
"upload_time_iso_8601": "2025-07-14T01:43:57.514703Z",
"url": "https://files.pythonhosted.org/packages/95/4d/6b6454a464f2c9c6469be7c6e58d81a4a922c99ee67ee54a576d1100e9b2/meridianalgo-0.1.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-07-14 01:43:57",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "MeridianAlgo",
"github_project": "Packages",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "pandas",
"specs": [
[
">=",
"1.3.0"
]
]
},
{
"name": "numpy",
"specs": [
[
">=",
"1.21.0"
]
]
},
{
"name": "matplotlib",
"specs": [
[
">=",
"3.4.0"
]
]
},
{
"name": "seaborn",
"specs": [
[
">=",
"0.11.0"
]
]
},
{
"name": "requests",
"specs": [
[
">=",
"2.25.0"
]
]
},
{
"name": "python-dateutil",
"specs": [
[
">=",
"2.8.0"
]
]
}
],
"lcname": "meridianalgo"
}