/quant-skills:python-programmingfrom quant-skills
Guides writing, reviewing, refactoring, and debugging Python code. Covers type hints, dataclasses, asyncio, pytest, project setup with pyproject.toml, and tooling (uv, ruff, mypy, pyright).
Ships in quant-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Write Python that a reader can follow top to bottom and a type checker can verify. Most defects in Python code are things a checker or a test would have caught, so the habit that pays is making them able to catch it.
Match the project first. Before writing, read pyproject.toml (or
setup.cfg, requirements*.txt) for the Python version, formatter, linter and
test runner, and look at two existing modules for naming and layout. The
project's conventions win over the defaults below.
Target Python 3.11 or later unless the project says otherwise.
| Decision | Default | Instead of |
|---|---|---|
| Project and dependencies | pyproject.toml, uv for environments and locking | setup.py, bare requirements.txt |
| Layout | src/<package>/, tests/ beside it | package at the repository root |
| Format and lint | ruff format and ruff check | separate black, isort, flake8 |
| Types | built-in generics (list[str]), X | None, collections.abc for parameters | typing.List, Optional, Union |
| Records | @dataclass(frozen=True, slots=True) | dicts with string keys, hand-written __init__ |
| Untrusted input | Pydantic model at the boundary | manual isinstance chains |
| Fixed choices | enum.StrEnum | string constants |
| Paths | pathlib.Path | os.path string joins |
| Time | datetime.now(UTC), always timezone-aware | datetime.utcnow() (deprecated, returns naive) |
| Concurrency (I/O) | asyncio.TaskGroup, asyncio.timeout | bare gather, manual task bookkeeping |
| Concurrency (CPU) | ProcessPoolExecutor, or vectorize | threads |
| Config | tomllib, environment variables, typed settings object | globals, eval |
| Logging | logging.getLogger(__name__), %s arguments | print, f-strings in log calls |
| Tests | pytest, plain assert, tmp_path, monkeypatch | unittest.TestCase boilerplate |
Iterable[str], Mapping[str, int]), return
the narrowest (list[str]). Callers stay flexible and get precise results.Protocol for "anything with this method" instead of a base class the
caller must inherit from.Any switches the checker off for everything it touches. Prefer object for
"anything", and narrow with isinstance or match.| Need | Use |
|---|---|
| Internal record with behaviour | @dataclass(frozen=True, slots=True) |
| Parsing and validating external data (JSON, env, user input) | Pydantic model |
| Describing the shape of a dict you do not control | TypedDict |
| Small immutable tuple with names | NamedTuple |
| Closed set of values | StrEnum / Enum |
except Exception: pass hides the bug and the next person's afternoon.raise NewError(...) from err so the original traceback survives.time.sleep, requests.get, a heavy loop) stalls
every task. Push blocking work to asyncio.to_thread.TaskGroup: if one task fails the rest are
cancelled and the error surfaces. A task created and not awaited can vanish
with its exception.Semaphore.test_rejects_negative_quantity).pytest.mark.parametrize for input tables, fixtures for setup, tmp_path for
files, monkeypatch for environment and attributes.Measure before changing anything: python -m cProfile -s cumtime script.py, or
py-spy on a running process. Then, in order of payoff:
set and dict lookups, not list scans).functools.cache).Generators keep memory flat for large streams; lists are faster for small ones.
| Trap | What happens | Fix |
|---|---|---|
def f(x, items=[]) | the default list is shared across calls | items: list | None = None, create inside |
Closures in a loop (lambda: i) | all see the final i | bind it: lambda i=i: i |
is for value comparison | works for small ints and some strings by accident | == for values, is only for None and sentinels |
| Modifying a list while iterating it | skipped elements | iterate over a copy or build a new list |
| Naive datetimes | silent errors across time zones and DST | timezone-aware everywhere, convert at the edge |
| Floats for money | 0.1 + 0.2 != 0.3 | Decimal or integer minor units |
except: or broad except Exception | swallows KeyboardInterrupt or real bugs | catch the specific error |
| Circular imports | ImportError or partially initialised modules | move shared types to a third module; import inside the function as a last resort |
Opening files without with | leaked handles | context manager |
ruff format . && ruff check . --fix
mypy src # or: pyright
pytest -q
Run them and read the output. If the project has no configuration for one of these, say so instead of inventing a passing result.
| File | When |
|---|---|
references/patterns.md | worked examples: dataclasses, Protocol, StrEnum with match, error chaining, context managers, TaskGroup with timeout and bounded concurrency, pytest patterns |
references/project-setup.md | pyproject.toml template, uv commands, ruff and mypy configuration, pre-commit, CI |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
python-development, type-hints, code-quality, testing, project-setup
npx claudepluginhub ricko12vpl/claude-code-skills --plugin quant-skills9 skills in this plugin
/hedge-fund-blueprintUse when building, planning, reviewing or extending the platform of a systematic (quant) hedge fund or trading operation as a whole - point-in-time data store, backtester, factor risk model, signals, portfolio optimizer, execution and order management, reconciliation, P&L attribution - or when deciding what to build first, which stack to start with, or whether one of those pieces is finished. Triggers - "build a hedge fund / quant fund / trading system from scratch", "what should I build next", research-to-production pipeline, alpha platform architecture, "is my backtester / risk model / optimizer good enough", trade lifecycle from decision to settlement, how the parts of a fund fit together. Use it even when only one piece is named but the user is clearly assembling the full loop./machine-learningUse when building, training, evaluating, debugging or deploying a machine learning model - tabular models with scikit-learn, XGBoost, LightGBM or CatBoost, deep learning with PyTorch, feature engineering, train/validation/test splitting, cross-validation, choosing metrics, class imbalance, hyperparameter tuning, overfitting, data leakage, probability calibration, model serving, drift monitoring. Triggers - "train a model to predict", "which model should I use", "validation score is great but production is bad", "is this data leakage", "loss is not decreasing", "tune hyperparameters", "imbalanced classes", "deploy this model", "the model got worse over time"./quantitative-financeUse when working on one quantitative finance or systematic trading problem - designing or checking a backtest, testing a signal or alpha idea, time-series statistics (stationarity, cointegration, mean-reversion half-life, GARCH volatility), factor regressions, portfolio construction (mean-variance, risk parity, Black-Litterman), risk measures (volatility, VaR, expected shortfall, drawdown), position sizing and Kelly, execution schedules, market impact, transaction cost analysis, or computing and interpreting performance numbers such as a Sharpe ratio. Triggers - pairs trading, momentum or mean-reversion strategies, walk-forward optimization, overfitting or look-ahead worries, slippage, order book analysis, "is this result real". For assembling a whole fund platform in build order, use hedge-fund-blueprint./senior-quantitative-developerUse when building, optimizing or hardening trading infrastructure - market data feed handlers, order gateways and routing, pre-trade risk, low-latency hot paths, tick capture and replay - or when the work concerns latency percentiles (P50, P99), jitter, throughput, packet loss, sequence gaps, deterministic recovery, lock-free queues, kernel bypass, clock synchronisation, or production readiness of a trading system (observability, canary release, rollback, incident response). Triggers - "reduce feed handler latency", "tick to trade", "why did P99 spike", "handle exchange gaps", FIX, ITCH, OUCH, kill switch, backpressure./senior-quantitative-researcherUse when researching, validating or documenting a trading signal or systematic strategy to an institutional standard - forming and pre-registering a hypothesis, building features without leakage, walk-forward or purged cross-validation, ablations and sensitivity analysis, capacity and cost modelling, writing a research report, preparing a signal for handover to production, or diagnosing why live results differ from the backtest. Triggers - "alpha research", "is this signal real", "validate my strategy", "factor research", "research memo", "live vs backtest gap", "alpha decay", "how much capital can this take"./senior-quantitative-traderUse when making portfolio-level decisions for a systematic book - allocating risk across strategies or signals, sizing and leverage, hedging factor or market exposure, setting and applying drawdown rules, reviewing performance attribution (alpha versus factor versus cost), deciding whether to scale, cut, pause or retire a strategy, or writing a periodic performance review or decision memo. Triggers - "attribution review", "how much risk should each strategy get", "we are in drawdown, what now", "should we scale this up", "hedge the beta", "risk budget", "quarterly review", "is this strategy broken or unlucky".Other plugins' skills for the same job