Compute technical indicators and build trade strategies in a simple way
Project description
simple-trade
A Python library that allows you to compute technical indicators and build trade strategies in a simple way.
Features
- Data Fetching: Easily download historical stock data using
yfinance. - Technical Indicators: Compute a variety of technical indicators:
- Trend (e.g., Moving Averages, MACD, ADX)
- Momentum (e.g., RSI, Stochastics)
- Volatility (e.g., Bollinger Bands, ATR)
- Volume (e.g., On-Balance Volume)
- Trading Strategies: Implement custom trading strategies or select from premade trading strategies.
- Backtesting: Evaluate the performance of your trading strategies on historical data.
- Optimization: Optimize strategy parameters using techniques like grid search.
- Plotting: Visualize data, indicators, and backtest results using
matplotlib. - Combining: Combine different strategies to create a more complex strategies.
Installation
- Clone the repository:
git clone <repository_url> # Replace with your repo URL cd simple-trade
- Create and activate a virtual environment (recommended):
python -m venv myenv # On Windows myenv\Scripts\activate # On macOS/Linux source myenv/bin/activate
- Install the package and dependencies:
pip install .
Alternatively, installed with PyPI:pip install simple-trade
Dependencies
- Python >= 3.10
- yfinance
- pandas
- numpy
- joblib
- matplotlib
These will be installed automatically when you install simple-trade using pip.
Basic Usage
Calculate Indicators
Here's a quick example of how to download data and compute a technical indicator:
# Load Packages and Functions
from simple_trade import compute_indicator, download_data
from simple_trade import list_indicators
# Step 1: Download data
symbol = 'TSLA'
start = '2024-01-01'
end = '2025-01-01'
interval = '1d'
print(f"\nDownloading data for {symbol}...")
data = download_data(symbol, start, end, interval=interval)
# Step 2: Calculate indicator
parameters = dict()
columns = dict()
parameters["window"] = 14
data, columns, fig = compute_indicator(
data=data,
indicator='adx',
parameters=parameters
)
# Step 3: Display the plot
fig.show()
Plot of Results
To see a list of all indicators, use list_indicators() function.
Backtesting Strategies
Use the run_premade_trade function to select from premade strategies or create your custom strategies using run_cross_trade/run_band_trade functions.
# Example for backtesting a premade strategy
# Load Packages and Functions
from simple_trade import download_data
from simple_trade import run_premade_trade
from simple_trade import list_premade_strategies
from simple_trade import print_results
# Step 1: Download data
symbol = 'AAPL'
start_date = '2020-01-01'
end_date = '2022-12-31'
interval = '1d'
data = download_data(symbol, start_date, end_date, interval=interval)
# Step 2: Set Global Parameters
global_parameters = {
'initial_cash': 10000,
'commission_long': 0.001,
'commission_short': 0.001,
'short_borrow_fee_inc_rate': 0.0,
'long_borrow_fee_inc_rate': 0.0,
'trading_type': 'long',
'day1_position': 'none',
'risk_free_rate': 0.0,
}
# Step 3: Set Strategy Parameters
strategy_name = 'sma'
specific_parameters = {
'short_window': 25,
'long_window': 75,
'fig_control': 1,
}
# Step 4: Run Backtest
parameters = {**global_parameters, **specific_parameters}
results, portfolio, fig = run_premade_trade(data, strategy_name, parameters)
print_results(results)
Plot of Results
============================================================
🗓️ BACKTEST PERIOD: • Period: 2020-04-20 to 2022-12-30 • Duration: 984 days • Trading Periods: 682
📊 BASIC METRICS: • Initial Investment: $10,000.00 • Final Portfolio Value: $13,199.32 • Total Return: 31.99% • Annualized Return: 10.80% • Number of Trades: 16 • Total Commissions: $237.12
📈 BENCHMARK COMPARISON: • Benchmark Return: 87.48% • Benchmark Final Value: $18,748.45 • Strategy vs Benchmark: -55.49%
📉 RISK METRICS: • Sharpe Ratio: 0.530 • Sortino Ratio: 0.500 • Maximum Drawdown: -32.50% • Average Drawdown: -14.25% • Max Drawdown Duration: 360 days • Avg Drawdown Duration: 43.43 days • Annualized Volatility: 25.89%
============================================================
To see a list of all premade strategies, use list_premade_strategies() function.
Optimizing Strategies
Use the premade_optimizer function to find the best parameters for your premade strategies or optimize your custom strategies using custom_optimizer function.
# Example for optimizing a premade strategy
# Load Packages and Functions
from simple_trade import download_data
from simple_trade import premade_optimizer
# Step 1: Load Data
ticker = "AAPL"
start_date = "2020-01-01"
end_date = "2023-12-31"
data = download_data(ticker, start_date, end_date)
# Step 2: Load Optimization Parameters
# Define the parameter grid to search
param_grid = {
'short_window': [10, 20, 30],
'long_window': [50, 100, 150],
}
# Step 3: Set Base Parameters
base_params = {
'initial_cash': 100000.0,
'commission_long': 0.001, # 0.1% commission
'commission_short': 0.001,
'trading_type': 'long', # Only long trades
'day1_position': 'none',
'risk_free_rate': 0.02,
'metric': 'total_return_pct', # Metric to optimize
'maximize': True, # Maximize the metric
'parallel': False, # Sequential execution for this example
'fig_control': 0 # No plotting during optimization
}
# Step 4: Run Optimization
best_results, best_params, all_results = premade_optimizer(
data=data,
strategy_name='sma',
parameters=base_params,
param_grid=param_grid
)
# Show top 3 parameter combinations
print("\nTop 3 SMA Parameter Combinations:")
sorted_results = sorted(all_results, key=lambda x: x['score'], reverse=True)
for i, result in enumerate(sorted_results[:3]):
print(f" {i+1}. {result['params']} -> {result['score']:.2f}%")
Output of Results
Top 3 SMA Parameter Combinations:
1. {'short_window': 10, 'long_window': 50} -> 99.87%
2. {'short_window': 20, 'long_window': 50} -> 85.69%
3. {'short_window': 30, 'long_window': 50} -> 67.08%
Combining Strategies
Use the run_combined_trade function to combine multiple strategies.
# Example for combining premade strategies
# Load Packages and Functions
from simple_trade import download_data
from simple_trade import run_premade_trade
from simple_trade import run_combined_trade
# Step 1: Download data
print("Downloading stock data...")
symbol = 'AAPL'
start_date = '2020-01-01'
end_date = '2022-12-31'
interval = '1d'
data = download_data(symbol, start_date, end_date, interval=interval)
# Step 2: Set Global Parameters
global_parameters = {
'initial_cash': 10000,
'commission_long': 0.001,
'commission_short': 0.001,
'short_borrow_fee_inc_rate': 0.0,
'long_borrow_fee_inc_rate': 0.0,
'trading_type': 'long',
'day1_position': 'none',
'risk_free_rate': 0.0,
}
# Step 3: Compute RSI Strategy
rsi_params = {
'window': 14,
'upper': 70,
'lower': 30,
'fig_control': 0
}
rsi_params = {**global_parameters, **rsi_params}
rsi_results, rsi_portfolio, _ = run_premade_trade(data, "rsi", rsi_params)
# Step 3: Compute SMA Strategy
sma_params = {
'short_window': 20,
'long_window': 50,
'fig_control': 0
}
sma_params = {**global_parameters, **sma_params}
sma_results, sma_portfolio, _ = run_premade_trade(data, "sma", sma_params)
# Step 4: Combine RSI and SMA Strategies
strategies = {
'RSI': {'results': rsi_results, 'portfolio': rsi_portfolio},
'SMA': {'results': sma_results, 'portfolio': sma_portfolio}
}
combined_results, combined_portfolio, _ = run_combined_trade(
portfolio_dfs=[rsi_portfolio, sma_portfolio],
price_data=data,
price_col='Close',
combination_logic='majority',
trading_type='long',
fig_control=0,
strategies=strategies,
strategy_name='Majority',
initial_cash=200,
commission_long=0.001,
commission_short=0.001
)
print(f"2 Trading Strategy Combination - Final Value: ${combined_results['final_value']:.2f}")
print(f"2 Trading Strategy Combination - Total Return: {combined_results['total_return_pct']}%")
print(f"2 Trading Strategy Combination - Number of Trades: {combined_results['num_trades']}")
print(f"2 Trading Strategy Combination - Sharpe Ratio: {combined_results['sharpe_ratio']:.3f}")
Output of Results
2 Trading Strategy Combination - Final Value: $318.11
2 Trading Strategy Combination - Total Return: 59.16%
2 Trading Strategy Combination - Number of Trades: 13
2 Trading Strategy Combination - Sharpe Ratio: 0.780
Examples
For more detailed examples, please refer to the Jupyter notebooks in the /examples directory:
/examples/indicators: Demonstrations of various technical indicators./examples/backtest: Examples of backtesting different strategies./examples/optimize: Examples of optimizing strategy parameters./examples/combine_trade: Examples of combining different strategies./examples/lists: Examples of listing functions.
Contributing
Contributions are welcome! Please feel free to submit a pull request or open an issue. (Further details can be added here if needed).
License
This project is licensed under the AGPL-3.0 License - see the LICENSE file for details.
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 simple_trade-0.3.0.tar.gz.
File metadata
- Download URL: simple_trade-0.3.0.tar.gz
- Upload date:
- Size: 218.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3f7147e3836f8f6d8c6e8b3b5a6e1d762fe8b962c4e69f930a0a95642d544b67
|
|
| MD5 |
4ce9ffa1ff69b0e5b68d41483c402077
|
|
| BLAKE2b-256 |
af4907b33676b5fa5ef97fd47fe1b67809c3573ceab3875a7f5154caa98fe583
|
File details
Details for the file simple_trade-0.3.0-py3-none-any.whl.
File metadata
- Download URL: simple_trade-0.3.0-py3-none-any.whl
- Upload date:
- Size: 306.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
df25ecf091ef1d4246a86b633a13c1dbfe5cfffc0fd9d40709f4e0a3e63760b3
|
|
| MD5 |
005f6bd8a14d09e75c11008e9834e970
|
|
| BLAKE2b-256 |
fcb239965480588ae441ffa164bf1c054fa0a0e7ac7764163316befe6945e604
|