GhosalQuant
Ghosal Fund | Quantitative Trading Team Repository
An event-driven Python framework for backtesting and trading quantitative strategies. A strategy turns market events (bars, order books, public trades) into signals. The same strategy class runs on historical data, recorded sessions, a simulated broker or Interactive Brokers.
Documentation
- User Guide - writing strategies, configuring and running backtests, live trading, recording
- System Overview - component reference: core types, data sources, risk rules, brokers, configuration
Installation
Requires Python 3.10 or later.
Using a release
To write and backtest strategies, install the published package from PyPI:
pip install ghosalquant
Pin a version (pip install ghosalquant==0.1.0) to keep results reproducible, and pip install -U ghosalquant to
upgrade. Optional extras add integrations:
| Extra | Adds |
|---|---|
alpaca |
Alpaca market data (alpaca-py) |
plotting |
Equity curve and results charts (matplotlib, plotly) |
ui |
The prototype backtest GUI, launched with ghosalquant-ui |
pip install "ghosalquant[plotting,ui]"
API keys for Alpaca and Polygon are read from environment variables or a .env file beside your config (see
.env.example). They are refused if written
into the config file.
For developers
To work on the framework itself, clone the repository and install it in editable mode, so your changes take effect without reinstalling:
git clone https://github.com/Ghosal-Quants/GhosalQuant.git
cd GhosalQuant
pip install -e ".[plotting,ui]" pytest
python -m pytest tests --ignore=tests/legacy
Copy .env.example to .env and fill in any API keys you need.
Releases are published by CI: bump __version__ in src/ghosalquant/__init__.py, push to main, then publish a
GitHub release tagged with that version (e.g. v0.1.1). The workflow runs the tests, builds the package and uploads
it to PyPI, and fails if the tag and version don't match.
Quick Start
Subclass Strategy, return a Signal from on_market_data, and backtest it on any OHLCV DataFrame. This runs as is,
with no config file, network or API keys:
import numpy as np
import pandas as pd
from ghosalquant import Signal, SignalType, Strategy, metadata_keys
from ghosalquant.backtester import DataFrameBacktester
class Trend(Strategy):
"""Fully invested above the 50-day average, flat below it."""
def on_start(self):
self.closes = []
def on_end(self):
pass
def on_market_data(self, bar):
self.closes.append(bar.close)
if len(self.closes) < 50:
return None
weight = 1.0 if bar.close > np.mean(self.closes[-50:]) else 0.0
return Signal(
time_stamp=bar.time_stamp, symbol=bar.symbol, ref_price=bar.close,
signal_type=SignalType.BUY if weight else SignalType.SELL,
metadata={metadata_keys.TARGET_WEIGHT: weight},
)
# Two years of synthetic daily bars; any DataFrame with OHLCV columns works.
rng = np.random.default_rng(0)
close = 100 * np.exp(np.cumsum(rng.normal(0.0004, 0.012, 500)))
open_ = np.r_[100.0, close[:-1]] * np.exp(rng.normal(0.0, 0.003, 500))
df = pd.DataFrame(
{"Open": open_, "High": np.maximum(open_, close), "Low": np.minimum(open_, close),
"Close": close, "Volume": 1e6},
index=pd.bdate_range("2023-01-02", periods=500),
)
kpms = DataFrameBacktester(strategy=Trend(), dataframe=df, symbol="DEMO").run()
print(kpms)
run() returns a BacktestKPMs: trade counts and win rate, realised and unrealised P&L, open positions, fills, max
drawdown, annualised return and volatility, and the Sharpe, Sortino and Calmar ratios. total_trades counts closed
lots: one per lot, or part of a lot, that an opposite fill closed. The backtester also exposes equity_curve, and
plot_equity_curve (ghosalquant.util.visualisation, plotting extra) draws it.
Every signal needs a size: a quantity, a TARGET_WEIGHT (a share of equity) in its metadata, or a sizing rule
such as ConfidenceSizer in the risk rules. A signal with none of these is dropped, with a warning. A
TARGET_WEIGHT buy is capped at the cash not committed to resting buys, less RISK.cash_buffer (default 1%) of
equity.
A simulated market order fills at the next bar's open, with the broker's spread, slippage and impact applied.
Configuring a run
With no config you get a simulated broker and no risk rules. To change that, pass a Config:
from ghosalquant.util.config import BrokerConfig, Config, RiskConfig, RiskRuleConfig, SimBrokerConfig
config = Config(
broker=BrokerConfig(sim=SimBrokerConfig(spread_bps=5.0, commission_per_share=0.005)),
risk=RiskConfig(rules=[RiskRuleConfig("MaxOpenPositions", {"max_open_positions": 3})]),
)
kpms = DataFrameBacktester(strategy=Trend(), dataframe=df, config=config).run()
Or keep the same settings in YAML and pass config_path="config.yaml", or load it with Config.from_yaml; see
examples/config.yaml. Only SYSTEM
is required. To have the library load the bars too, set DATA (yfinance, polygon, live_ibkr or
live_alpaca), plus TIME_RANGE for the historical sources, and use
Backtester.from_config(strategy=Trend(), config_path="config.yaml").
Components
Strategies and execution
Strategyhandles bars (on_market_data).OrderBookStrategyhandles order books and prints (on_order_book,on_public_trade), with aStrategyContextholding the symbol's position, cash and resting orders. Optional hooks:on_fill,on_order_accepted,on_order_expired. A hook returnsNone, oneSignalor several.- A
Signalbecomes a market order, or a limit order when it setslimit_price, withliquiditydeclaring maker or taker. Metadata keys (ghosalquant.core.metadata_keys) carry the target weight, stop loss and take profit, order time to live, and replacement of resting orders. ExecutionSystemruns one event loop for backtests, paper and live trading. For each event it expires resting orders past their time to live, updates the broker, marks the portfolio, books fills, then sends the strategy's signals through the risk manager to the broker.- Signal sinks (
PrintSink,ListSink,DataFrameSink) receive every signal before the risk manager. AnExecutionSystemwith no risk manager, portfolio or broker only emits signals to them. - Benchmarks (
ghosalquant.bench):BenchmarkBuyAndHoldandBenchmarkTrendVolTarget(EMA trend with volatility targeting).
Data sources (ghosalquant.data_layer)
| Source | Provides |
|---|---|
DataFrameDataSource, ListDataSource |
Bars from a DataFrame; any events from a list |
YFinanceDataSource, YFinanceMultiDataSource |
Historical bars from yfinance, one or several symbols |
ParquetPolygonDataSource |
Polygon aggregates from a local parquet store, filtered to a session and resampled |
LivePolygonDataSource |
Polygon WebSocket: bars, quotes, trades |
LiveIBKRDataSource |
IBKR: bars, market depth, tick-by-tick trades, for equities and options |
LiveAlpacaDataSource |
Alpaca: bars, top-of-book quotes, trades, for equities and options (alpaca extra) |
DoltOptionsDataSource, CboeEODDataSource, NSEDataSource |
End-of-day option chains from DoltHub, Cboe DataShop and NSE bhavcopies |
RecordingDataSource, RecordedDataSource |
Record a stream to disk as it is consumed; replay a recording |
MergedDataSource (merge_datasources), ShockedDataSource |
Merge streams in time order; replay with shifted prices or thinned depth |
Brokers (ghosalquant.brokerage)
SimBroker: fills against bars, with spread, slippage, market impact, a cap on the share of bar volume, partial fills, rejections, latency and per-share commission, with an optional seed.OrderBookSimBroker: fills against L2 books. A taker sweeps displayed depth; a maker queues behind the displayed size at its price and fills when prints trade through it. Maker rebate, taker fee, lot size and order time to live are all configurable.IBKRBroker: paper and live trading throughib_insync. Sends market and limit orders for equities and options, persists submitted orders across restarts withstate_path, and returns cash and positions withaccount_snapshot().
Risk (ghosalquant.risk)
RiskManager turns a signal into an order through a chain of rules, each of which can resize or block it.
| Purpose | Rules |
|---|---|
| Sizing | ConfidenceSizer, SymbolCapitalFractionSizer, FractionalKellySizer, SignalQuantityCap |
| Limits | MaxOpenPositions, MaxSymbolExposure, CashAllocationRule, DrawdownKillSwitch, CorrelationFilter, RegimeFilter |
| Venue | IntegerQuantity, TickRounding |
Portfolio and valuation (ghosalquant.portfolio)
BasicPortfolio: signed positions, LIFO lots, commissions, de-duplication of fills byexecution_id, andadopt()to start from a live account's cash and positions. It refuses a buy fill it can't afford, with a warning.PortfolioValuationEngine: marked NAV, liquidation equity into displayed bids, and a risk equity capped at cost.hedginggives net delta and gamma per underlier and the hedge quantity;attributionsplits a position's change in value into its causes.
Contracts and options (ghosalquant.core)
ContractRegistryandContract: multiplier, option right, strike, expiry, and cash or physical settlement.settlement_fillssettles positions at expiry.blackscholes(price, greeks, implied volatility), andVolSurface/Smilebuilt from a chain.
Metrics (ghosalquant.metrics)
risk_adjusted_metrics(equity_curve, init_capital=...)for any equity curve.evaluate_gates(metrics, spec)for go/no-go checks on a set of metrics.
Recording and state
ghosalquant.recording: one durable stream per event kind. Each stream is a write-ahead log sealed into verified Parquet segments, with books stored only when they change and prints de-duplicated.ghosalquant.state: atomic JSON writes,VersionedJsonStateStore, and the SQLiteEventLog/EventStorejournal taken byExecutionSystem(journal=...).
Examples
Run as python examples/<file>. The yfinance examples plot with matplotlib (the plotting extra).
| File | Shows |
|---|---|
example_main.py |
DataFrameBacktester on yfinance AAPL bars with config.yaml |
example_comparison.py |
The example strategy against both benchmarks, equity curves overlaid |
example_order_book_strategy.py |
OrderBookStrategy on synthetic L2 books and prints with OrderBookSimBroker |
example_options_momentum.py |
Options from underlier bars and a quoted chain, with ContractRegistry, Kelly sizing and exposure caps |
example_non_backtesting.py |
ExecutionSystem on a live Polygon stream with simulated fills (needs POLYGON_API_KEY) |
example_ibkr.py |
IBKR live data and paper trading (needs TWS or IB Gateway running) |
config.yaml |
Every config section, commented |
Project Structure
src/ghosalquant/
core/ # Bar, OrderBook, PublicTrade, Signal, Order, Fill, Trade; contracts, Black-Scholes, vol surfaces
execution/ # Strategy, OrderBookStrategy, StrategyContext, ExecutionSystem, signal sinks
data_layer/ # Data sources, merging, shocks, recording; Polygon parquet store tools
backtester/ # Backtester, DataFrameBacktester
bench/ # Benchmark strategies
risk/ # RiskManager, risk rules, cash allocation, sizing helpers
portfolio/ # Portfolio protocol, BasicPortfolio, lots, marks, valuation, hedging, attribution
brokerage/ # Broker base, SimBroker, OrderBookSimBroker, IBKRBroker, fill and commission models
metrics/ # Risk-adjusted metrics, performance gates
recording/ # Recorders and segmented Parquet storage
state/ # Atomic JSON, versioned state store, SQLite event journal
util/ # Config, visualisation, KPM calculation, tick rounding
backtest_ui/ # Prototype GUI (the ui extra)
compatibility/ # Deprecated LegacyBacktester
examples/ # Example scripts and a commented config.yaml
design/ # User guide, system overview, diagrams
tests/ # pytest suite
Metadata
Release files for ghosalquant 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ghosalquant-0.1.1.tar.gz | 225.1 kB | With provenance | Details for ghosalquant-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ghosalquant-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for ghosalquant-0.1.1-py3-none-any.whl |
Total release size: 408.5 kB
Release files / ghosalquant-0.1.1.tar.gz
| Download URL | ghosalquant-0.1.1.tar.gz |
|---|---|
| Size | 225.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d4ec69acb947e038ccc59664dd8e958f5248d4edf43f2230232d8510d2603471
|
|
BLAKE2b-256 checksum How to use checksums |
dbd17384cc466e5e6e6743db7789e5de18c4cac49e9e8dafd92570815a442806
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logRelease files / ghosalquant-0.1.1-py3-none-any.whl
| Download URL | ghosalquant-0.1.1-py3-none-any.whl |
|---|---|
| Size | 183.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d4de4b7d3a74231c659730cc1e0e6edf0584c5831df3c1237b289d909a98f53b
|
|
BLAKE2b-256 checksum How to use checksums |
daa33d046ce846231172a124ea5b884af8b3c2e4d2861cfe59e0cab979ff0dab
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logSecurity for ghosalquant 0.1.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ghosalquant-0.1.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.