Ashutosh0x
QuantHedgeFund
Python

A Python-powered Quant Hedge Fund System with automated data ingestion, backtesting, and trade execution using MLflow, Luigi, Prefect, and Interactive Brokers

Last updated Jun 13, 2026
20
Stars
12
Forks
0
Issues
0
Stars/day
Attention Score
63
Language breakdown
No language data available.
โ–ธ Files click to expand
README

Quant Hedge Fund System

Python DuckDB MLflow Streamlit Prefect IB

A complete Python-powered algorithmic trading system for building and running your own quant hedge fund

Gemini<em>Generated</em>Image_wl6okgwl6okgwl6o image image https://github.com/user-attachments/assets/0a2bbe6c-188f-41e2-9080-8c016b3c9743

Table of Contents


Overview

The Quant Hedge Fund System is a comprehensive, end-to-end algorithmic trading platform that automates the entire investment process:
  • Data Collection - Download and store 25+ years of market data and fundamentals
  • Research & Backtesting - Test trading strategies with professional-grade analytics
  • Experiment Tracking - Log all experiments with MLflow for reproducibility
  • Automated Execution - Execute trades automatically via Interactive Brokers
  • Real-time Monitoring - Track performance with a live dashboard
This system is based on the Quant Science production architecture, designed to bring institutional-quality tools to individual investors and traders.

Who Is This For?

  • Python developers interested in algorithmic trading
  • Quantitative analysts looking for a complete research framework
  • Retail traders who want to systematize their investment process
  • Data scientists exploring financial applications of ML

What Makes This Different?

Unlike simple trading bots, this is a full quant infrastructure: | Feature | Simple Bot | This System | |---------|------------|-------------| | Data Management | CSV files | DuckDB columnar database with billions of rows | | Backtesting | Single strategy | Multi-factor with parameter sweeps | | Tracking | None | MLflow with 88+ metrics per run | | Automation | Manual | Luigi + Prefect orchestration | | Execution | Basic orders | Portfolio rebalancing with risk controls |

Why This Matters in 2025

The financial markets in 2025 demand a new level of sophistication:
  • AI-Driven Markets - Institutional players now use advanced ML models. This system levels the playing field with AI Agent integration (Grok/Llama 3), XGBoost, and MLflow experiment tracking.
  • High-Frequency Data - Markets move faster than ever. DuckDB handles 900M+ rows efficiently, enabling analysis that would crash traditional tools.
  • Volatility & Uncertainty - Factor-based strategies like QSMOM have historically outperformed during volatile periods by capturing momentum while avoiding short-term noise.
  • Regulatory Complexity - Full audit trails via MLflow ensure every backtest is reproducible and documented.
  • Cost Efficiency - No expensive Bloomberg terminals or proprietary platforms. This is 100% open-source Python running on your own infrastructure.
Key 2025 Market Advantages: | Challenge | How This System Helps | |-----------|----------------------| | Rising interest rates | Factor backtesting across multiple rate regimes (2015-2025) | | AI/Tech sector rotations | Universe screening filters 500+ stocks by liquidity and sector | | Increased retail participation | Automated rebalancing removes emotional decision-making | | Geopolitical risk | Risk controls and position limits protect against drawdowns | | Information overload | Streamlit dashboard surfaces only actionable signals |

Architecture

The system follows a layered architecture with clear separation of concerns:
graph TB
 subgraph Monitoring[" MONITORING LAYER"]
 Dashboard["Streamlit Dashboard"]
 MLflowUI["MLflow UI"]
 end

 subgraph Orchestration[" ORCHESTRATION LAYER"]
 Luigi["Luigi<br/>(Development)"]
 Prefect["Prefect<br/>(Production)"]
 end

 subgraph Core[" CORE LAYERS"]
 subgraph Data["DATA LAYER<br/>(QS Connect)"]
 FMP["FMP API"]
 DuckDB["DuckDB"]
 Cache["Parquet Cache"]
 Bundle["Zipline Bundler"]
 end

 subgraph Research["RESEARCH LAYER<br/>(QS Research)"]
 Factors["Factor Engine"]
 Backtest["Backtester"]
 MLflow["MLflow Tracking"]
 Strategies["Strategies"]
 end

 subgraph Execution["EXECUTION LAYER<br/>(Omega)"]
 IB["IB API"]
 Orders["Order Management"]
 Positions["Positions"]
 Risk["Risk Controls"]
 end
 end

 Dashboard --> Backtest
 MLflowUI --> MLflow
 Luigi --> Data
 Luigi --> Research
 Luigi --> Execution
 Prefect --> Data
 Prefect --> Research
 Prefect --> Execution
 Data <--> Research
 Research --> Execution

 style Dashboard fill:#FF4B4B,color:#fff
 style MLflowUI fill:#0194E2,color:#fff
 style Luigi fill:#1f77b4,color:#fff
 style Prefect fill:#024DFD,color:#fff
 style DuckDB fill:#FFF000,color:#000
 style MLflow fill:#0194E2,color:#fff
 style IB fill:#CC0000,color:#fff

