Skip to main content

A Python quantitative trading framework — data, factors, backtesting, and live execution.

Project description

DeltaFQ - Quantitative Trading Framework

DeltaFQ is a Python quantitative trading library covering the full workflow: data sourcing → factor research → portfolio construction → order execution → performance evaluation.

Features

  • Data Layer — Unified data sourcing with abstract provider interface, CSV/Parquet local storage, MultiIndex DataFrame (date, asset)
  • Factor Engine — Factor base class, common alphas (momentum, reversal, volatility, turnover), custom factor expression algebra
  • Portfolio Management — Weight optimization, rebalancing, constraint solving
  • Risk Modeling — Covariance estimation, VaR/CVaR, attribution analysis
  • Backtesting — Event-driven engine, slippage/commission/market-impact simulation, daily and intraday support
  • Paper Trading — Simulated broker with market/limit/stop orders, configurable slippage and commission
  • Live Trading — Broker adapter base class for real-market execution (CTP, IB, Binance, etc.)
  • Performance Evaluation — Sharpe/Calmar/Max-Drawdown, IC/IR analysis, turnover tracking

Installation

pip install -e .

Usage Guide

1. Load Data

from deltafq.core.data import DataFrameSource, CSVDataSource

# From in-memory DataFrame (requires date, asset, close columns at minimum)
src = DataFrameSource(df, name="mydata")
prices = src.get_close()         # wide (date x asset) DataFrame
returns = src.get_returns()      # daily returns
print(src.assets)                # ['AAPL', 'GOOG', ...]

# From CSV
src = CSVDataSource("data/daily_prices.csv")
df = src.load()                  # canonical (date, asset) MultiIndex

2. Compute Factors

from deltafq.core.factor import (
    MomentumFactor, ReversalFactor, VolatilityFactor,
    RSI, MACD, cross_sectional_zscore, rank_normalize,
)

# Single factor
mom = MomentumFactor(window=20)
raw = mom.compute(prices)        # (date x asset) factor matrix

# Cross-sectional normalization
z = cross_sectional_zscore(raw)  # z-score per date
r = rank_normalize(raw)          # percentile rank, scaled to [-1, 1]

# Factor algebra
combo = 0.5 * MomentumFactor(20) + 0.3 * ReversalFactor(5)
signal = combo.compute(prices)

3. Build Portfolio

from deltafq.core.portfolio import signal_weight, mean_variance, rebalance

# Signal-to-weight (auto clip + redistribute + normalize)
target_w = signal_weight(signal.iloc[-1], long_only=True, max_weight=0.10)

# Mean-variance optimization
target_w = mean_variance(returns.mean(), returns.cov(), risk_aversion=2.0)

# Rebalance (compute required trades + turnover control)
result = rebalance(target_w, current_w, max_turnover=0.3)
print(result.trades)             # buy/sell orders
print(result.turnover)           # actual one-way turnover

4. Risk Management

from deltafq.core.risk import (
    shrinkage_covariance, historical_var, historical_cvar,
    portfolio_volatility, factor_exposure_attribution,
)

cov = shrinkage_covariance(returns, window=252, shrinkage=0.2)
var95 = historical_var(returns["AAPL"], confidence=0.95)
cvar95 = historical_cvar(returns["AAPL"], confidence=0.95)
vol = portfolio_volatility(target_w, cov)

5. Backtest — Full Pipeline

from deltafq.core.backtest import BacktestEngine, BacktestConfig
from deltafq.core.factor import MomentumFactor, cross_sectional_zscore
from deltafq.core.portfolio import signal_weight

engine = BacktestEngine(BacktestConfig(
    initial_capital=1_000_000,
    commission_rate=0.0003,
    slippage_bps=1.0,
))

def my_strategy(date, history):
    """Called at each bar. Receives (timestamp, {asset: price_series})."""
    prices = pd.DataFrame({a: h for a, h in history.items()})
    factor = MomentumFactor(20).compute(prices)
    z = cross_sectional_zscore(factor).iloc[-1]
    return signal_weight(z, long_only=True, max_weight=0.10).to_dict()

result = engine.run(prices, my_strategy)

print(result.equity_curve.tail())         # daily equity
print(result.metrics["sharpe_ratio"])     # annualized Sharpe
print(result.metrics["max_drawdown"])     # max drawdown
print(len(result.trades))                 # total fills

6. Paper Trading

from deltafq.trading import PaperBroker
from deltafq.trading.broker import Order, OrderSide, OrderType

broker = PaperBroker(initial_capital=500_000, slippage=2.0)
broker.load_market_data("AAPL", aapl_ohlcv)

# Market order
order = Order(asset="AAPL", side=OrderSide.BUY, order_type=OrderType.MARKET, quantity=100)
result = broker.submit_order(order)
print(result.status, result.avg_fill_price)

# Limit order (fills automatically when price crosses)
limit = Order(
    asset="AAPL", side=OrderSide.BUY, order_type=OrderType.LIMIT,
    quantity=200, limit_price=148.0,
)
broker.submit_order(limit)
broker.step(timestamp)                   # advance simulation, check triggers

# Account snapshot
acc = broker.get_account()
print(acc.cash, broker.get_positions())

7. Evaluate Performance

from deltafq.core.evaluation import performance_report

report = performance_report(
    returns=daily_returns,
    equity=equity_curve,
    factor=factor_matrix,                # optional: IC analysis
    forward_returns=fwd_returns,         # optional: IC analysis
    weights=weights_history,             # optional: turnover analysis
)
print(report["sharpe_ratio"], report["max_drawdown"], report["calmar_ratio"])

8. Top-Level Imports

from deltafq import (
    BacktestEngine, BacktestConfig,        # backtest
    MomentumFactor, cross_sectional_zscore,# factor
    PaperBroker,                            # trading
    performance_report, sharpe_ratio,       # evaluation
)

Project Structure

deltafq/               # Core library
  core/                # Quant modules (data, factor, portfolio, risk, backtest, evaluation)
  trading/             # Execution layer (broker, paper, live)
  utils/               # Shared utilities
  examples/            # Usage examples & notebooks
tests/                 # Unit tests (91 passed, 1 skipped)
docs/                  # Documentation

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

deltafq_crixus-0.1.0.tar.gz (31.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

deltafq_crixus-0.1.0-py3-none-any.whl (25.9 kB view details)

Uploaded Python 3

File details

Details for the file deltafq_crixus-0.1.0.tar.gz.

File metadata

  • Download URL: deltafq_crixus-0.1.0.tar.gz
  • Upload date:
  • Size: 31.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for deltafq_crixus-0.1.0.tar.gz
Algorithm Hash digest
SHA256 93369a78907d558a7ff3ceb0f6fc22078bae2bbc71fb190e64a7235126e5e0df
MD5 0d7f5c33080e1a26749cdf4d0f1fa809
BLAKE2b-256 f6b0c81f85cba9216ce682a05b9096035566f30b1c7e45f1ca0cd8c4102770c1

See more details on using hashes here.

File details

Details for the file deltafq_crixus-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: deltafq_crixus-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 25.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for deltafq_crixus-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 56c8a0f6ea4c917fc01f9bb4b9b34305fa233d88904c24763f9fbdfa640814e7
MD5 5a7cd11baf96c5a32194f426d15fdcfb
BLAKE2b-256 33b611f63b594b3b1e61d648492d51206afb986c46c03ac2f70f6525a0cff47a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page