{"repo":"jrmeier/fast-trade","free":true,"listed":false,"github":"https://github.com/jrmeier/fast-trade","clone":"git clone https://github.com/jrmeier/fast-trade.git","description":"low code backtesting library utilizing pandas and technical analysis indicators","language":"Python","stars":581,"topics":["algotrading","backtesting","charting-library","cryptocurrency","finance","technical-analysis","technical-indicators"],"license":"AGPL-3.0","category":"algotrading_tool","readme_excerpt":"# Fast Trade\n\n[![License: LGPL v3](https://img.shields.io/github/license/jrmeier/fast-trade)](LICENSE)\n[![PyPI](https://img.shields.io/pypi/v/fast-trade.svg?style=flat-square)](https://pypi.org/project/fast-trade/)\n[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/download/releases/3.11.0/)\n[![Python application](https://github.com/jrmeier/fast-trade/workflows/Python%20application/badge.svg)](https://github.com/jrmeier/fast-trade/actions)\n\nA library built with backtest portability and performance in mind for trading strategy backtests. There is also an [Archive](#Archive), which can be used to download compatible kline data from Binance (.com or .us) and Coinbase into local parquet datasets.\n\n## Motivations\nIf backtests are fast, strategies are cheap.\n\n## MCP Server\n\nI'm using this library and my own closed-source data collection software which has live-streaming data from HyperLiquid, Coinbase, and Binanceus. If you want to try it out with absolutely no garentees, send me an email at fasttrade@jedm.dev or join the Discord [https://discord.gg/Y8ypD3dcgs](https://discord.gg/Y8ypD3dcgs).\n\nStart the local MCP server with `python -m fast_trade.mcp_server`. Available tools include CLI wrappers, portfolio helpers, log tailing, `fxmacrodata_macro_context`, and `hmm_screen`.\n\n## Contributing\n\nIf you'd like to add a feature, fix a bug, or something else, please clone the repo and fork it. When you're ready, open a PR into this main repo.\n\nTo get started with local dev, clone the repo, set up a virtual env, source it, then install the dev requirements.\n\n```bash\ngit clone git@github.com:<YOUR GIT USERNAME>/fast-trade.git\ncd ./fast-trade\npython -m venv venv\nsource venv/bin/activate\npip install -e .\n```\n\nTo generate testing coverage, run\n\n```bash\ncoverage run -m pytest\ncoverage report -m\n```\n\n## Install\n\n```bash\npip install fast-trade\n```\n\nSee `docs/GETTING_STARTED.md` for the fastest end-to-end setup and first-run guide.\n\n## Usage\n\n[strategy.yml](./strategy.yml) for an example strategy. The basic idea is you describe the \"datapoints\" then compare them in the \"logics\". The \"datapoints\" describe the technical analysis functions to run, and the \"logics\" describe the logic to use to determine when to enter and exit trades.\n\nExample backtest script\n\n```python\nfrom fast_trade import run_backtest, validate_backtest\n\nbacktest = {\n    \"base_balance\": 1000, # start with a balance of 1000\n    \"freq\": \"5Min\", # time period selected on the chard\n    \"chart_start\": \"2021-08-30 18:00:00\", # when to start the chart\n    \"chart_stop\": \"2021-09-06 16:39:00\", # when to stop the chart\n    \"comission\": 0.01, # a comission to pay per transaction \n    \"datapoints\": [ # describes the data to use in the logic\n        {\n            \"args\": [ # args are passed to the transformer function\n                30\n            ],\n            \"transformer\": \"sma\", # technical analysis function to run\n            \"name\": \"sma_short\" # reference point for use in logic\n        },\n        {\n            \"args\": [\n                90\n            ],\n            \"transformer\": \"sma\",\n            \"name\": \"sma_long\"\n        },\n    ],\n    \"enter\": [\n      [\n        \"close\", # field to reference, by default this is any column in the data file. Could also be a float or int\n        \">\", # operator to compare these to\n        \"sma_long\" # name of datapoint that was prevously defined\n      ],\n      [\n        \"close\",\n        \">\",\n        \"sma_short\"\n      ]\n    ],\n    \"exit\": [\n      [\n        \"close\",\n        \"<\",\n        \"sma_short\"\n      ]\n    ],\n    \"rules\": [[\"sharpe_ratio\", \">\", 0.5]], # use rules to filter out backtests that didnt perform well\n    \"trailing_stop_loss\": 0.05, # optional trailing stop loss \n    \"exit_on_end\": False, # at then end of the backtest, if true, the trade will exit\n}\n# backtests can also come from urls\n# backtest = \"https://raw.githubusercontent.com/jrmeier/fast-trade/master/sma_strategy.yml\"\n\n# returns a mirror of the object, with errors if any\nprint(validate_backtest(backtest))\n\n# returns the summary object and the dataframe\nresult = run_backtest(backtest)\n\nsummary = result[\"summary\"]\ndf = result[\"df\"]\ntrade_log_df = result[\"trade_df\"]\n\nprint(summary)\nprint(df.head())\n```\n\n\n## CLI\n\nYou can also use the package from the command line. Each command's specific help feature can be viewed by running `ft <command> -h`.\n\nList the commands and their help.\n`ft -h`\n\n### Basic usage\n\nThis will download the last month of data for BTCUSD from binance.us and store it in `ft_archive/`.\n\n`ft download BTCUSD binanceus`\n\nThis will backtest a file with a strategy. By default, it will only show a summary of the backtest. However, if you want to save the results, add the `--save` flag and it will go the `saved_backtests/` directory.\n\n`ft backtest ./strategy.yml`\n\nYou can validate a backtest before you run it. This doesn't help with the data, but does help with the logic.\n`ft validate strategy.yml`\n\n### Backteset Modifiers\n\nModifying the `freq`\n\n`ft backtest ./strategy.yml --mods freq 1H`\n\nModifying the `freq` and the `trailing_stop_loss`\n\n`ft backtest ./strategy.yml --mods freq 1H trailing_stop_loss .05`\n\nSaving a test result\nThis generates creates the `saved_backtest` directory (if it doesn't exist), then inside of there, is another directory with a timestamp, with a chart, the backtest file, the summary, and the raw dataframe as a csv.\n`ft backtest ./strategy.yml --save`\n\n### Archive\nYou can download data directly from the CoinbaseAPI and BinanceAPI without registering for an API key.\n\nGet a list of assets available for download from the given exchange. Defaults to binanceus.\n\n`ft assets --exchange=EXCHANGE`\n\nDownload a single asset from the given exchange. Defaults to binanceus.\n`ft download SYMBOL EXCHANGE`\n\nDownload the last 30 days of BTCUSDT from binance.us\n`ft download BTCUSDT binanceus`\n\n`ft download SYMBOL --archive ARCHIVE_PATH --start START_DATE --end END_DATE --exchange=EXCHANGE`\n\nUpdate the archive. Brings the archive up to date with the latest data for each symbol.\n\n```ft update_archive```\n\nThis update all the existing items in the archive, downloading the latest data for each symbol.\n\n## Browse saved backtests\n\n```bash\nft backtests list\nft backtests show --index 1\nft logs --kind all --tail 200\n```\n\n### Persistent logs\n\nPortfolio activity is persisted as JSONL so it can be tailed with `ft logs` or consumed by external tools.\n\n- Portfolio: `ft_archive/portfolio/<NAME>/portfolio.jsonl`\n- Optional live/stream logs (if present): `ft_archive/live_logs/<RUN_ID>.jsonl`, `ft_archive/stream_logs/<RUN_ID>.jsonl`\n\n## Changelog\n\nSee `docs/CHANGELOG.md`.\n\n## Release Notes\n\nVersion `2.1.0` adds FXMacroData macro/FX context and a productized HMM screener (`ft screen hmm`, MCP `hmm_screen`). See `docs/CHANGELOG.md` for the full change list and `docs/RELEASE.md` for the release checklist.\n\n## Machine Learning\n\nFast Trade includes optional ML utilities for optimization and regime detection.\n\n### Genetic Algorithm (Evolver)\n\nRun a GA optimization using a YAML config:\n\n```bash\nft evolve evolver_example.yml\n```\n\nKey fields in `evolver_example.yml`:\n- `strategy` or `strategy_path` — base strategy\n- `genes` — list of tunable parameters\n- `settings` — population size, generations, mutation rates, etc.\n- `fitness` — metrics to optimize\n\n### Regime Model\n\nTrain a regime model:\n\n```bash\nft regime_train regime_example.yml data.csv --out regime_model.pkl\n```\n\nApply a trained model:\n\n```bash\nft regime_apply regime_model.pkl data.csv --out regime_output.csv\n```\n\nSee `regime_example.yml` for expected config structure.\n\n### HMM Screener\n\nRank symbols with a Gaussian HMM + Monte Carlo forecast screen:\n\n```bash\n# Archive-first (download candles first)\nft download BTC-USD coinbase --start 2024-01-01\nft screen hmm hmm_screen_example.yml\n\n# Or live Coinbase / Hyperliquid fetch\nft screen hmm --exchange coinbase --symbol BTC-USD --symbol ETH-USD --live\nft screen hmm --exchange hyperliquid --symbol BTC --live --json-out ft_archive/screens/hl.json\n```\n\nSee `hmm_screen_example.yml` for filters, horizons, and output paths. Agents can call the MCP tool `hmm_screen`.\n\n\n## Testing\n\n```bash\npython -m pytest\n```\n\n## Coverage\n\n```bash\ncoverage run -m pytest\ncoverage report -m\n```\n\n## FXMacroData macro context\n\n`FXMacroDataClient` uses the canonical `https://api.fxmacrodata.com/v1/` API host.\nSet `FXMACRODATA_API_KEY` (or `FXMD_API_KEY`) to access protected data, or pass\n`api_key` directly when creating the client. `build_macro_context(\"EUR\", \"USD\")`\nreturns the pair's catalogue, filtered release calendars and announcements, and FX data.\nThe same helper is available to agents as the MCP tool `fxmacrodata_macro_context`.\n\n## Output\n\nThe output its a dictionary. The summary is a summary all the inputs and of the performace of the model. The df is a Pandas Dataframe, which contains all of the data used in the simulation. And the `trade_df` is a subset of the `df` frame which just has all the rows when there was an event. The `backtest` object is also returned, with the details of how the backtest was run.\n\nExample output:\n\n```python\n{\n  \"return_perc\": 10.093,\n  \"sharpe_ratio\": 0.893,\n  \"buy_and_hold_perc\": 2.086,\n  \"median_trade_len\": 4200.0,\n  \"mean_trade_len\": 7341.7,\n  \"max_trade_held\": 54300.0,\n  \"min_trade_len\": 300.0,\n  \"total_num_winning_trades\": 136.0,\n  \"total_num_losing_trades\": 371.0,\n  \"avg_win_perc\": 0.142,\n  \"avg_loss_perc\": -0.021,\n  \"best_trade_perc\": 0.012,\n  \"min_trade_perc\": -0.0025,\n  \"median_trade_perc\": -0.0001,\n  \"mean_trade_perc\": 0.0002,\n  \"num_trades\": 507,\n  \"win_perc\": 26.824,\n  \"loss_perc\": 73.176,\n  \"equity_peak\": 1127.147,\n  \"equity_final\": 1112.254,\n  \"max_drawdown\": 985.676,\n  \"total_fees\": 26.662,\n  \"first_tic\": \"2024-11-27 01:15:00\",\n  \"last_tic\": \"2025-01-09 03:10:00\",\n  \"total_tics\": 12408,\n  \"perc_missing\": 0.0,\n  \"total_missing\": 0,\n  \"test_duration\": 0.302,\n  \"num_of_enter_signals\": 718,\n  \"num_of_exit_signals\": 5564,\n ","default_branch":"master","files":125,"tree":[".coveragerc",".flake8",".github/workflows/codeql-analysis.yml",".github/workflows/pythonapp.yml",".github/workflows/pythonpublish.yml",".gitignore",".python-version","AGENTS.md","LICENSE","Live.plan.md","MANIFEST.INI","README.md","_config.yml","docs/ACTION_ENGINE_PLAN.md","docs/CHANGELOG.md","docs/CONTRIBUTING.md","docs/FINTA_README.md","docs/GETTING_STARTED.md","docs/METRICS.md","docs/README.md","docs/RELEASE.md","docs/RUN_ANALYSIS_PLAN.md","docs/TRANSFORMER_README.md","evolver_example.quick.yml","evolver_example.yml","example_backtest.yml","fast_trade/__init__.py","fast_trade/archive/__init__.py","fast_trade/archive/binance_api.py","fast_trade/archive/cli.py","fast_trade/archive/coinbase_api.py","fast_trade/archive/db_helpers.py","fast_trade/archive/update_archive.py","fast_trade/archive/update_kline.py","fast_trade/build_data_frame.py","fast_trade/build_summary.py","fast_trade/calculate_perc_missing.py","fast_trade/cli.py","fast_trade/cli_helpers.py","fast_trade/cli_render.py","fast_trade/evaluate.py","fast_trade/finta.py","fast_trade/ftv.py","fast_trade/fxmacrodata.py","fast_trade/logic_utils.py","fast_trade/mcp_server.py","fast_trade/ml/__init__.py","fast_trade/ml/evolver.py","fast_trade/ml/hmm_data.py","fast_trade/ml/hmm_screen.py","fast_trade/ml/markov.py","fast_trade/ml/regime.py","fast_trade/portfolio.py","fast_trade/run_analysis.py","fast_trade/run_backtest.py","fast_trade/summary/__init__.py","fast_trade/summary/metrics.py","fast_trade/summary/trades.py","fast_trade/transformers_map.py","fast_trade/utils.py","fast_trade/validate_backtest.py","finta_examples/examples/README.md","finta_examples/examples/backtest.ipynb","finta_examples/examples/charting.ipynb","finta_examples/examples/intro.ipynb","finta_examples/examples/plot.png","genes.yml","hmm_screen_example.yml","pyproject.toml","regime_example.yml","run_example.py","run_parallel_example.py","scripts/coinbase_hmm_screener.py","scripts/hyperliquid_hmm_screener.py","scripts/profile_backtest_hotspots.py","sma_strategy.yml","strategy.yml","strategy_mean_revert.yml","strategy_momentum.yml","test/__init__.py","test/archive_main_runners.py","test/conftest.py","test/empty.csv.txt","test/extra_data.txt","test/ohlcv_data.csv.txt","test/test_additional_summary_metrics.py","test/test_archive_binance_api.py","test/test_archive_cli.py","test/test_archive_coinbase_api.py","test/test_archive_db_helpers.py","test/test_archive_update_archive.py","test/test_archive_update_kline.py","test/test_build_data_frame.py","test/test_build_data_frame_coverage.py","test/test_build_summary.py","test/test_calculate_perc_missing.py","test/test_cli_backtest.py","test/test_cli_coverage_remaining.py","test/test_cli_helpers.py","test/test_cli_portfolio.py","test/test_cli_render.py","test/test_cli_screen.py","test/test_effective_trades.py","test/test_evaluate.py","test/test_evolver.py","test/test_finta.py","test/test_ftv.py","test/test_fxmacrodata.py","test/test_hmm_data.py","test/test_hmm_screen.py","test/test_logic_utils.py","test/test_markov.py","test/test_mcp_server.py","test/test_phase2_remaining_coverage.py","test/test_portfolio.py","test/test_regime.py","test/test_run_analysis.py","test/test_run_analysis_coverage.py","test/test_run_backtest.py","test/test_run_backtest_coverage.py","test/test_run_backtest_e2e.py","test/test_summary_portfolio_coverage.py","test/test_utils.py","test/test_validate_backtest.py","zma1_strat.yml"],"storefront":"/r/jrmeier","claimed":false,"request_supported":{"post":"https://gitbuyer.com/r/jrmeier/fast-trade/request-supported","requests":0},"note":"indexed from public GitHub; nothing is for sale on this page. Clone it from GitHub. Paid listings live at /search."}