Data Flow

flowchart LR
 A[(" FMP API")] --> B[(" Parquet Cache")]
 B --> C[(" DuckDB")]
 C --> D[(" Zipline Bundle")]
 D --> E[(" Backtest")]
 E --> F[(" MLflow")]
 F --> G[(" Omega")]
 G --> H[(" Interactive Brokers")]

 style A fill:#1f77b4,color:#fff
 style C fill:#FFF000,color:#000
 style F fill:#0194E2,color:#fff
 style H fill:#CC0000,color:#fff
  • FMP API: Financial Modeling Prep provides market and fundamental data
  • Parquet Cache: Raw API responses cached as compressed columnar files
  • DuckDB: High-performance analytical database for fast queries
  • Zipline Bundle: Data formatted for the Zipline backtesting engine
  • Backtest: Strategy executed historically with realistic simulation
  • MLflow: Results logged with full configuration reproducibility
  • Omega: Winning strategy positions converted to orders
  • Interactive Brokers: Orders executed in the live market

Features

Data Layer (QS Connect)

| Feature | Description | |---------|-------------| | Bulk Price Download | Download historical OHLCV data for thousands of symbols | | Fundamental Data | Income statements, balance sheets, cash flows, ratios | | DuckDB Storage | Columnar database handling 900M+ rows efficiently | | Parquet Caching | Delta detection to avoid re-downloading data | | Zipline Bundler | One-line command to create Zipline data bundles | | Rate Limiting | Automatic API rate limiting with retries |

Real-Time Layer (TIP-Search)

| Feature | Description | |---------|-------------| | Latency Profiling | Offline profiling of model inference times (P99 latency) | | Deadline Awareness | Filters models that cannot meet the strict nanosecond deadline | | Accuracy Maximization | Selects the most accurate valid model dynamically | | O(K) Scheduling | Constant-time decision making for low-latency loops | | Performance | Benchmarked scheduler overhead of ~84ยตs (0.08ms) per decision | | Task Abstraction | Unified InferenceTask interface for all market events |

Research Layer (QS Research)

| Feature | Description | |---------|-------------| | Factor Engine | Momentum, value, quality factor calculations | | Preprocessing | Universe screening, outlier removal, data cleaning | | Backtest Runner | Run strategies with configurable parameters | | Parameter Sweeps | Test 100s of parameter combinations automatically | | MLflow Integration | Log 88+ metrics for every backtest run | | Tear Sheets | Professional reports for returns, factors, transactions | | XGBoost Integration | Machine learning enhanced factor strategies | | LLM Strategy Generator | AI-powered regime analysis and parameter tuning via Groq |

Execution Layer (Omega)

| Feature | Description | |---------|-------------| | IB Connection | Connect to Interactive Brokers Gateway | | ordertargetpercent() | Rebalance to target portfolio weights | | Position Tracking | Monitor current holdings | | Order Management | Submit, modify, cancel orders | | Zipline Converter | Convert backtest outputs to live orders |

Orchestration Layer

| Feature | Description | |---------|-------------| | Luigi DAGs | Lightweight task orchestration for development | | Prefect Flows | Production-grade nightly automation | | Dependency Graphs | Tasks execute in correct order | | Retry Logic | Automatic retry on failures | | Resource Locking | Prevent concurrent database writes |

Dashboard (Operational Control Plane)

| Feature | Description | |---------|-------------| | Live Ops | Real-time performance metrics, live candle charts, and P&L tracking | | Emergency Controls | Backend-enforced HALT/RESUME trading with persistent state | | Authentication | Password-protected access (configurable) | | Light/Dark Theme | Toggle between dark mode and light mode with sun/moon button | | Market Profile | Volume profile chart with configurable lookback periods | | AI Insight Engine | New: Real-time Grok-powered market analysis (Summary, Regime, Risk, Levels) | | Governance Audit | Immutable audit trail for strategy approvals | | Drift Monitoring | Track strategy performance drift in real-time | | Ops Reporting | Generate daily operational reports |

