Backtest in Python with Kibot CSVs: pandas, backtrader, vectorbt

Kibot files are plain CSV with no header row, so loading them is a few lines of pandas. This guide loads a real file, checks it, resamples it, and runs the same toy strategy in two backtesting libraries. Every line of code and every output block below was executed on October 9, 2026 against the free IBM 1-minute sample, which you can download from the free samples page (use the adjusted file and save it as IBM_1min.txt).

Environment used. Python 3.12 on Windows, pandas 3.0.6, backtrader 1.9.78.123, vectorbt 1.1.1, numpy 2.5.3. The strategy is a deliberately plain moving-average crossover. The results show that the plumbing works, not that the strategy does.

1. Load a minute file

The columns are Date, Time, Open, High, Low, Close, Volume (see the data format reference). Read date and time as text, then parse them together. Kibot stamps each bar with its open time, in US Eastern time unless you ordered another zone.

# load.py
import pandas as pd

COLS = ["date", "time", "open", "high", "low", "close", "volume"]

def load_kibot_minutes(path):
    df = pd.read_csv(path, header=None, names=COLS, dtype={"date": str, "time": str})
    ts = pd.to_datetime(df["date"] + " " + df["time"], format="%m/%d/%Y %H:%M")
    return df.drop(columns=["date", "time"]).set_index(ts.rename("datetime"))

Checks worth running on any file before trusting it (output below comes from running this on the IBM file):

df = load_kibot_minutes("IBM_1min.txt")
print(df.head(3))
print(len(df), "bars,", df.index.normalize().nunique(), "days")
print("first/last time of day:", df.index.time.min(), df.index.time.max())
print("bars per day (min/max):", df.groupby(df.index.normalize()).size().agg(["min", "max"]).tolist())
print("NaNs:", int(df.isna().sum().sum()), " monotonic:", df.index.is_monotonic_increasing,
      " dupes:", int(df.index.duplicated().sum()))
                       open    high     low   close  volume
datetime
2026-07-13 09:30:00  288.43  293.88  288.43  293.52  108452
2026-07-13 09:31:00  293.88  295.38  291.94  292.28   28903
2026-07-13 09:32:00  292.25  293.61  290.59  290.59   19380

24554 bars, 63 days
first/last time of day: 09:30:00 15:59:00
bars per day (min/max): [387, 390]
NaNs: 0  monotonic: True  dupes: 0

A regular session has 390 minutes, but the file has days with 387 to 389 bars: 51 of the 63 days are complete and 12 are not. Kibot writes a bar only for minutes in which something traded, so a quiet minute is simply absent. Do not assume a fixed number of rows per day. If your code needs every minute, reindex and forward-fill the close yourself, and decide what a missing minute means for your volume.

2. Resample to 5-minute bars

Use left-labelled, left-closed bins so a 5-minute bar keeps the open-time stamp that the 1-minute bars have:

from load import load_kibot_minutes

df = load_kibot_minutes("IBM_1min.txt")
five = df.resample("5min", label="left", closed="left").agg(
    {"open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum"}
).dropna()
print(five.head(3))
print(len(df), "1-minute bars ->", len(five), "5-minute bars")
                       open    high     low   close  volume
datetime
2026-07-13 09:30:00  288.43  295.38  288.43  290.47  184306
2026-07-13 09:35:00  290.65  291.59  289.94  290.41   59575
2026-07-13 09:40:00  290.49  290.58  288.97  290.22   43539

24554 1-minute bars -> 4914 5-minute bars

Kibot also sells 5-minute bars directly. Resampling yourself is useful when you want to keep one source file and change the bar size during research.

3. backtrader

backtrader's PandasData feed picks up columns named open, high, low, close and volume from a DataFrame with a datetime index, which is exactly what step 1 returns.

import backtrader as bt
from load import load_kibot_minutes

