GS Quant Python Toolkit

repository·master·Indexed 11 days ago

https://github.com/goldmansachs/gs-quant

A Python-based quantitative finance toolkit developed by Goldman Sachs for building trading strategies, managing risk, and performing derivative analysis. It provides comprehensive modules for pricing and risk across Rates, FX, Equities, and Credit, as well as tools for portfolio management, backtesting engines, factor models, and index analysis via Marquee.

Tokens
64.9K
Snippets
196
Records
243
Agent score
96%

What's inside GS Quant

  1. Overview of GS Quant

    master

    GS Quant is a Python toolkit for quantitative finance designed to accelerate the development of quantitative trading strategies and risk management solutions. It is used for:

    • Derivative structuring, trading, and risk management.
    • Statistical analysis and data analytics applications.
    • Developing quantitative trading strategies.
  2. Explore GS Quant research and case studies

    master

    The gs_quant repository contains a collection of research, tactical case studies, and analytical notebooks. You can use these to learn how to implement specific financial workflows using the library.

    Key areas of research include:

    • Events: Analysis of specific market events (e.g., US election analysis, risk re-rating ideas, equity trading optimization, and ESG basket portfolio optimization).
    • Made with GS Quant: Practical applications and tutorials covering topics like navigating rates, explaining performance drivers, FX election hedges, delta hedging, and machine learning for hedging.
    • Reports and Screens: Specialized screens and reports for different asset classes:
      • FX: Volatility screens, calendar screens, forward vol, and vol skew.
      • Rates: Vol fixed strike grids, moneyness screens, and swaption carry grids.
      • Prime: Case studies on sector positioning, flows, factors, country positioning, and leverage using GS Prime Brokerage data.
  3. Explore GS Quant documentation examples

    master

    The GS Quant documentation is organized into functional modules, each containing Jupyter notebooks that serve as practical examples for specific tasks. You can find examples for:

    • Data (00_data): Querying datasets, managing data contexts, retrieving volatility surfaces, and using screeners.
    • Markets (01_markets): Working with securities and managing relative dates/business day calendars.
    • Pricing and Risk (02_pricing_and_risk):
      • Instruments and Measures: Detailed examples for Rates (swaps, swaptions), FX (forwards, options, var swaps), Equities (options), and Credit (CDX).
      • Scenarios and Contexts: Understanding market objects and market data patterns.
    • Analytics and Visualizations: Charting, exporting data, and creating visualizations.
  4. Navigate gs_quant documentation

    master

    The gs_quant documentation is structured into two primary types of resources to help you learn the library:

    1. Tutorials: These introduce core concepts, fundamental ideas, and primary functions. They are recommended as the starting point for new users.
    2. Examples: A searchable library of short, specific code snippets designed to demonstrate particular use cases or functions.
  5. Manage instruments using the `Portfolio` class

    master

    The Portfolio class groups instruments for pricing, resolution, and analysis as a single unit. Portfolios can be created from lists or dictionaries (where keys are instrument names) and can be nested.

    Portfolio Operations

    • Creation: Pass a list of instruments or a dictionary of {name: instrument}.
    • Nesting: A Portfolio can contain other Portfolio objects.
    • Access: Access instruments by index (portfolio[0]) or by name (portfolio['name']).
    • Aggregation: portfolio.all_instruments returns all instruments across all nested portfolios.
    • Resolution: portfolio.resolve() resolves all instruments within the portfolio in place.
    • Pricing: portfolio.calc(measure) calculates risk measures (e.g., DollarPrice, IRDelta) for the entire portfolio.
    from gs_quant.instrument import IRSwap, IRSwaption
    from gs_quant.markets.portfolio import Portfolio
    from gs_quant.risk import DollarPrice, IRDelta
    
    # Creating from a list
    swap = IRSwap('Pay', '10y', 'USD', name='USD 10y Payer')
    swaption = IRSwaption('Receive', '10y', 'EUR', expiration_date='1y', name='EUR 1y10y Receiver')
    portfolio = Portfolio([swap, swaption], name='My Portfolio')
    
    # Creating from a dictionary
    portfolio = Portfolio(
        {
            'USD 10y Payer': IRSwap('Pay', '10y', 'USD'),
            'EUR 5y Receiver': IRSwap('Receive', '5y', 'EUR'),
        }
    )
    
    # Nesting portfolios
    book_a = Portfolio([IRSwap('Pay', '5y', 'USD')], name='Book A')
    book_b = Portfolio([IRSwap('Pay', '5y', 'EUR')], name='Book B')
    master = Portfolio([book_a, book_b], name='Master Book')
    
    # Operations
    master.resolve()  # resolves all instruments in place
    prices = master.calc(DollarPrice)  # single risk measure
    results = master.calc([DollarPrice, IRDelta])  # multiple risk measures
  6. Understand how gs_quant.skills files are placed

    master

    When you run the installer, the files are placed in the target .claude/skills/ directory as follows:

    • Linux/macOS: The installer creates symlinks from .claude/skills/<name> to the source directory inside the installed gs_quant package. Updating the gs_quant package automatically updates the skills.
    • Windows: The installer copies the skill directory (no symlinks). You must re-run the install command after upgrading gs_quant to refresh the skills.

    Warning: If a target directory already exists at the destination, it will be overwritten.

  7. Understand the GS Quant Backtesting Architecture

    master

    The backtesting framework is built on three core abstractions that compose to form a strategy:

    1. Strategy: The top-level object that combines an optional initial portfolio with one or more Trigger objects.
    2. Trigger: Defines when to act (e.g., on a schedule, a risk threshold breach, or market data changes). Each trigger holds one or more Action objects.
    3. Action: Defines what to do when a trigger fires (e.g., add a trade, hedge, exit, or rebalance).

    A backtest Engine executes the strategy over a specified date range, resolving instruments, computing risks, and generating P&L time series.

    from gs_quant.backtests.strategy import Strategy
    from gs_quant.backtests.triggers import PeriodicTrigger
    from gs_quant.backtests.actions import AddTradeAction
    
    # Example composition
    strategy = Strategy(None, PeriodicTrigger(trig_req, action))
  8. Coding standards and PEP 8 for GS Quant measures

    master

    All new measure code must comply with strict formatting and naming standards. Enforcement is done via ruff.

    Naming Conventions

    • Functions/Variables: snake_case (e.g., swap_rate)
    • Classes/Enums: CamelCase (e.g., EventType)
    • Constants: UPPER_SNAKE_CASE (e.g., CENTRAL_BANK_WATCH_START_DATE)
    • Private/Internal: Prefix with underscore (e.g., _extract_series_from_df)

    Import Rules

    • import pandas as pd (never from pandas import ...)
    • import numpy as np
    • import datetime as dt
    • Prohibited: Do not import from gs_quant.target.common (use gs_quant.common instead).
    • Prohibited: Do not use pytz (use zoneinfo or datetime.timezone).
    • Ordering: Group by stdlib $\rightarrow$ third-party $\rightarrow$ local. Alphabetize within groups.

    Formatting & Type Annotations

    • Indentation: 4 spaces.
    • Line Length: Max 120 characters.
    • Docstrings: Use triple double-quotes ("""). Must include :param, :return:, **Usage**, and **Examples** sections.
    • Types: All public parameters and return types must be annotated. Use Optional[X] and Union[X, Y] where appropriate.

    Enforcement Commands

    Run these before committing:

    ruff check --fix
    ruff format
  9. Configure authentication strategies for the MCP server

    master

    The server supports two authentication modes via the --auth flag:

    local (Default)

    Best for single-user / desktop use. The server creates and authenticates one GsSession at startup using the provided --client-id and --client-secret (or environment variables). This single shared session is reused for every request made to the server.

    python -m gs_quant.mcp server --auth local \
      --client-id "$CLIENT_ID" --client-secret "$CLIENT_SECRET"

    passthrough

    Best for multi-user / remote deployments. No session is created at startup. Instead, the server inspects each incoming HTTP request to construct a per-user GsSession. It detects authentication from:

    • GSSSO cookie $\rightarrow$ GSSSO SSO token
    • MarqueeLogin cookie $\rightarrow$ MARQUEE_LOGIN
    • Authorization: Bearer <3-part JWT> $\rightarrow$ JWT
    • Authorization: Bearer <otherwise> $\rightarrow$ OAUTH access token
    python -m gs_quant.mcp server --auth passthrough
    python -m gs_quant.mcp server --auth local --client-id "$CLIENT_ID" --client-secret "$CLIENT_SECRET"
  10. Use different trigger types for backtesting strategies

    master

    Triggers determine when an action (like a trade) is executed during a backtest. Available trigger types include:

    • PeriodicTrigger: Executes trades on a specific schedule (e.g., every 6 months).
    • StrategyRiskTrigger: Triggers when a specific risk threshold is breached.
    • MktTrigger: Triggers based on market data movements.
    • DateTrigger: Triggers on specific, predefined dates.
    • AggregateTrigger: Combines multiple triggers using AND/OR logic.
    • NotTrigger: Inverts the logic of a trigger.
  11. Manage relative dates and business calendars

    master

    The 01_markets/02_rdates module provides tools for handling financial dates. Key capabilities include:

    • Getting dates relative to today.
    • Getting dates relative to a specific base date.
    • Using pricing contexts to resolve dates.
    • Utilizing business day calendars and passing custom holiday calendars to ensure accurate date arithmetic.