Real-Time Data Feed

| Feature | Description | |---------|-------------| | Twelve Data WebSocket | Free real-time streaming for stocks, forex, and crypto | | Mock Feed | Simulated data feed for testing without API keys | | Candle Aggregator | Tick-to-candle conversion with 1-minute bars | | Truth Layer | Deterministic bar-close synchronization |

AI Insight Layer (Omega AI)

| Feature | Description | |---------|-------------| | AI Agent | Powered by Grok (Llama 3 70B) via groq client | | Market Summary | Natural language commentary on price action and momentum | | Regime Detection | Classifies market state (Trend, Range, Breakout, Volatility) | | Risk Guardrail | Pre-trade risk assessment based on spread, liquidity, and vol | | Trade Levels | Automated Stop-Loss and Take-Profit suggestions based on ATR/VWAP |

Project Structure

QuantHedgeFund/
โ”‚
โ”œโ”€โ”€ config/                # Configuration and settings
โ”‚   โ”œโ”€โ”€ init.py        # Module exports
โ”‚   โ”œโ”€โ”€ settings.py        # Pydantic settings management
โ”‚   โ”œโ”€โ”€ constants.py       # Enums and default parameters
โ”‚   โ””โ”€โ”€ logging_config.py  # Loguru logging setup
โ”‚
โ”œโ”€โ”€ qsconnect/             # DATA LAYER
โ”‚   โ”œโ”€โ”€ init.py        # Main Client import
โ”‚   โ”œโ”€โ”€ client.py          # Primary data interface
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ”œโ”€โ”€ base_client.py # Rate-limited HTTP client
โ”‚   โ”‚   โ””โ”€โ”€ fmp_client.py  # FMP API implementation
โ”‚   โ”œโ”€โ”€ database/
โ”‚   โ”‚   โ””โ”€โ”€ duckdb_manager.py # Database operations
โ”‚   โ”œโ”€โ”€ cache/
โ”‚   โ”‚   โ””โ”€โ”€ cache_manager.py  # Parquet caching
โ”‚   โ”œโ”€โ”€ bundle/
โ”‚   โ”‚   โ””โ”€โ”€ zipline_bundler.py # Zipline bundle creation
โ”‚   โ””โ”€โ”€ utils/
โ”‚       โ””โ”€โ”€ paths.py       # Path utilities
โ”‚
โ”œโ”€โ”€ qsresearch/            # RESEARCH LAYER
โ”‚   โ”œโ”€โ”€ init.py
โ”‚   โ”œโ”€โ”€ features/
โ”‚   โ”‚   โ”œโ”€โ”€ momentum.py    # QSMOM factor
โ”‚   โ”‚   โ”œโ”€โ”€ forward_returns.py # ML target creation
โ”‚   โ”‚   โ”œโ”€โ”€ factor_engine.py   # Factor computation engine
โ”‚   โ”‚   โ””โ”€โ”€ technical_indicators.py # pandas-ta integration
โ”‚   โ”œโ”€โ”€ preprocessors/
โ”‚   โ”‚   โ”œโ”€โ”€ price_preprocessor.py # Data cleaning
โ”‚   โ”‚   โ””โ”€โ”€ universe_screener.py  # Stock filtering
โ”‚   โ”œโ”€โ”€ realtime/          # REAL-TIME LAYER (TIP-Search)
โ”‚   โ”‚   โ”œโ”€โ”€ scheduler.py   # O(K) Inference Scheduler
โ”‚   โ”‚   โ”œโ”€โ”€ tasks.py       # Real-time Task definitions
โ”‚   โ”‚   โ””โ”€โ”€ models.py      # Latency-aware Model wrappers
โ”‚   โ”œโ”€โ”€ backtest/
โ”‚   โ”‚   โ”œโ”€โ”€ run_backtest.py # Main backtest runner
โ”‚   โ”‚   โ”œโ”€โ”€ parameter_sweep.py # Iterative sweeps
โ”‚   โ”‚   โ””โ”€โ”€ strategy_artifacts.py # Manifest generation
โ”‚   โ”œโ”€โ”€ portfolio_analysis/
โ”‚   โ”‚   โ”œโ”€โ”€ performance_metrics.py # 88+ metrics
โ”‚   โ”‚   โ””โ”€โ”€ tear_sheets.py # HTML reports
โ”‚   โ””โ”€โ”€ strategies/
โ”‚       โ””โ”€โ”€ factor/
โ”‚           โ”œโ”€โ”€ algorithms.py # Signal generation
โ”‚           โ””โ”€โ”€ config.py     # Strategy configs
โ”‚
โ”œโ”€โ”€ omega/                 # EXECUTION LAYER
โ”‚   โ”œโ”€โ”€ init.py
โ”‚   โ”œโ”€โ”€ trading_app.py     # IB trading interface
โ”‚   โ””โ”€โ”€ utils/
โ”‚       โ””โ”€โ”€ omegatradesconverter.py
โ”‚
โ”œโ”€โ”€ workflow/              # LUIGI ORCHESTRATION
โ”‚   โ”œโ”€โ”€ dags/
โ”‚   โ”‚   โ””โ”€โ”€ 01ingestdata.py # Complete DAG
โ”‚   โ””โ”€โ”€ luigi.cfg          # Luigi configuration
โ”‚
โ”œโ”€โ”€ automation/            # PREFECT ORCHESTRATION
โ”‚   โ”œโ”€โ”€ prefect_flows.py   # Production flows
โ”‚   โ””โ”€โ”€ deployment_manager.py # Model promotion
โ”‚
โ”œโ”€โ”€ dashboard/             # STREAMLIT UI
โ”‚   โ””โ”€โ”€ app.py             # Main dashboard
โ”‚
โ”œโ”€โ”€ scripts/               # UTILITIES
โ”‚   โ”œโ”€โ”€ setup_database.py       # Initialize DB
โ”‚   โ”œโ”€โ”€ downloadinitialdata.py # First data download
โ”‚   โ”œโ”€โ”€ start_dashboard.py      # Launch dashboard
โ”‚   โ””โ”€โ”€ simulaterealtimeinference.py # TIP-Search simulation
โ”‚
โ”œโ”€โ”€ .env.example           # Environment template
โ”œโ”€โ”€ .gitignore             # Git ignore rules
 requirements.txt # Python dependencies
 pyproject.toml # Project metadata
 README.md # This file
 docs/
 DOCUMENTATION.md # Detailed documentation

