Fast Trade
low code backtesting library utilizing pandas and technical analysis indicators
Install / Use
npx skills add jrmeier/fast-tradeInstalls into whichever agent you are using.
README
Fast Trade
A library built with backtest portability and performance in mind for trading strategy backtests. There is also an Archive, which can be used to download compatible kline data from Binance (.com or .us) and Coinbase into local parquet datasets.
Motivations
If backtests are fast, strategies are cheap.
MCP Server
I'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.
Start 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.
Contributing
If 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.
To get started with local dev, clone the repo, set up a virtual env, source it, then install the dev requirements.
git clone git@github.com:<YOUR GIT USERNAME>/fast-trade.git
cd ./fast-trade
python -m venv venv
source venv/bin/activate
pip install -e .
To generate testing coverage, run
coverage run -m pytest
coverage report -m
Install
pip install fast-trade
See docs/GETTING_STARTED.md for the fastest end-to-end setup and first-run guide.
Usage
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.
Example backtest script
from fast_trade import run_backtest, validate_backtest
backtest = {
"base_balance": 1000, # start with a balance of 1000
"freq": "5Min", # time period selected on the chard
"chart_start": "2021-08-30 18:00:00", # when to start the chart
"chart_stop": "2021-09-06 16:39:00", # when to stop the chart
"comission": 0.01, # a comission to pay per transaction
"datapoints": [ # describes the data to use in the logic
{
"args": [ # args are passed to the transformer function
30
],
"transformer": "sma", # technical analysis function to run
"name": "sma_short" # reference point for use in logic
},
{
"args": [
90
],
"transformer": "sma",
"name": "sma_long"
},
],
"enter": [
[
"close", # field to reference, by default this is any column in the data file. Could also be a float or int
">", # operator to compare these to
"sma_long" # name of datapoint that was prevously defined
],
[
"close",
">",
"sma_short"
]
],
"exit": [
[
"close",
"<",
"sma_short"
]
],
"rules": [["sharpe_ratio", ">", 0.5]], # use rules to filter out backtests that didnt perform well
"trailing_stop_loss": 0.05, # optional trailing stop loss
"exit_on_end": False, # at then end of the backtest, if true, the trade will exit
}
# backtests can also come from urls
# backtest = "https://raw.githubusercontent.com/jrmeier/fast-trade/master/sma_strategy.yml"
# returns a mirror of the object, with errors if any
print(validate_backtest(backtest))
# returns the summary object and the dataframe
result = run_backtest(backtest)
summary = result["summary"]
df = result["df"]
trade_log_df = result["trade_df"]
print(summary)
print(df.head())
CLI
You can also use the package from the command line. Each command's specific help feature can be viewed by running ft <command> -h.
List the commands and their help.
ft -h
Basic usage
This will download the last month of data for BTCUSD from binance.us and store it in ft_archive/.
ft download BTCUSD binanceus
This 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.
ft backtest ./strategy.yml
You can validate a backtest before you run it. This doesn't help with the data, but does help with the logic.
ft validate strategy.yml
Backteset Modifiers
Modifying the freq
ft backtest ./strategy.yml --mods freq 1H
Modifying the freq and the trailing_stop_loss
ft backtest ./strategy.yml --mods freq 1H trailing_stop_loss .05
Saving a test result
This 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.
ft backtest ./strategy.yml --save
Archive
You can download data directly from the CoinbaseAPI and BinanceAPI without registering for an API key.
Get a list of assets available for download from the given exchange. Defaults to binanceus.
ft assets --exchange=EXCHANGE
Download a single asset from the given exchange. Defaults to binanceus.
ft download SYMBOL EXCHANGE
Download the last 30 days of BTCUSDT from binance.us
ft download BTCUSDT binanceus
ft download SYMBOL --archive ARCHIVE_PATH --start START_DATE --end END_DATE --exchange=EXCHANGE
Update the archive. Brings the archive up to date with the latest data for each symbol.
ft update_archive
This update all the existing items in the archive, downloading the latest data for each symbol.
Browse saved backtests
ft backtests list
ft backtests show --index 1
ft logs --kind all --tail 200
Persistent logs
Portfolio activity is persisted as JSONL so it can be tailed with ft logs or consumed by external tools.
- Portfolio:
ft_archive/portfolio/<NAME>/portfolio.jsonl - Optional live/stream logs (if present):
ft_archive/live_logs/<RUN_ID>.jsonl,ft_archive/stream_logs/<RUN_ID>.jsonl
Changelog
See docs/CHANGELOG.md.
Release Notes
Version 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.
Machine Learning
Fast Trade includes optional ML utilities for optimization and regime detection.
Genetic Algorithm (Evolver)
Run a GA optimization using a YAML config:
ft evolve evolver_example.yml
Key fields in evolver_example.yml:
strategyorstrategy_path— base strategygenes— list of tunable parameterssettings— population size, generations, mutation rates, etc.fitness— metrics to optimize
Regime Model
Train a regime model:
ft regime_train regime_example.yml data.csv --out regime_model.pkl
Apply a trained model:
ft regime_apply regime_model.pkl data.csv --out regime_output.csv
See regime_example.yml for expected config structure.
HMM Screener
Rank symbols with a Gaussian HMM + Monte Carlo forecast screen:
# Archive-first (download candles first)
ft download BTC-USD coinbase --start 2024-01-01
ft screen hmm hmm_screen_example.yml
# Or live Coinbase / Hyperliquid fetch
ft screen hmm --exchange coinbase --symbol BTC-USD --symbol ETH-USD --live
ft screen hmm --exchange hyperliquid --symbol BTC --live --json-out ft_archive/screens/hl.json
See hmm_screen_example.yml for filters, horizons, and output paths. Agents can call the MCP tool hmm_screen.
Testing
python -m pytest
Coverage
coverage run -m pytest
coverage report -m
FXMacroData macro context
FXMacroDataClient uses the canonical https://api.fxmacrodata.com/v1/ API host.
Set FXMACRODATA_API_KEY (or FXMD_API_KEY) to access protected data, or pass
api_key directly when creating the client. build_macro_context("EUR", "USD")
returns the pair's catalogue, filtered release calendars and announcements, and FX data.
The same helper is available to agents as the MCP tool fxmacrodata_macro_context.
Output
The 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.
Example output:
{
"return_perc": 10.093,
"sharpe_ratio": 0.893,
"buy_and_hold_perc": 2.086,
"median_trade_len": 4200.0,
"mean_trade_len": 7341.7,
"max_trade_held": 54300.0,
"min_trade_len": 300.0,
"total_num_winning_trades": 136.0,
"total_num_losing_trades": 371.0,
"avg_win_perc": 0.142,
"avg_loss_perc": -0.021,
"best_trade_perc": 0.012,
"min_trade_perc": -0.0025,
"median_trade_perc": -0.0001,
"mean_trade_perc": 0.0002,
"num_trades": 507,
"win_perc": 26.824,
"loss_perc": 73.176,
"equity_peak": 1127.147,
"equity_final": 1112.254,
"max_drawdown": 985.676,
"total_fees": 26.662,
"first_tic": "2024-11-27 01:15:00",
"last_tic": "2025-01-09 03:10:00",
"total_tics": 12408,
"perc_missing": 0.0,
"total_missing": 0,
"test_duration": 0.302,
"num_of_enter_signals": 718,
"num_of_exit_signals": 5564,
Related Skills
node-connect
385.5kDiagnose OpenClaw Android, iOS, or macOS node pairing, QR/setup code, route, auth, and connection failures.
blender-python-addon
40.5kBlender Python add-on rules for operators, panels, properties, registration, testing, and API-safe scripting
flutter-development-guidelines-cursorrules-prompt-file
40.5kCursor rules for Flutter development with MVVM architecture, Riverpod state management, Material widgets, and Dart style guidelines.
commit-push-pr
140.6kCommit, push, and open a PR