class SmaCross(bt.Strategy):
    params = dict(fast=10, slow=30)

    def __init__(self):
        fast = bt.ind.SMA(period=self.p.fast)
        slow = bt.ind.SMA(period=self.p.slow)
        self.cross = bt.ind.CrossOver(fast, slow)

    def next(self):
        if not self.position and self.cross > 0:
            self.buy()
        elif self.position and self.cross < 0:
            self.close()

df = load_kibot_minutes("IBM_1min.txt")
cerebro = bt.Cerebro()
cerebro.adddata(bt.feeds.PandasData(dataname=df, timeframe=bt.TimeFrame.Minutes, compression=1))
cerebro.addstrategy(SmaCross)
cerebro.addsizer(bt.sizers.FixedSize, stake=100)
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
cerebro.broker.setcash(100_000)
start = cerebro.broker.getvalue()
res = cerebro.run()[0]
ta = res.analyzers.ta.get_analysis()
print(f"start {start:,.2f}  end {cerebro.broker.getvalue():,.2f}  trades {ta.total.closed}")
start 100,000.00  end 93,015.97  trades 482

It ran in about 2.5 seconds. backtrader fills an order on the next bar's open.

4. vectorbt

import vectorbt as vbt
from load import load_kibot_minutes

df = load_kibot_minutes("IBM_1min.txt")
close = df["close"]
fast = vbt.MA.run(close, 10)
slow = vbt.MA.run(close, 30)
pf = vbt.Portfolio.from_signals(
    close,
    entries=fast.ma_crossed_above(slow),
    exits=fast.ma_crossed_below(slow),
    init_cash=100_000,
    size=100,
    size_type="amount",
    freq="1min",
)
print(f"end value {pf.final_value():,.2f}  trades {pf.trades.count()}  win rate {pf.trades.win_rate():.1%}")
end value 93,601.50  trades 483  win rate 32.7%

About 24 seconds on the first run, most of it numba compiling. The two libraries agree on the shape (about 480 trades, a loss of around 6.5 to 7 percent) and differ in the details: vectorbt fills at the close of the signal bar by default, backtrader at the next bar's open, and the trade counts differ by one.

5. What this toy ignores

  • No commission or slippage. At about 480 round trips on a stock, costs matter more than the signal.
  • The moving averages run straight through the overnight gap, so the first bars of each day mix yesterday's close with today's open. Reset the indicators each session, or add a session filter, if that matters to your idea.
  • The IBM file is split and dividend adjusted. For stock backtests that is usually what you want; see adjusted vs unadjusted data. For futures, a continuous contract is unadjusted and has a price jump at each roll (see Continuous Futures), which an indicator will read as a real move unless you handle rolls.
  • The free sample covers three months. Statistics from 63 days say very little.

6. Tick data with bid/ask

The tick-with-bid/ask layout is Date, Time, Price, Bid, Ask, Size. Run on the free IVE sample:

import pandas as pd

df = pd.read_csv("IVE_tick.txt", header=None,
                 names=["date", "time", "price", "bid", "ask", "size"],
                 dtype={"date": str, "time": str})
df.index = pd.to_datetime(df.pop("date") + " " + df.pop("time"), format="%m/%d/%Y %H:%M:%S")
print(df.head(3))
print(len(df), "ticks,", df.index.normalize().nunique(), "days, median spread",
      round((df.ask - df.bid).median(), 2))
                      price     bid     ask  size
2026-09-09 09:30:00  233.99  233.79  233.99  11606
2026-09-09 09:30:01  233.90  233.63  233.99    100
2026-09-09 09:30:01  233.83  233.79  233.99    100
40703 ticks, 22 days, median spread 0.02

Timestamps are to the second and several ticks share one, so keep the file order (it is chronological) rather than sorting by time alone. Quote sizes are not in the file.

Other engines

Any engine that reads a pandas DataFrame or a CSV can use the loader above. I did not run the other engines people ask about (NautilusTrader, zipline, LEAN), so this page does not claim they work with these files.

Get the data

Price your own slice, for example one futures root or a basket of stocks over the years you need, in the custom order builder; the price is shown before you pay. The free samples page has the files used here.

All guides