Quick Start

Prerequisites

  • Python 3.10+ (3.11 or 3.12 recommended)
  • Interactive Brokers account (optional, for live trading)
  • 8GB+ RAM recommended for large datasets

Step 1: Clone and Setup

# Clone the repository
git clone https://github.com/your-username/QuantHedgeFund.git
cd QuantHedgeFund

Create virtual environment

python -m venv venv

Activate (Windows)

venv\Scripts\activate

Activate (macOS/Linux)

source venv/bin/activate

Install dependencies

pip install -r requirements.txt

Step 2: Configure Environment

# Copy environment template
cp .env.example .env

Edit .env and add your API keys

Required: FMPAPIKEY

Optional: OPENAIAPIKEY (for AI features)

Example .env file:
# API Keys
FMPAPIKEY=yourfmpapikeyhere
GROKAPIKEY=yourgrokapikeyhere # Required for AI features

Database

DUCKDB_PATH=data/quantdb.duckdb

MLflow

MLFLOWTRACKINGURI=http://127.0.0.1:5050 MLFLOWEXPERIMENTNAME=Momentum Factor Strategy

Step 3: Initialize Database

python scripts/setup_database.py
This creates:
  • DuckDB database with schema
  • Required directories (data/, logs/, cache/)

Step 4: Download Data

python scripts/downloadinitialdata.py
This downloads:
  • Historical price data (2015-present)
  • Fundamental data (optional, takes longer)
  • Creates Zipline bundle

Step 5: Initialize Database & Run Dashboard

# Initialize the database schema (required first time)
python scripts/init_db.py

Start the dashboard

python scripts/start_dashboard.py
Open http://localhost:8501 in your browser. Login Credentials:
  • Password: quant123 (default, change in dashboard/app.py for production)

Step 5b: Start Real-Time Data Feed (Optional)

For live market data, run ONE of these:
# Option A: Twelve Data (Free real-time API)
python scripts/starttwelvedatafeed.py

Option B: Mock Feed (For testing without API)

python scripts/startmockfeed.py

Step 6: Start MLflow (Optional)

