Quant Guild Library

repository·main·Indexed 22 days ago

https://github.com/romanmichaelpaolucci/quant-guild-library

An educational repository of Jupyter Notebooks and video lectures on quantitative finance, covering topics from beginner to advanced stochastic calculus and AI-driven trading. The library includes a PDE Solver with Finite Difference, Monte-Carlo, and analytic engines; a Grid World Search visualization for graph-search algorithms (BFS, DFS, Dijkstra, A*, Greedy); and a Trading Dashboard for portfolio analysis using Flask and Plotly.

Tokens
29.3K
Snippets
53
Records
111
Agent score
79%

What's inside quant-guild-library

  1. Overview of the Quant Guild Library

    main

    The Quant Guild Library is a curated educational repository containing Jupyter Notebooks and lecture videos focused on quantitative finance. It covers advanced topics such as stochastic calculus, options pricing, trading strategies, and the application of AI in finance.

    Each topic in the library is typically organized into a folder containing:

    1. A Jupyter Notebook for hands-on implementation.
    2. A corresponding lecture video by Roman Paolucci for conceptual explanation.
  2. Understand the Binomial Tree Pricer project structure

    main

    The project is organized into several key components:

    FilePurpose
    pricing.pyPure pricing engine: CRR tree (fast + full-lattice variants), Black–Scholes with greeks, and convergence series.
    app.pyFlask server running on port 5002. It builds Plotly figures server-side and serves them as JSON.
    templates/index.htmlSingle-page dashboard with MathJax-rendered LaTeX.
    static/app.jsFront-end controller that gathers inputs, calls the API, and renders results.
    smoke_test.pyHeadless correctness and boot checks.
    requirements.txtDependencies: flask, numpy, scipy, plotly.

    Visualizations provided by the dashboard include a recombining lattice (node graph), a convergence chart (binomial vs. Black-Scholes), and a risk-neutral intuition panel.

  3. Understand the PDE Solver project structure

    main

    The PDE Solver project is organized into several specialized modules that can be run standalone for testing or used together by the Flask server (app.py).

    • app.py: The Flask server (port 5003) that integrates the FD engine, MC pricer, and analytics into the web UI.
    • fd_solver.py: The core Finite Difference engine implementing the $\theta$-scheme (Explicit, Implicit, and Crank-Nicolson), the Thomas algorithm for tridiagonal solves, and PSOR for American options.
    • mc_pricer.py: The Monte-Carlo engine implementing risk-neutral simulation, barrier monitoring, and the Longstaff-Schwartz method for American options.
    • analytics.py: Provides closed-form solutions (Black-Scholes, cash-or-nothing, and Reiner-Rubinstein barriers) used for cross-checking.
    • smoke_test.py: A headless script for verifying that FD $\approx$ MC $\approx$ analytic solutions.
    • templates/ & static/: Contain the HTML, CSS, and JavaScript for the interactive dashboard UI.
  4. Project roadmap by Quant role and level

    main

    The library provides 9 hands-on projects categorized by three quant roles and three difficulty levels:

    Quant Trader

    Focuses on turning market views into risk-managed positions and P/L.

    • Intro: Trading Dashboard (Flask + Plotly) — Portfolio returns analysis, regressions, and factor attribution.
    • Intermediate: Market Making Simulator (Flask + animated Plotly) — Options market simulation with pricing and market-path models.
    • Advanced: Algorithmic Trading System (IBAPI + tkinter) — Desktop trading cockpit with live portfolio readouts and strategy management.

    Quant Researcher

    Focuses on the pricing theory pipeline.

    • Intro: Binomial Tree Pricer (Flask + Plotly) — Visual guide to risk-neutral pricing and Black–Scholes convergence.
    • Intermediate: PDE Solver (Flask + Plotly) — Finite-difference solvers for pricing PDEs (Black–Scholes, barriers, etc.).
    • Advanced: Pricing Library (Flask + Plotly + LaTeX) — Path signatures, model-free pricing, and rough volatility models.

    Quant Developer

    Focuses on data structures, algorithms, and performance.

    • Intro: Grid World Search (pygame) — Visualization of BFS, DFS, Dijkstra, and A* algorithms.
    • Intermediate: Order Book Simulator (tkinter) — Price-time-priority matching engine built from first principles.
    • Advanced: Latency & Cythonization — Benchmarking and speeding up Monte Carlo pricing kernels using Cython.
  5. Compare BFS, DFS, Dijkstra, A*, and Greedy algorithms

    main

    The project visualizes five classic graph-search algorithms. They all follow the same core loop (pop a cell from the frontier, expand neighbors, repeat) but differ in how they select the next cell from the frontier.

    AlgorithmFrontierPops nextOptimal?TimeSpace
    BFSFIFO queueoldest✅ (unit weights)O(V + E)O(V)
    DFSLIFO stacknewestO(V + E)O(V)
    Dijkstramin-heap on gcheapest so far✅ (non-neg weights)O((V + E) log V)O(V)
    A*min-heap on g + hbest f estimate✅ (admissible h)O(b^d) worstO(b^d)
    Greedymin-heap on hclosest-lookingO(b^m) worstO(b^m)
  6. Use different pricing frameworks in the PDE Solver

    main

    The solver supports four distinct pricing frameworks by varying the terminal and boundary conditions applied to the Black-Scholes PDE:

    • Vanilla (Call/Put): Uses standard payoffs like $\max(S-K,0)$. Boundary conditions are set at $S=0$ and $S=S_{max}$.
    • Barrier (Knock-out): Uses vanilla payoffs on an un-knocked domain. It applies a Dirichlet boundary condition ($V(H,t)=0$) at the barrier $H$.
    • Digital (Cash-or-nothing): Uses a discontinuous payoff (e.g., $Q \cdot \mathbb{1}_{S>K}$).
    • American (Call/Put): Uses vanilla payoffs but treats the exercise boundary as a free boundary. It is solved as a Linear Complementarity Problem (LCP) using Projected SOR (PSOR) to ensure $V \ge \text{intrinsic payoff}$ at all times.
  7. Understand the quantitative metrics in the dashboard

    main

    The dashboard provides several layers of factor analysis and performance statistics:

    CAPM (Capital Asset Pricing Model)

    Estimates exposure to the market via OLS regression:

    • Beta (β): Sensitivity to the market (systematic risk).
    • Alpha (α): Average return above what beta-driven market exposure explains (annualized by multiplying the daily intercept by 252).
    • : Fraction of portfolio variance explained by the market.

    Fama-French Factor Models

    Adds systematic style factors to the regression:

    • Mkt-RF: Market excess return.
    • SMB (Small Minus Big): Size factor.
    • HML (High Minus Low): Value factor.
    • RMW (Robust Minus Weak): Profitability factor.
    • CMA (Conservative Minus Aggressive): Investment factor.

    Performance & Risk Statistics

    • Total return / CAGR: Cumulative and annualized geometric growth.
    • Annualized volatility: Standard deviation of daily returns scaled by $\sqrt{252}$.
    • Sharpe ratio: Annualized excess return per unit of total volatility.
    • Sortino ratio: Annualized excess return per unit of downside volatility.
    • Maximum drawdown (MDD): Worst peak-to-trough decline.
    • Rolling factor attribution: Re-estimates factor betas over a moving window (default 63 trading days) to detect style drift.
  8. Understand the Order Book Simulator architecture

    main

    The project is architected with a strict separation between the matching engine and the presentation layer to ensure the engine is pure, testable, and reusable.

    • order_book.py: The core matching engine. It contains all matching logic and has zero I/O or GUI dependencies.
    • market_sim.py: A stochastic order-flow generator that simulates market activity (limit orders, market orders, and cancellations) to keep the book active.
    • app.py: The tkinter desktop application providing the live GUI (ladder, depth chart, tape, and controls).
    • test_order_book.py: Headless unit tests verifying matching semantics.
  9. Configure Finite Difference (FD) schemes and stability

    main

    The FD engine in fd_solver.py uses a $\theta$-scheme to blend explicit and implicit evaluations. You can choose between three schemes in the dashboard:

    $\theta$SchemeStabilityAccuracyNotes
    0Explicitconditional$O(\Delta\tau)+O(\Delta S^2)$Cheap per step; requires $\Delta\tau \le \Delta S^2 / (\sigma^2 S_{max}^2)$ to avoid divergence
    1Implicitunconditional$O(\Delta\tau)+O(\Delta S^2)$Requires one tridiagonal solve per step
    0.5Crank-Nicolsonunconditional$O(\Delta\tau^2)+O(\Delta S^2)$The default; most accurate

    Stability Tip: If using the Explicit scheme, ensure your time steps ($\Delta\tau$) are small enough relative to your spatial steps ($\Delta S$) to satisfy the CFL condition, otherwise the price will diverge.

  10. How Cython improves numerical performance

    main

    Cython optimizes pure Python code by removing the overhead of the Python interpreter in hot loops. It achieves this through several mechanisms:

    • Static typing: Using cdef (e.g., cdef double) converts variables into native C types, turning arithmetic into raw machine instructions rather than dynamic Python-object calls.
    • Typed memoryviews: Using syntax like double[:, ::1] allows array elements to be accessed via C pointer arithmetic, avoiding per-element Python boxing.
    • Compiling to C: The .pyx file is translated to C and compiled into a native extension module, removing the interpreter from the loop.
    • Releasing safety checks: Using boundscheck(False) and wraparound(False) removes per-index bounds and negative-index checks. cdivision(True) uses C division semantics.
    • C math: Importing directly from libc.math (e.g., from libc.math cimport exp, sqrt) allows calling the C library directly instead of the Python math module.

    Comparison Note: While numpy is highly efficient through vectorization, it often requires materializing large intermediate arrays in memory. Cython and Numba can stream data through registers with $O(1)$ extra memory, often resulting in better performance for both time and memory usage in tight loops.

  11. How the Limit Order Book matching engine works

    main

    The engine implements a price-time-priority matching rule, which is the standard for most exchanges.

    Matching Rules

    1. Price Priority: The best price is filled first. Buyers sweep the cheapest asks; sellers hit the highest bids.
    2. Time Priority: Within a single price level, orders are filled first-in, first-out (FIFO). The order that arrived earlier at that price level is at the front of the queue.

    Order Types

    • Limit Order: Has a specific price. If it can trade immediately against an existing order, it does so; otherwise, the remainder rests in the book, providing liquidity (the user becomes a maker).
    • Market Order: Has no price and takes available liquidity on the opposite side until filled. Any unfilled remainder is discarded (market orders never rest).

    Key Concepts

    • Marketable Order: An order that crosses the spread (e.g., a buy priced $\ge$ best ask). These trigger immediate matches.
    • Price Improvement: Trades print at the resting maker's price. For example, a buy limit at 100.10 hitting a resting ask at 99.90 will trade at 99.90.
    • Fat-finger Protection: The system includes a price band guard. If a manual limit order is placed far through the market, the system warns the user and can collar the order to a 10% band around the mid-price to prevent sweeping the entire book at an absurd price.
  12. How the strategy framework works

    main

    The system uses a strategy framework where every strategy must subclass Strategy and implement generate_signal(prices) -> float.

    Signal Generation

    Signals are dimensionless directional values in the range [-1, +1]:

    • +1: Maximum long conviction
    • 0: Flat
    • -1: Maximum short conviction

    Supported Strategy Types

    StrategyIdeaKey parameters
    Trend FollowingFast SMA vs slow SMA crossoverfast, slow, scale
    Mean ReversionFade the z-score of price vs rolling meanlookback, entry_z
    MomentumSign & size of trailing returnlookback, scale

    New strategies can be added by subclassing Strategy and declaring type_name and param_spec; they will automatically appear in the UI via the STRATEGY_REGISTRY.