# Backtest a crypto strategy in Python: fees, funding, bias

URL: https://fincodelabs.com/en/blog/crypto-backtesting-python · Publisher: Fincode (Fincode Yazılım ve Teknoloji A.Ş.), Istanbul, Turkey · Category: Backtesting and risk · Published: 2026-11-26 · Updated: 2026-11-26

Backtest a crypto strategy in Python: tested code on synthetic data showing how fees, slippage and funding change results, plus a look-ahead bias test.

**Short answer:** To **backtest a crypto strategy in Python**, check the candles for gaps, shift each signal one bar so it trades after the close it used, and charge fees, slippage and, for perpetual futures, funding. In a test on synthetic data on 26 November 2026, costs turned −8.90% into −63.98% and a missing one-bar shift produced a false +243.86%. A backtest shows how rules behaved on one history under stated assumptions and does not guarantee future results.

All figures below come from seeded synthetic data generated on 26 November 2026 and describe no market or strategy.

## How to backtest a crypto strategy in Python: five steps

A crypto backtest in Python needs five steps.

1. **Check the data:** UTC index, sorted, no duplicates, finite positive prices, no missing bars. Stop on a gap instead of forward-filling it; sources and licenses are in [crypto historical data download](https://fincodelabs.com/en/blog/crypto-historical-data-download).
2. **Use only data known at each bar's close,** then shift the signal one bar.
3. **Charge every trade:** fee and slippage per side (see [slippage in crypto](https://fincodelabs.com/en/blog/slippage-crypto)).
4. **Add funding for perpetual futures** at the venue's funding timestamps, separate from fees.
5. **Test the backtester:** broken inputs must fail, and a later price must never move an earlier position.

The code below does only this: no position sizing, compounding or order book; results are summed bar returns on a constant notional. Full frameworks are compared in [Python backtesting libraries compared](https://fincodelabs.com/en/blog/backtesting-python-libraries).

## A minimal crypto backtester in Python, with tests

About 60 lines of pandas show where crypto backtests go wrong; the tests matter more than the backtest.

The rule is a placeholder to exercise the code: long when the close is above its 168-bar mean. It is not a strategy, and nothing on this page suggests using it or any setting. Tested on 26 November 2026 with Python 3.11.3, pandas 2.2.3 and NumPy 2.0.0.

```python
import numpy as np, pandas as pd

H = pd.Timedelta("1h")

def check_candles(df):
    idx = df.index
    if df.empty or not isinstance(idx, pd.DatetimeIndex) or idx.tz is None:
        raise ValueError("need hourly candles on a UTC DatetimeIndex (bar open time)")
    if idx.has_duplicates or not idx.is_monotonic_increasing:
        raise ValueError("timestamps duplicated or unsorted")
    c = pd.to_numeric(df["close"], errors="coerce").to_numpy(dtype=float)
    if not np.isfinite(c).all() or (c <= 0).any():
        raise ValueError("close prices must be finite and positive")
    gaps = int((~((idx[1:] - idx[:-1]) == H)).sum())
    if gaps:
        raise ValueError(f"{gaps} gap(s) in candles: fetch them, do not forward-fill")
    return pd.Series(c, index=idx)                 # exchanges send prices as text

def parse_funding(body):
    if not isinstance(body, list):                 # error bodies are objects
        raise ValueError(f"funding request failed: {repr(body)}")
    times, rates = [], []
    for r in body:
        if not isinstance(r, dict) or "fundingTime" not in r or "fundingRate" not in r:
            raise ValueError(f"bad funding record: {repr(r)}")
        try:
            times.append(pd.Timestamp(int(r["fundingTime"]), unit="ms", tz="UTC"))
            rates.append(float(r["fundingRate"]))
        except (TypeError, ValueError):            # None, "", "abc"
            raise ValueError(f"bad funding record: {repr(r)}") from None
    s = pd.Series(rates, index=pd.DatetimeIndex(times), dtype=float)
    if s.index.has_duplicates or not np.isfinite(s).all():
        raise ValueError("duplicate funding times or non-finite rates")
    return s.sort_index()

def rule(close):          # placeholder to exercise the code, not a strategy
    return (close > close.rolling(168).mean()).astype(float)

def backtest(df, funding, fee, slip, peek=False):
    close = check_candles(df)
    ret = close.pct_change().fillna(0)
    sig = rule(close)                              # known at each bar's close
    held = sig if peek else sig.shift(1).fillna(0) # peek=True is the bug
    trades = held.diff().abs().fillna(held.abs())
    bar = pd.DatetimeIndex(funding.index).round("h") - H             # bar that ends at funding time
    if bar.has_duplicates:
        raise ValueError("two funding events map to one bar")
    f = pd.Series(funding.to_numpy(), index=bar).reindex(df.index, fill_value=0.0)
    return pd.DataFrame({"gross": held * ret, "fees": -fee * trades,
                         "slippage": -slip * trades, "funding": -held * f,
                         "trades": trades, "held": held})

def peeks(df, points, **kw):      # does a later price change an earlier position?
    none = pd.Series(dtype=float)
    base = backtest(df, none, 0, 0, **kw)["held"]
    for t in points:
        for k in (0.5, 1.5):
            d = df.copy()
            d.iloc[t:, d.columns.get_loc("close")] *= k
            if not backtest(d, none, 0, 0, **kw)["held"].iloc[t] == base.iloc[t]:
                return True
    return False
```

The tests feed in what arrives from APIs and CSVs: an empty frame, a gap, reversed or duplicated rows, a naive index, a price of 1e400 (infinity to Python) or text, an error object, a record without fields or with a null rate, a repeated funding time and two funding times in one hour. Numeric strings, as exchange APIs send prices, must still work.

```python
import numpy as np, pandas as pd
from bt import *   # the module above, saved as bt.py
idx = pd.date_range("2025-01-01", periods=400, freq="h", tz="UTC")
df = pd.DataFrame({"close": 100 + np.sin(np.arange(400) / 9)}, index=idx)
ok = {"fundingTime": 1735718400003, "fundingRate": "0.0001"}
pts = range(200, 400, 7)
assert peeks(df, pts, peek=True) and not peeks(df, pts)
backtest(df.assign(close=df.close.map(str)), parse_funding([ok]), 0, 0)  # text prices are fine
bad_candles = [df.iloc[:0], df.drop(idx[50:55]), df.iloc[::-1], pd.concat([df, df.iloc[-1:]]),
               df.tz_localize(None), df.assign(close=df.close.mask(df.index == idx[9], float("1e400"))),
               df.assign(close=df.close.mask(df.index == idx[9], "n/a"))]
bad_bodies = [{"code": -1121, "msg": "Invalid symbol."}, [{"fundingTime": 1}], [ok, ok],
              [ok | {"fundingRate": None}], [ok | {"fundingRate": "1e400"}],
              [ok, ok | {"fundingTime": 1735720200000}]]
for d in bad_candles:
    try: backtest(d, pd.Series(dtype=float), 0, 0)
    except ValueError: continue
    raise AssertionError("accepted bad candles")
for b in bad_bodies:
    try: backtest(df, parse_funding(b), 0, 0)
    except ValueError: continue
    raise AssertionError(f"accepted {repr(b)}")
print("all checks passed")
```

```
all checks passed
```

Printing each error confirmed that every case stops at its own check, not on an unrelated error.

## How fees, slippage and funding change a crypto backtest

Costs are charged per trade and per funding event, so a rule that trades often loses more to costs than the gross figure suggests.

The demo generates one year of synthetic hourly prices (log returns with mean 0 and standard deviation 0.6% per hour) and synthetic funding every 8 hours, passed through the same parser as exchange JSON.

```python
import numpy as np, pandas as pd
from bt import *

rng = np.random.default_rng(7)                     # synthetic data, no market
idx = pd.date_range("2025-01-01", periods=8760, freq="h", tz="UTC")
df = pd.DataFrame({"close": 100 * np.exp(np.cumsum(rng.normal(0, 0.006, 8760)))}, index=idx)
ft = pd.date_range("2025-01-01 08:00", periods=1095, freq="8h", tz="UTC")
funding = parse_funding([{"fundingTime": int(t.timestamp() * 1000) + 3, "fundingRate": f"{r:.6f}"}
                         for t, r in zip(ft, rng.normal(0.0001, 0.00005, 1095))])
r = backtest(df, funding, fee=0.001, slip=0.0005).sum()
p = backtest(df, funding, 0, 0, peek=True).sum()
print((100 * r[["gross", "fees", "slippage", "funding"]]).round(2).to_dict(), int(r.trades))
print("peek=True, no costs:", round(100 * p.gross, 2))
```

```
{'gross': -8.9, 'fees': -33.8, 'slippage': -16.9, 'funding': -4.38} 338
peek=True, no costs: 243.86
```

**Synthetic data, seed 7, generated 26 November 2026; summed bar returns, not compounded**

| Step | Result | Change |
| --- | ---: | --- |
| No costs | −8.90% | – |
| Fees 0.10% per side, 338 sides | −42.70% | −33.80 points |
| Slippage 0.05% per side | −59.60% | −16.90 points |
| Funding at 1,095 funding times | −63.98% | −4.38 points |
| Same-bar signal (look-ahead), no costs | +243.86% | bug, not a result |

The 0.10% fee matches the 0.100% maker and taker rate Binance's fee schedule showed for regular spot users on 26 November 2026; use the rate your account pays. The 0.05% slippage is an assumption.

> **Hypothetical.** At 0.10% fee and 0.05% slippage per side, a round trip costs 0.30%. 169 round trips (338 sides) cost 50.7 points before funding, which the gross result must exceed just to reach zero.

## Funding rates in a perpetual futures backtest

Funding is a cash flow between longs and shorts at set times, so a perpetual futures backtest charges it on the positions held then, not as a fee.

Binance's funding FAQ (updated 6 March 2026, read 26 November 2026) gives the funding amount as nominal value (mark price times size) times the funding rate. Longs pay shorts when the rate is positive, shorts pay longs when it is negative, the default times are 00:00, 08:00 and 16:00 UTC, and a position closed before the funding time pays nothing. The page also notes a timing deviation of about 15 seconds, so test a trade at the funding time both ways.

- **Do not hardcode 8 hours.** `GET /fapi/v1/fundingInfo` lists symbols with an adjusted `fundingIntervalHours`, and the FAQ describes moves to one-hour settlement when the rate hits its cap or floor (both read 26 November 2026); the code reads timestamps from the data.
- **Page the history.** `GET /fapi/v1/fundingRate` takes `limit`, default 100, maximum 1000, yet the same page says that without `startTime` and `endTime` the most recent 200 records are returned. Send an explicit range and limit, and check what came back: the code charges zero where no record exists, so a history cut short looks like free funding.
- **Funding times can be off the hour.** The demo adds 3 ms; the code rounds to the nearest hour, so a few milliseconds either side lands on the same bar, and refuses two events in one bar instead of keeping the last.

See [perpetual futures and funding rate](https://fincodelabs.com/en/blog/perpetual-futures-funding-rate) and [funding rate history API](https://fincodelabs.com/en/blog/funding-rate-history-api). Naming Binance here does not mean Fincode integrates it or has built on it. Article 99/A of Capital Markets Law No. 6362 treats activity by foreign crypto-asset platforms directed at Turkish residents as unauthorized.

## Look-ahead bias test in Python: change the future, watch the past

The most reliable look-ahead check is mechanical: change prices from bar t onward and confirm that the position held at bar t does not move.

In the demo, dropping the one-bar shift (`peek=True`) produced +243.86% on data with no edge. The `peeks()` function multiplies every close from bar t onward by 0.5 and 1.5 and compares the position at bar t; it flagged the missing shift and, in a separate run, a rule using `rolling(24, center=True)`, which per the pandas documentation labels each window at its center, so half the window lies in the future.

Resampling is another source: in the pandas 3.1.1 documentation read on 26 November 2026, `resample` labels and closes bins on the left for most frequencies, so an hourly bar labeled 10:00 holds data up to 11:00. Other forms of the bias, and survivorship and overfitting, are in [backtesting pitfalls](https://fincodelabs.com/en/blog/backtesting-trading-strategy-pitfalls).

## Exchange rules a crypto backtest skips

A backtest fills any quantity at any price, while the exchange rejects orders that break its symbol filters.

Binance's spot filter documentation, read on 26 November 2026, requires the price to be a multiple of `tickSize` (PRICE_FILTER), the quantity a multiple of `stepSize` (LOT_SIZE), and price times quantity to meet a minimum notional (MIN_NOTIONAL or NOTIONAL; flags decide whether it also applies to market orders). A backtest that trades fractions below the step, or exits a small remainder below the minimum, records impossible trades. Round quantities down to the step with `decimal.Decimal`, read the filters per symbol, and keep the leftover position in the books.

## Free crypto backtesting: what any platform or script cannot show

No free tool or paid platform can show how the rule would have been filled, or whether a past result will repeat.

The same code on seeds 0 to 99 of the same edgeless generator gave a no-cost result between −72.4% and +80.2% (5th to 95th percentile), positive in 60 of 100 runs; after all costs, 12 runs were still positive and 5 were above +22.4%. One backtest on one history is one draw; [Monte Carlo backtesting](https://fincodelabs.com/en/blog/monte-carlo-backtesting) shows how to describe that spread. Beyond noise, a backtest cannot show:

- queue position, partial fills and the market impact of your own orders;
- outages, maintenance, delistings and API errors during live trading;
- funding, fee tiers or symbol rules that change after the test period;
- a regime the history did not contain;
- whether the rule is allowed for your account, country and venue.

Automated trading can lose money, and a backtest does not guarantee future results. If you already have backtest code and want it checked for the faults above, Fincode's [trading bot code review](https://fincodelabs.com/en/services/trading-bot-code-review) page describes that work; Fincode does not supply strategies or settings.

Related guide: [Look-ahead bias in backtesting](https://fincodelabs.com/en/blog/look-ahead-bias) · [Survivorship bias in crypto](https://fincodelabs.com/en/blog/survivorship-bias-crypto).

## Frequently asked questions

### Can I backtest crypto strategies for free?

Yes. Python, pandas and NumPy are free, and some exchanges publish candles and funding history at no charge, though their licenses can restrict commercial use.

### Do spot backtests need funding?

No. Funding applies to perpetual futures positions; spot positions pay trading fees and spread, and margin borrowing has its own interest.

### How do I know my backtest has look-ahead bias?

Change the prices after a bar and rerun: if the position at that bar changes, the code used information it did not have yet.

### Is a profitable backtest proof that a strategy works?

No. On edgeless synthetic data, 12 of 100 runs were still positive after costs, and 5 showed more than +22.4%. A backtest result is one sample under assumptions.

## Sources

- [Binance Developers: USD-M futures Get Funding Rate History, GET /fapi/v1/fundingRate and fundingInfo, read 26 November 2026](https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Rate-History)
- [Binance FAQ: Introduction to Binance Futures Funding Rates, updated 6 March 2026, read 26 November 2026](https://www.binance.com/en/support/faq/introduction-to-binance-futures-funding-rates-360033525031)
- [Binance Developers: spot API filters (PRICE_FILTER, LOT_SIZE, MIN_NOTIONAL, NOTIONAL), read 26 November 2026](https://developers.binance.com/docs/binance-spot-api-docs/filters)
- [Binance fee schedule, regular user spot maker and taker rates, read 26 November 2026](https://www.binance.com/en/fee/schedule)
- [pandas 3.1.1 documentation: DataFrame.resample, closed and label defaults](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html)
- [pandas documentation: Series.rolling, center parameter](https://pandas.pydata.org/docs/reference/api/pandas.Series.rolling.html)

> This guide is general information about software and markets, not investment, legal or tax advice. Automated trading can lose money, past or backtested performance does not guarantee future results, and the rules that apply depend on your jurisdiction and your exchange's terms. Sources, checks and corrections: see the [editorial policy](https://fincodelabs.com/en/editorial-policy).

---

Published by Fincode (Fincode Yazılım ve Teknoloji A.Ş.), a software company in Istanbul, Turkey: https://fincodelabs.com/en/blog/crypto-backtesting-python

Cite as: Fincode, "Backtest a crypto strategy in Python: fees, funding, bias", updated November 26, 2026, https://fincodelabs.com/en/blog/crypto-backtesting-python