mlflow server --port 5050
Open http://localhost:5050 to view experiments.

Configuration

Environment Variables

| Variable | Description | Required | |----------|-------------|----------| | FMPAPIKEY | Financial Modeling Prep API key | | | DATALINKAPIKEY | Datalink API key (alternative data) | | | OPENAIAPIKEY | OpenAI API for AI Quant Team | | | DUCKDB_PATH | Path to DuckDB database file | | | CACHE_DIR | Directory for parquet cache | | | LOG_DIR | Directory for log files | | | MLFLOWTRACKINGURI | MLflow server URL | | | MLFLOWEXPERIMENTNAME | Default experiment name | | | IB_HOST | Interactive Brokers Gateway host | | | IB_PORT | IB Gateway port (7497 paper, 7496 live) | | | IBCLIENTID | IB client identifier | |

Strategy Configuration

Strategies are configured via Python dictionaries. See qsresearch/strategies/factor/config.py:
MOMENTUMFACTORCONFIG = {
 # MLflow settings
 "experiment_name": "Momentum Factor Strategy",
 "runname": "qsmomequalweightlong_only",
 
 # Backtest parameters
 "bundlename": "historicalprices_fmp",
 "start_date": "2015-01-01",
 "end_date": "2025-02-14",
 "capitalbase": 1000_000,
 
 # Preprocessing pipeline
 "preprocessing": [
 {
 "name": "price_preprocessor",
 "params": {"mintradingdays": 504}
 },
 {
 "name": "universe_screener",
 "params": {"volumetopn": 500}
 },
 ],
 
 # Factor calculation
 "factors": [
 {
 "name": "momentum_factor",
 "params": {
 "fast_period": 21, # 1 month
 "slow_period": 252, # 1 year
 "signal_period": 126, # 6 months
 }
 },
 ],
 
 # Algorithm
 "algorithm": {
 "callable": "usefactoras_signal",
 "params": {"top_n": 20}
 },
 
 # Portfolio construction
 "portfolio_strategy": {
 "func": "longshortequalweightportfolio",
 "params": {
 "numlongpositions": 20,
 "numshortpositions": 0, # Long only
 }
 },
}

Components Deep Dive

QS Connect (Data Layer)

QS Connect is your single source of truth for all market data. It handles: Connecting to APIs:
from qsconnect import Client

client = Client() # Uses environment variables

Or pass keys directly

client = Client(fmpapikey="your_key")
Downloading Price Data:
# Download bulk historical prices
prices = client.bulkhistoricalprices(
 start_date=date(2015, 1, 1),
 end_date=date.today(),
)

Data is automatically cached to parquet and stored in DuckDB

print(f"Downloaded {len(prices)} records")
Downloading Fundamental Data:
# Download income statements, balance sheets, etc.
client.fetchbulkfinancial_statements(
 statement_type=[
 "income-statement",
 "balance-sheet-statement",
 "cash-flow-statement",
 "ratios"
 ],
 periods="all", # annual + quarterly
 start_year=2000,
 end_year=2025,
)
Querying the Database:
# Direct SQL queries
df = client.query("""
 SELECT symbol, date, close, volume
 FROM prices
 WHERE symbol = 'AAPL'
 AND date >= '2024-01-01'
 ORDER BY date
""")
Building Zipline Bundles:
# Create a bundle for backtesting
client.buildziplinebundle("historicalpricesfmp")
client.registerbundle("historicalprices_fmp")
client.ingestbundle("historicalprices_fmp")

QS Research (Research Layer)

QS Research provides the framework for developing and testing strategies. Running a Backtest:
from qsresearch.backtest import run_backtest
from qsresearch.strategies.factor.config import MOMENTUMFACTORCONFIG

Run backtest with full MLflow logging

results = run_backtest( config=MOMENTUMFACTORCONFIG, logtomlflow=True )

Access metrics

print(f"Total Return: {results['metrics']['portfoliototalreturn']:.2%}") print(f"Sharpe Ratio: {results['metrics']['portfoliodailysharpe']:.2f}") print(f"Max Drawdown: {results['metrics']['portfoliomaxdrawdown']:.2%}")
Calculating Factors:
from qsresearch.features.momentum import addqsmomfeatures

Add momentum factor to price data

dfwithfactors = addqsmomfeatures( prices_df, fast_period=21, slow_period=252, signal_period=126 )

The factor column is named: closeqsmom21252126

