# simple-trade
[](https://www.gnu.org/licenses/agpl-3.0)
[](https://pypi.org/project/simple-trade/)
[](https://www.python.org/downloads/)
[](https://github.com/BSoybilgen/simple-trade/actions/workflows/tests.yml)
[](https://codecov.io/github/BSoybilgen/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 and backtest common trading strategies:
* Cross Trade Strategies (`cross_trade`)
* Band Trading Strategies (`band_trade`)
* **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 strategy.
## Installation
1. **Clone the repository:**
```bash
git clone <repository_url> # Replace with your repo URL
cd simple-trade
```
2. **Create and activate a virtual environment (recommended):**
```bash
python -m venv myenv
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate
```
3. **Install the package and dependencies:**
```bash
pip install .
```
Alternatively, installed with PyPI:
```bash
pip install simple-trade
```
## Dependencies
* Python >= 3.10
* [yfinance](https://pypi.org/project/yfinance/)
* [pandas](https://pandas.pydata.org/)
* [numpy](https://numpy.org/)
* [joblib](https://joblib.readthedocs.io/en/latest/)
* [matplotlib](https://matplotlib.org/)
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:
```python
# Load Packages and Functions
import pandas as pd
from simple_trade import compute_indicator, download_data
# 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**
<img src="https://i.imgur.com/JBpd0qo.png" alt="Figure 1" width="900" height="600">
### Backtesting Strategies
Use the `premade_backtesting` module to simulate strategies like moving average crossovers (`cross_trade`) or Bollinger Band breakouts (`band_trade`).
```python
# Load Packages and Functions
import pandas as pd
from simple_trade import download_data
from simple_trade import premade_backtest
from simple_trade import CrossTradeBacktester
# 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 = premade_backtest(data, strategy_name, parameters)
```
**Plot of Results**
<img src="https://i.imgur.com/4qxr0dp.png" alt="Figure 2" width="900" height="600">
### Optimizing Strategies
The `premade_optimizer` module allows you to find the best parameters for your strategy (e.g., optimal moving average windows).
```python
# Load Packages and Functions
from simple_trade import download_data
from simple_trade.premade_optimizer 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%
```
## 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.
## 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](LICENSE) file for details.
Raw data
{
"_id": null,
"home_page": null,
"name": "simple-trade",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "algo, algorithmic, backtest, backtesting, candlestick, chart, crypto, currency, equity, exchange, finance, financial, forex, fx, indicator, invest, investing, investment, ohlc, ohlcv, order, price, profit, quant, quantitative, simulation, stocks, strategy, ticker, trader, trading",
"author": "Baris Soybilgen",
"author_email": null,
"download_url": null,
"platform": null,
"description": "# simple-trade\r\n\r\n[](https://www.gnu.org/licenses/agpl-3.0)\r\n[](https://pypi.org/project/simple-trade/)\r\n[](https://www.python.org/downloads/)\r\n[](https://github.com/BSoybilgen/simple-trade/actions/workflows/tests.yml)\r\n[](https://codecov.io/github/BSoybilgen/simple-trade)\r\n\r\nA Python library that allows you to compute technical indicators and build trade strategies in a simple way.\r\n\r\n## Features\r\n\r\n* **Data Fetching:** Easily download historical stock data using `yfinance`.\r\n* **Technical Indicators:** Compute a variety of technical indicators:\r\n * Trend (e.g., Moving Averages, MACD, ADX)\r\n * Momentum (e.g., RSI, Stochastics)\r\n * Volatility (e.g., Bollinger Bands, ATR)\r\n * Volume (e.g., On-Balance Volume)\r\n* **Trading Strategies:** Implement and backtest common trading strategies:\r\n * Cross Trade Strategies (`cross_trade`)\r\n * Band Trading Strategies (`band_trade`)\r\n* **Backtesting:** Evaluate the performance of your trading strategies on historical data.\r\n* **Optimization:** Optimize strategy parameters using techniques like grid search.\r\n* **Plotting:** Visualize data, indicators, and backtest results using `matplotlib`.\r\n* **Combining:** Combine different strategies to create a more complex strategy.\r\n\r\n## Installation\r\n\r\n1. **Clone the repository:**\r\n ```bash\r\n git clone <repository_url> # Replace with your repo URL\r\n cd simple-trade\r\n ```\r\n2. **Create and activate a virtual environment (recommended):**\r\n ```bash\r\n python -m venv myenv\r\n # On Windows\r\n myenv\\Scripts\\activate\r\n # On macOS/Linux\r\n source myenv/bin/activate\r\n ```\r\n3. **Install the package and dependencies:**\r\n ```bash\r\n pip install .\r\n ```\r\n Alternatively, installed with PyPI:\r\n ```bash\r\n pip install simple-trade\r\n ```\r\n\r\n## Dependencies\r\n\r\n* Python >= 3.10\r\n* [yfinance](https://pypi.org/project/yfinance/)\r\n* [pandas](https://pandas.pydata.org/)\r\n* [numpy](https://numpy.org/)\r\n* [joblib](https://joblib.readthedocs.io/en/latest/)\r\n* [matplotlib](https://matplotlib.org/)\r\n\r\nThese will be installed automatically when you install `simple-trade` using `pip`.\r\n\r\n## Basic Usage\r\n\r\n### Calculate Indicators\r\n\r\nHere's a quick example of how to download data and compute a technical indicator:\r\n\r\n```python\r\n# Load Packages and Functions\r\nimport pandas as pd\r\nfrom simple_trade import compute_indicator, download_data\r\n\r\n# Step 1: Download data\r\nsymbol = 'TSLA'\r\nstart = '2024-01-01'\r\nend = '2025-01-01'\r\ninterval = '1d'\r\nprint(f\"\\nDownloading data for {symbol}...\")\r\ndata = download_data(symbol, start, end, interval=interval)\r\n\r\n# Step 2: Calculate indicator\r\nparameters = dict()\r\ncolumns = dict()\r\nparameters[\"window\"] = 14\r\ndata, columns, fig = compute_indicator(\r\n data=data,\r\n indicator='adx',\r\n parameters=parameters\r\n)\r\n\r\n# Step 3: Display the plot\r\nfig.show()\r\n```\r\n\r\n**Plot of Results**\r\n<img src=\"https://i.imgur.com/JBpd0qo.png\" alt=\"Figure 1\" width=\"900\" height=\"600\">\r\n\r\n### Backtesting Strategies\r\n\r\nUse the `premade_backtesting` module to simulate strategies like moving average crossovers (`cross_trade`) or Bollinger Band breakouts (`band_trade`).\r\n\r\n```python\r\n# Load Packages and Functions\r\nimport pandas as pd\r\nfrom simple_trade import download_data\r\nfrom simple_trade import premade_backtest\r\nfrom simple_trade import CrossTradeBacktester\r\n\r\n# Step 1: Download data\r\nsymbol = 'AAPL'\r\nstart_date = '2020-01-01'\r\nend_date = '2022-12-31'\r\ninterval = '1d'\r\ndata = download_data(symbol, start_date, end_date, interval=interval)\r\n\r\n# Step 2: Set Global Parameters\r\nglobal_parameters = {\r\n 'initial_cash': 10000,\r\n 'commission_long': 0.001,\r\n 'commission_short': 0.001,\r\n 'short_borrow_fee_inc_rate': 0.0,\r\n 'long_borrow_fee_inc_rate': 0.0,\r\n 'trading_type': 'long',\r\n 'day1_position': 'none',\r\n 'risk_free_rate': 0.0,\r\n}\r\n\r\n# Step 3: Set Strategy Parameters\r\nstrategy_name = 'sma'\r\nspecific_parameters = {\r\n 'short_window': 25,\r\n 'long_window': 75,\r\n 'fig_control': 1,\r\n}\r\n\r\n# Step 4: Run Backtest\r\nparameters = {**global_parameters, **specific_parameters}\r\nresults, portfolio, fig = premade_backtest(data, strategy_name, parameters)\r\n```\r\n\r\n**Plot of Results**\r\n<img src=\"https://i.imgur.com/4qxr0dp.png\" alt=\"Figure 2\" width=\"900\" height=\"600\">\r\n\r\n\r\n### Optimizing Strategies\r\n\r\nThe `premade_optimizer` module allows you to find the best parameters for your strategy (e.g., optimal moving average windows).\r\n\r\n```python\r\n# Load Packages and Functions\r\nfrom simple_trade import download_data\r\nfrom simple_trade.premade_optimizer import premade_optimizer\r\n\r\n# Step 1: Load Data\r\nticker = \"AAPL\"\r\nstart_date = \"2020-01-01\"\r\nend_date = \"2023-12-31\"\r\n\r\ndata = download_data(ticker, start_date, end_date)\r\n\r\n# Step 2: Load Optimization Parameters\r\n# Define the parameter grid to search\r\nparam_grid = {\r\n 'short_window': [10, 20, 30],\r\n 'long_window': [50, 100, 150],\r\n}\r\n\r\n# Step 3: Set Base Parameters\r\nbase_params = {\r\n 'initial_cash': 100000.0,\r\n 'commission_long': 0.001, # 0.1% commission\r\n 'commission_short': 0.001,\r\n 'trading_type': 'long', # Only long trades\r\n 'day1_position': 'none',\r\n 'risk_free_rate': 0.02,\r\n 'metric': 'total_return_pct', # Metric to optimize\r\n 'maximize': True, # Maximize the metric\r\n 'parallel': False, # Sequential execution for this example\r\n 'fig_control': 0 # No plotting during optimization\r\n}\r\n\r\n# Step 4: Run Optimization\r\nbest_results, best_params, all_results = premade_optimizer(\r\n data=data,\r\n strategy_name='sma',\r\n parameters=base_params,\r\n param_grid=param_grid\r\n)\r\n\r\n# Show top 3 parameter combinations\r\nprint(\"\\nTop 3 SMA Parameter Combinations:\")\r\nsorted_results = sorted(all_results, key=lambda x: x['score'], reverse=True)\r\nfor i, result in enumerate(sorted_results[:3]):\r\n print(f\" {i+1}. {result['params']} -> {result['score']:.2f}%\")\r\n```\r\n\r\n**Output of Results**\r\n```\r\nTop 3 SMA Parameter Combinations:\r\n 1. {'short_window': 10, 'long_window': 50} -> 99.87%\r\n 2. {'short_window': 20, 'long_window': 50} -> 85.69%\r\n 3. {'short_window': 30, 'long_window': 50} -> 67.08%\r\n```\r\n\r\n## Examples\r\n\r\nFor more detailed examples, please refer to the Jupyter notebooks in the `/examples` directory:\r\n\r\n* `/examples/indicators`: Demonstrations of various technical indicators.\r\n* `/examples/backtest`: Examples of backtesting different strategies.\r\n* `/examples/optimize`: Examples of optimizing strategy parameters.\r\n* `/examples/combine_trade`: Examples of combining different strategies.\r\n\r\n## Contributing\r\n\r\nContributions are welcome! Please feel free to submit a pull request or open an issue. (Further details can be added here if needed).\r\n\r\n## License\r\n\r\nThis project is licensed under the AGPL-3.0 License - see the [LICENSE](LICENSE) file for details.\r\n",
"bugtrack_url": null,
"license": "AGPL-3.0",
"summary": "Compute technical indicators and build trade strategies in a simple way",
"version": "0.2.0",
"project_urls": {
"Source": "https://github.com/BSoybilgen/simple-trade/"
},
"split_keywords": [
"algo",
" algorithmic",
" backtest",
" backtesting",
" candlestick",
" chart",
" crypto",
" currency",
" equity",
" exchange",
" finance",
" financial",
" forex",
" fx",
" indicator",
" invest",
" investing",
" investment",
" ohlc",
" ohlcv",
" order",
" price",
" profit",
" quant",
" quantitative",
" simulation",
" stocks",
" strategy",
" ticker",
" trader",
" trading"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "60053cf88d062cce2155c041b1dcff37aad0f8eb79e2e0e1352ad297d9ac5f1b",
"md5": "3b1d21896cd2922f6641bbede01bcf65",
"sha256": "d8e028789d1fcb5dba20eac18178a7411df998d98adeebe92eeab3ccf80ea219"
},
"downloads": -1,
"filename": "simple_trade-0.2.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "3b1d21896cd2922f6641bbede01bcf65",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 99398,
"upload_time": "2025-09-01T20:40:06",
"upload_time_iso_8601": "2025-09-01T20:40:06.850200Z",
"url": "https://files.pythonhosted.org/packages/60/05/3cf88d062cce2155c041b1dcff37aad0f8eb79e2e0e1352ad297d9ac5f1b/simple_trade-0.2.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-09-01 20:40:06",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "BSoybilgen",
"github_project": "simple-trade",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "yfinance",
"specs": [
[
">=",
"0.2.59"
]
]
},
{
"name": "pandas",
"specs": [
[
">=",
"1.4.0"
]
]
},
{
"name": "numpy",
"specs": [
[
">=",
"1.22.0"
]
]
},
{
"name": "matplotlib",
"specs": [
[
">=",
"3.6.0"
]
]
},
{
"name": "joblib",
"specs": [
[
">=",
"1.1.1"
]
]
}
],
"lcname": "simple-trade"
}