Running Parameter Sweeps:
from qsresearch.backtest.parametersweep import runiterative_sweep

sweep_config = {
 "param_grid": {
 "fast_period": [21, 42, 63],
 "slow_period": [126, 252, 504],
 "top_n": [10, 20, 30],
 }
}

results = runiterativesweep(
 sweepconfig=sweepconfig,
 experimentname="MomentumFactorIterativeSweep"
)

Find best combination

best = max(results, key=lambda x: x["sharpe_ratio"]) print(f"Best params: {best['params']}")

Omega (Execution Layer)

Omega connects your strategies to interactive Brokers. Connecting:
from omega import TradingApp

app = TradingApp(paper_trading=True) # Use paper account
Checking Positions:
positions = app.get_positions()
for pos in positions:
 print(f"{pos['symbol']}: {pos['quantity']} shares @ ${pos['avg_cost']:.2f}")
Rebalancing Portfolio:
# The key method: ordertargetpercent

This calculates exact shares needed to reach target allocation

app.ordertargetpercent("AAPL", 0.05) # 5% in Apple app.ordertargetpercent("MSFT", 0.05) # 5% in Microsoft app.ordertargetpercent("GOOGL", 0.05) # 5% in Google

To exit a position completely

app.liquidate_position("TSLA")
Converting Backtest to Orders:
from omega.utils.omegatradesconverter import omegatradesfrom_zipline

Get current positions from broker

current = app.get_positions()

Get target positions from backtest

target = backtest_results["positions"]

Calculate required trades

orders = omegatradesfrom_zipline(current, target)

Execute

for order in orders: app.submit_order(order)

Running the System

Development: Luigi Workflow

Luigi is ideal for development and one-off runs:
# Start Luigi scheduler (optional, for web UI)
luigid --port 8082

Run the full pipeline

python -m workflow.dags.01ingestdata ExecuteTrades \ --start-date 2015-01-01 \ --run-date 2025-12-30 \ --local-scheduler
The Luigi DAG executes in order:
  • DownloadPricesFMP - Download historical prices
  • DownloadFundamentalsFMP - Download financial statements
  • BuildZiplineBundle - Create backtest data bundle
  • RunBacktest - Execute strategy backtest
  • ExecuteTrades - Place orders with broker

Production: Prefect Automation

Prefect handles production scheduling:
# Start Prefect server
prefect server start

Deploy flows

python automation/prefect_flows.py

View at http://localhost:4200

Deployed flows:
  • nightly-pipeline-orchestrator - Master flow (1 AM Tue-Sat)
  • nightly-qsconnect-refresh - Database update (10 PM daily)
  • nightly-backtest - Production backtest (2 AM daily)
  • nightly-iterative-sweep - Parameter optimization
  • nightly-dashboard-snapshot - Update dashboard data

Strategy Development

The QSMOM Factor

The core strategy uses a momentum factor calculated as:
QSMOM = ROC(slowperiod) - ROC(fastperiod)
Where:
  • ROC = Rate of Change (percent return)
  • slow_period = 252 days (1 year)
  • fast_period = 21 days (1 month)
Why this works:
  • Long-term momentum (252 days) captures trend persistence
  • Subtracting short-term momentum avoids recent price spikes
  • Stocks in the top quintile by QSMOM historically outperform

Portfolio Construction

The strategy constructs a long-only equal-weight portfolio:
  • Screen Universe: Filter to top 500 stocks by volume
  • Calculate Factor: Compute QSMOM for each stock
  • Rank Stocks: Sort by factor value (descending)
  • Select Top N: Take top 20 stocks
  • Equal Weight: Allocate 5% to each position
  • Rebalance Monthly: Update positions at month end

Creating Your Own Strategy

  • Copy the template:
# In qsresearch/strategies/factor/config.py
MYSTRATEGYCONFIG = MOMENTUMFACTORCONFIG.copy()
MYSTRATEGYCONFIG["experiment_name"] = "My Custom Strategy"
  • Modify parameters:
MYSTRATEGYCONFIG["factors"] = [
 {
 "name": "momentum_factor",
 "params": {
 "fast_period": 42, # 2 months
 "slow_period": 126, # 6 months
 }
 }
]
  • Run backtest:
from qsresearch.backtest import run_backtest
results = runbacktest(MYSTRATEGY_CONFIG)
  • Compare in MLflow:
- Open http://localhost:5050 - View all runs side-by-side - Select best by Sharpe ratio

API Reference

QS Connect Client

class Client:
 def stocklist(assettype="stock", exchanges=None, min_price=5.0) -> pd.DataFrame
 def bulkhistoricalprices(startdate, enddate, symbols=None, use_cache=True) -> pl.DataFrame
 def fetchbulkfinancialstatements(statementtype, periods, startyear, endyear) -> Dict
 def query(sql: str) -> pl.DataFrame
 def buildziplinebundle(bundlename, startdate=None, end_date=None) -> None
 def registerbundle(bundlename) -> None
 def ingestbundle(bundlename) -> None

QS Research

def runbacktest(config: Dict, outputdir=None, logtomlflow=True) -> Dict
def runiterativesweep(sweepconfig: Dict, rundate=None, experiment_name=None) -> List
def addqsmomfeatures(df, fastperiod=21, slowperiod=252, signal_period=126) -> pd.DataFrame
def calculateallmetrics(performance: pd.DataFrame, benchmark=None) -> Dict[str, float]

Omega Trading App

class TradingApp:
 def connect() -> bool
 def disconnect() -> None
 def get_positions() -> List[Dict]
 def getaccountinfo() -> Dict
 def getportfoliovalue() -> float
 def ordertargetpercent(symbol, targetpercent, ordertype="MKT") -> Trade
 def liquidate_position(symbol) -> Trade
 def getopenorders() -> List[Dict]
 def cancelallorders() -> int

LLM Strategy Generator

The system includes an AI-powered research assistant (qsresearch/llm/) that uses Groq's openai/gpt-oss-20b model to:
  • Analyze Market Regimes: Calculate volatility, trend strength, and returns to classify the market (Bull Steady, Bull Volatile, Bear, Sideways).
  • Generate Strategy Parameters: Prompt the LLM for optimal factor weights and lookback periods based on the current regime.
  • Multi-Candidate Search: Generate N distinct strategy variations (Balanced, Aggressive, Defensive) and rank them.
  • Validation: All LLM outputs are validated against strict constraints before use.
from qsresearch.llm import StrategyGenerator

generator = StrategyGenerator()
candidates = generator.generate_candidates(prices, n=3)

Each candidate is validated and ready for backtesting

for c in candidates: print(c['style'], c['factor_weights'])
โš ๏ธ Important: The LLM is used offline for research and parameter tuningโ€”NOT in the low-latency execution path.

Pre-Live Checklist

Before enabling live trading, complete the mandatory safety checks in docs/PRELIVECHECKLIST.md:
  • Paper Trading: Full day validation of order lifecycle.
  • Latency Benchmarking: P50/P95/P99 for all execution hops.
  • Risk-Trigger Testing: Verify loss limits and kill switches.
  • Failure-Mode Testing: Simulate disconnects, stale data, and rejects.
โš ๏ธ Skipping these steps means accepting undefined behavior with real money.

Troubleshooting

Common Issues

Issue: FMP API rate limit exceeded
Solution: The client automatically rate-limits to 300 req/min.
If you still hit limits, increase apibufferseconds in config.
Issue: DuckDB file locked
Solution: Only one process can write to DuckDB at a time.
Check for running Python processes or increase retry delay.
Issue: Zipline bundle not found
Solution: Run the bundle build steps:
 client.buildziplinebundle("historicalpricesfmp")
 client.registerbundle("historicalprices_fmp")
 client.ingestbundle("historicalprices_fmp")
Issue: Interactive Brokers connection failed
Solution: 
  • Ensure IB Gateway or TWS is running
  • Enable API connections in settings
  • Check port (7497 paper, 7496 live)
  • Verify client ID is unique
Issue: MLflow tracking server not found
Solution: Start the server with:
 mlflow server --port 5050
Or set MLFLOWTRACKINGURI to a valid location.

License & Disclaimer

Disclaimer

This software is for educational and informational purposes only.
  • This is NOT financial advice
  • Past performance does NOT guarantee future results
  • Use paper trading accounts for testing
  • The authors are NOT responsible for any financial losses
  • Always consult a qualified financial professional

Risk Warning

Algorithmic trading involves substantial risk of loss. You could lose some or all of your investment. Do not trade with money you cannot afford to lose.

License

Proprietary - All Rights Reserved
๐Ÿ”— More in this category

ยฉ 2026 GitRepoTrend ยท Ashutosh0x/QuantHedgeFund ยท Updated daily from GitHub