You bring the problem.We ship the system.Cognitive frameworks. AI workflows. Data pipelines. Trading systems. Personal operating systems.
Built, not advised.
Shipped, not slidewared. Ravenrock / Est. 2024 · California
What We Are
Architecture.
Production. Ownership.
Ravenrock builds AI infrastructure and runs businesses on top of it. The founder is the architect and the operator. No gap between design and execution.
I
Architecture first
Every product starts with a structural question. Build the layer that holds everything else up.
II
Production only
No demos that don't ship. If it doesn't run live, it doesn't count.
III
Own the stack
No critical dependency on any single provider. Every layer upgradeable independently.
IV
Expand the domain
Finance proved it. Crypto and cybersecurity are next.
Educational research only. Not investment advice. No capital accepted.
Products
Two ways in. Both $599.
One is an hour of my time. One is a year inside the community. Pick the one that matches what you actually need.
01 · Consulting
1:1 Strategy Call
$599/ hour
Direct working session over Zoom. Trading system architecture, AI workflow design, macro research process, LLM integration for financial workflows.
PayPal uses one checkout for both products. After paying, a pre-filled email opens so we can attribute your payment — send it, and activation follows within 24h. Stripe attributes automatically.
Track Record
Fifteen years. On the record.
Macro research published continuously under the Ravenrock / 灰岩金融科技 brand since 2010 — cited by major mainland Chinese financial media for six consecutive years. The evidence chain is public and verifiable.
15Y
Continuous published research under one brand
2017–23
Six consecutive years cited by major mainland financial media
5
Working languages — EN · 中文 · 日本語 · 粵語 · DE
8mo
ZTrader.AI — full platform built solo, from zero coding background
Verification: search 灰岩金融科技 on Baidu. Citation history spans mainstream mainland financial outlets, 2017 through 2023.
Portfolio
Ravenrock is the operating company. ZTrader.AI is the research product. Dorian is the personal research brand. Capital is a prototype program, not a fund.
Five ventures. One architecture.
Live
V — 01
ZTrader.AI
Financial Research & Education Platform
Multilingual macro research, market education, and AI-assisted analysis. Macro, vol, rates, FX, commodities, digital assets. EN / ZH / JP markets.
Research on the platform is authored by Dorian personally — not by Ravenrock. Professional-grade research built for practitioners who act on their own conviction.
Research and prototype program only. No investment management services are offered. Not a registered fund. No capital accepted.
Systematic Macro Research
An internal research program exploring systematic macro strategies. Concept and dashboard prototype stage. Not currently accepting capital, advisory clients, or accredited investors.
capital.ravenrock.ai — Concept Preview
REGIME MACRO_DIV
STAGE Research / Prototype
STATUS Not Yet Operational
⬛ No Public Access — Research Only
Active
V — 03
Dorian
AI Consulting & Education
Independent AI consulting, courses, and tools for founders, teams, and individuals.
ZMACRO's verification architecture extended to threat intelligence and adversarial AI.
Threat intelligence
Adversarial AI detection
Building
V — 05
Ravenrock Chain
Blockchain · Derivatives · Advisory
On-chain capital markets infrastructure. Structured derivatives, tokenised macro strategies, and advisory for operators building at the intersection of TradFi and DeFi.
Derivatives structuring & advisory
Tokenised macro strategies
On-chain trading architecture
DeFi protocol consulting
Cross-chain risk & settlement frameworks
Selective. Serious.
One active partnership slot
per quarter.
Reviewed personally.
Services
Select engagements.
SVC — 01
AI Consulting
Hands-on guidance for individuals and teams adopting AI into their workflow. Practical, not theoretical.
Markets are not solved. They are interpreted —
and the interpreter changes what it reads.
A working philosophy at the intersection of reflexive markets, irreducible uncertainty, and artificial intelligence. Not a framework to trade with — a way of thinking about why frameworks break.
BLACK SWAN · CONSTRUCTED GEOMETRY
The Philosophy
Three ideas. One architecture.
None of these are mine. What might be mine is the insistence on holding all three at once — because each one, alone, produces a different kind of overconfidence.
I.
Reflexivity
George SorosThe Alchemy of Finance, 1987
The map changes the terrain it is mapping.
Standard economics assumes markets converge toward a true value that exists independently of what anyone believes. Reflexivity rejects this entirely. Participants' beliefs shape prices, and prices shape participants' beliefs — a feedback loop, not a mirror.
"Market prices are always wrong in the sense that they present a biased view of the future. But the bias can influence the course of events it anticipates."
Operationally, this means every model — including those built into ZTrader.AI — is itself a participant in the system it describes. Publish a signal widely enough, and the signal changes what it was measuring. That's not a flaw to engineer around. It's the actual texture of markets.
II.
Radical Uncertainty
Nassim Nicholas TalebThe Black Swan, 2007 · Antifragile, 2012
The risk that breaks the model is the one the model never included.
A black swan isn't just rare — it's an event the model assigned near-zero probability to because the training data came from a world before it happened. Every backtest bets the future resembles the past closely enough to matter. The times it doesn't are the only times that matter.
"Don't be the turkey." — every day the turkey is fed is evidence, to the turkey, that the farmer loves turkeys.
The response isn't predicting the unpredictable — that's a category error. It's designing structures that survive being wrong: capped downside, optional upside, deep suspicion of any system whose value depends on a calm, mean-reverting world.
Antifragility principle
"Some things benefit from shocks; they thrive and grow when exposed to volatility, randomness, disorder."
III.
AI as Epistemics
Applied, not theoreticalZMACRO · Z-Kernel · ZTrader.AI
Intelligence is not prediction. It's knowing the shape of what you don't know.
Most AI applied to markets chases the wrong target: better prediction. But reflexivity says the system is unpredictable in principle, and black swan theory says the tail events that matter most are by definition outside the training distribution.
The honest target is epistemic infrastructure — systems that compress information faster than a human can, flag when a claim is unverified, and explicitly track where the model stops applying. That is the actual design principle behind ZMACRO's verification layer: not "what will happen," but "what do we actually know, and where does our framework break down."
Loop, not line
Reflexivity demands the model know it's inside the loop — including AI systems that publish signals at scale.
A signal published widely enough becomes reflexive — the act of measuring changes what is being measured. Build for that, not against it.
Tails, not centers
The average case is the least interesting case. Design for where the model breaks.
Black swan theory says the edges dominate history. The model should know precisely where it fails, not only where it works.
Verify, don't predict
AI's honest job is compressing what's known and flagging what isn't. Fast enough to matter.
Not "what will happen" — but "what do we actually know with what confidence, and where does this framework stop applying."
Research Platform
ZTrader.AI
Macro research and AI-assisted analysis built on the premise that markets are reflexive and tail risk is the main event, not the exception. Every thesis includes its own falsification criteria.
Claim extraction, source weighting, explicit data-state flags — surfaces what's known vs assumed, not forecasts with false confidence. Verification as design principle.
The entity that exists to build infrastructure shaped by this philosophy — across financial intelligence first, and any domain where the same epistemics apply.
For teams building AI systems for uncertain domains — not just markets — who want the reflexivity and tail-risk lens applied to their own architecture and decision systems.
1987 / 1994Soros — The Alchemy of Finance. Reflexivity formalized: market participants' biased perceptions shape the fundamentals they believe they're merely observing.
2001Taleb — Fooled by Randomness. Luck and survivorship bias in apparent trading skill. The role of the invisible alternative histories.
2007Taleb — The Black Swan. Rare, high-impact, retrospectively-obvious events dominate history far beyond what normal distributions allow.
2012Taleb — Antifragile. Beyond robustness: systems that improve because of disorder, not despite it. The structural response to the black swan problem.
PresentApplied synthesis — ZMACRO verification architecture. Reflexivity + tail-risk thinking operationalized: verification-first, not prediction-first. The honest AI claim for uncertain domains.
A Working Thesis
The goal was never to predict the market. It was to build something honest enough to admit what it doesn't know — and fast enough to be useful anyway.
Personal research and philosophy — published independently by Dorian.
Built for independent operators who make their own calls. Not affiliated with any institutional research.
C
Consulting
Book a session.
Direct access to the founder. AI architecture, system design, workflow strategy, or a general advisory session. Pick a type, pick a time.
Sessions & Rates
$599/hour
All sessions conducted via Zoom · English / 中文 / 日本語
Recording provided on request · Follow-up summary included
Free
30
Minutes
Discovery Call
First contact. We scope your problem and determine fit. No commitment, no preparation required.
Anyone — first time
$599
60
Minutes
Deep Dive
One focused hour on your specific problem:
Trading system & strategy architecture review
AI workflow design — research, execution, verification
Macro research process audit
LLM integration for financial workflows
Founders · Traders · Institutions
$599
90
Minutes
Working Session
$599/hr · 90 min · balance invoiced after
Extended build session. We design or debug together in real time:
Live system design — bring your stack & codebase
AI trading pipeline construction
Prompt architecture & agent workflow engineering
Data verification layer design (ZMACRO methodology)
Teams · Technical founders
Every Paid Session Includes
01Pre-session intake — you send materials 24h ahead, I review before we start
02Zoom session with screen-share, recorded on request
03Written follow-up — key decisions, action items, references within 48h
All sessions bill at the same $599/hour rate. The 60-minute Deep Dive is $599; the 90-minute Working Session runs longer and is invoiced for the additional half hour after the call. Book your slot first, then pay — unpaid slots release after 24 hours.
June 2026
Mo
Tu
We
Th
Fr
Sa
Su
TimezoneDetecting...
Select a date
Available slots will appear here
Complete your booking
— Select a date and time above —
A confirmation will be sent to your email. No-shows may affect future access.
▣
Slot reserved.
Complete payment to lock it in. Send the booking notice below so Dorian gets your details immediately.
How we handle your data. What we collect, what we don't, and why.
Read →
Terms of Service
The rules of engagement for all Ravenrock services and products.
Read →
Disclosures
Financial and regulatory disclosures. Built for independent operators who make their own calls. Not a registered fund.
Read →
Cancellation Policy
How to reschedule or cancel a booked session, and our policy on no-shows.
Read →
Privacy Policy
Last updated: June 2026. Ravenrock Fintech LLC ("Ravenrock") is committed to protecting your privacy.
What We Collect
Name and email address when you submit an inquiry or book a session
Organization name and session context you choose to provide
Basic usage data (page views, session duration) via privacy-respecting analytics
What We Don't Collect
We do not sell, rent, or share your personal data with third parties
We do not use your data for advertising or profiling
We do not store payment information — payments processed via third-party providers only
How We Use Your Data
Solely to respond to your inquiry, confirm and manage your booking, and communicate about your engagement with Ravenrock. We do not contact you for marketing purposes without explicit consent.
Data Retention
Inquiry and booking data is retained for up to 24 months or deleted upon request. To request deletion, contact us directly via the inquiry form.
Jurisdiction
Ravenrock Fintech LLC is incorporated in California, USA. Data is handled in accordance with applicable US law. Users in the EU/EEA may have additional rights under GDPR.
Terms of Service
Last updated: June 2026. By accessing Ravenrock's website or engaging with its services, you agree to the following terms.
Services
Ravenrock provides AI infrastructure consulting, system design advisory, and access to products including ZTrader.AI. All services are provided as-is, subject to availability and the founder's discretion.
Intellectual Property
All content, systems, and frameworks published by Ravenrock are proprietary
Research published by Dorian is authored in a personal capacity and remains the intellectual property of the author
No reproduction or redistribution of Ravenrock's proprietary materials without written permission
Limitation of Liability
Ravenrock's advisory services deliver operator-grade intelligence — for principals who act on their own conviction, at their own risk. Ravenrock is not liable for decisions made based on information provided during sessions or through its platforms.
Governing Law
These terms are governed by the laws of the State of California, USA. Any disputes shall be resolved in the courts of California.
Financial Disclosures
Last updated: June 2026.
Operator Intelligence
Nothing published by Ravenrock Fintech LLC, ZTrader.AI, or Dorian (in any capacity) constitutes investment advice, financial advice, or a solicitation to buy or sell any financial instrument. All research and analysis is for informational and educational purposes only.
Not a Registered Investment Advisor
Ravenrock Fintech LLC is not a registered investment advisor, broker-dealer, or fund manager. Ravenrock Capital is a pre-launch vehicle and is not currently accepting capital. Any future fund operations will be subject to applicable regulatory compliance.
No Guarantee of Performance
Past analytical accuracy does not guarantee future performance. Markets are inherently unpredictable. Users of ZTrader.AI and related products assume full responsibility for their own trading and investment decisions.
Affiliate & Compensation Disclosure
Ravenrock does not accept affiliate fees or undisclosed compensation for product recommendations. Any partnerships or commercial relationships will be disclosed explicitly.
Cancellation & Rescheduling Policy
Last updated: June 2026.
Cancellation
Cancellations made more than 24 hours before the session: full credit, no fee
Cancellations made within 24 hours: session forfeited, no reschedule
Cancellations made by Ravenrock: full credit or reschedule offered, no penalty
Rescheduling
One reschedule per booking allowed, provided it is requested more than 24 hours before the original session time. Rescheduled sessions are subject to available slots.
No-Shows
Failure to attend a booked session without prior notice will be recorded. Repeated no-shows may result in restricted access to future bookings.
How to Cancel or Reschedule
Use the link in your booking confirmation email, or contact us directly via the inquiry form on this page. Include your booking reference and preferred new time if rescheduling.
First Issue — Seven Objects
Objects made for the long session.
A small, considered collection for the desk and the field. Notebooks, instruments, and a few quiet artifacts — designed first, manufactured once they earn it.
Each one earned its place by solving something specific. If it didn't make the desk quieter or the read clearer, it isn't here.
Noir Series — 01
Noir MKT Notebook
A markets edition for chart sketches, trade theses, and the notes that don't fit a spreadsheet. Hybrid grid pages, lay-flat binding that survives a real working session.
A build edition for system maps, architecture sketches, and the diagrams that happen before the code does. Same binding, dot-grid pages tuned for structure.
Machined from aluminum, finished matte black with a brass cap band. Weighted for sessions that run long. Refillable with a standard gel cartridge — built once, used for years.
The raven mark, reduced to its load-bearing geometry and cast solid in blackened steel. Small enough for a pocket, heavy enough to notice every time you reach for your keys.
A 52-card deck across checklists, risk prompts, and mental models. Pull one before a session, or shuffle when the thinking gets stale. Letterpress finish on matte stock.
A solid brass weight with hand-finished facets. No moving parts, no charge cable, no app. It holds the desk down, and gives the hand something to do while the mind works.
Beyond the first seven, a few more pieces are taking shape. Shown here as concepts, not commitments.
Noir Series
Noir Field Notes
Concept
Noir Series
Noir Chart Ruler
Concept
Armory Series
Pattern Ring
Concept
Armory Series
Logic Tile
Concept
Ravn Artifacts
Ravn Pendant
Concept
Ravn Artifacts
Ravn Card Holder
Concept
Field Kit
Operator Pouch
Concept
Desk Objects
Focus Timer
Concept
For the Curious
The complete working list.
Every name under consideration, organized by series. Most of it is just a name on a page right now.
01Noir Series
Noir MKT NotebookAvailable to notify
Noir HCK NotebookAvailable to notify
Noir Field NotesConcept
Noir Daily JournalConcept
Noir PenAvailable to notify
Noir Chart RulerConcept
Noir Notebook + Pen BundleConcept
02Armory Series
Focus CubeAvailable to notify
Signal StoneConcept
Pattern RingConcept
Logic TileConcept
Operator BeadConcept
Stress Ball / Grip ToolConcept
Pocket Puzzle ToolConcept
Magnetic Thinking BlocksConcept
03Ravn Artifacts
Obsidian Ravn Sigil KeychainAvailable to notify
Ravn CufflinksConcept
Ravn Challenge CoinAvailable to notify
Ravn PendantConcept
Ravn Pin / BadgeConcept
Ravn Card HolderConcept
Ravn Desk PaperweightConcept
04Signal Cards
Trading Checklist CardsAvailable to notify
Risk Management CardsConcept
Macro Transmission CardsConcept
Mental Model CardsConcept
Post-Trade Review CardsConcept
Builder Thinking CardsConcept
Attention Training CardsConcept
05Field Kit
Operator PouchConcept
Pen CaseConcept
Cable PouchConcept
Travel TrayConcept
Minimal Wallet / Card CaseConcept
Desk MatConcept
Carry Case — Notebook + Pen + ArmoryConcept
06Desk Objects
Focus TimerConcept
Focus StoneConcept
Chart PaperweightConcept
Mini Whiteboard / Desk BoardConcept
Mechanical CounterConcept
Analog Habit TrackerConcept
07Operator Apparel
Heavyweight Black T-ShirtConcept
Noir HoodieConcept
Cap / BeanieConcept
Technical VestConcept
Black Shirt / Inner LayerConcept
Minimal SocksConcept
08Hardware Layer
Noir EarbudsConcept
AI GlassesConcept
Voice RecorderConcept
Wearable Alert DeviceConcept
Operator Kit Device DockConcept
09Digital Companion
Noir OCR AppConcept
Ztrader Note SyncConcept
Trade Journal ScannerConcept
Mind Map ScannerConcept
Obsidian ExportConcept
Codex Entry GeneratorConcept
AI Review LayerConcept
10Bundle / Kit
Ravenrock Operator KitConcept
Ztrader Market Operator KitConcept
Noir MKT Starter KitAvailable to notify
Noir HCK Starter KitConcept
Armory Attention KitConcept
Founder Drop — Limited 100Concept
Paid Member Exclusive DropConcept
"Most of this list will never ship. That's by design — a long list is easy to write and hard to stand behind. The first seven are the test: if they hold up in someone's hands, the rest of the catalog earns the right to exist."
— Ravenrock
Pre-Production
Get notified at launch.
No store yet — just a list. When the first issue is ready to ship, this is who hears first.
No spam. One email, when it's real.
Ravenrock Capital · Client Portal
Private Access.
Restricted to research partners. All sessions are logged.
THE QUANT COOKBOOK — MODELS · DERIVATIVES · ALGORITHMS
A working reference of the models that matter. Each entry: the core equation, what it's actually for, and where it breaks. Monochrome by design — no decoration, only signal.
Math Notes · 数学笔记
The load-bearing mathematics.
Not a curriculum — a set of notes on the mathematics that actually carries weight in finance, and the precise points at which each result stops being true. Every entry: the statement (定义), why it matters (为何重要), where it fails (陷阱), and the source (文献).
Measure & Probability 测度与概率4
Measure Theory 测度论
定义
(Ω,ℱ,P): sample space, σ-algebra, measure. A filtration {ℱᵗ} is information accumulating in time. E[X|ℱᵗ] is the conditional expectation — the projection of X onto what is known at t.
为何重要
Why finance needs it: 'the information available at time t' must be a mathematical object before adaptedness, martingales, or no-arbitrage mean anything. The filtration is why a lookahead bias is a type error, not a coding error.
陷阱
Measure theory rules out pathologies that never arise in practice, and practitioners take this as evidence it is unnecessary. It is not: the whole risk-neutral apparatus is a change of measure, and you cannot change what you cannot define.
If Q ≪ P, there exists dQ/dP = Z ≥ 0 with Eᵦ[Z]=1, and Eᵪ[X] = Eᵦ[XZ]. Girsanov: under Q, Wᵗᵪ = Wᵗᵦ + ∫₀ᵗθᵔds is Brownian, where Zᵗ = exp(−∫θdW − ½∫θ²ds).
为何重要
The mathematical content of risk-neutral pricing: you do not change the world, you change the probability weights so that discounted prices become martingales. Drift disappears; volatility survives. That asymmetry is the entire pricing theory.
陷阱
Q exists because arbitrage does not; Q is unique because markets are complete. Both premises fail in reality, which is why incomplete-market pricing is a choice of Q, i.e. a choice of risk premium, dressed as mathematics.
E[Xᵗ|ℱᵔ] = Xᵔ for s ≤ t. Optional stopping: for a bounded stopping time τ, E[Xₜ] = X₀. Doob decomposition: any adapted process = martingale + predictable drift.
为何重要
American options are optimal stopping problems: V = supₜ Eᵪ[e⁻ʳₜpayoff(Sₜ)]. Optional stopping is why no betting system beats a fair game — the gambler's-ruin proof and the no-free-lunch theorem are the same theorem.
陷阱
Local martingales are not martingales. The distinction is invisible in examples and decisive in bubbles: a strict local martingale price process admits arbitrage-free bubbles where put-call parity fails. Most texts skip this; the failure mode is real.
LLN: sample mean → μ when E|X| < ∞. CLT: √n(X̄−μ) → N(0,σ²) when Var < ∞. Generalized CLT (Lévy): with infinite variance, sums converge to α-stable laws, not Gaussians.
为何重要
The two theorems everything rests on — and the exact conditions under which they do not hold. Financial returns have α ≈ 1.7 in many estimates: variance may not exist. Then the sample variance is not estimating anything; it is a random number that grows with n.
陷阱
'It's approximately normal for large n' is a statement about the tails you have already seen. Under fat tails, convergence is so slow that no realistic sample reaches the asymptotic regime — the CLT is true and useless simultaneously.
W₀=0, independent Gaussian increments Wᵗ−Wᵔ ~ N(0,t−s), continuous paths. Nowhere differentiable a.s. Quadratic variation <W>ᵗ = t — the single fact that makes Itô calculus different from Newton's.
为何重要
The canonical noise. Every diffusion model is Brownian motion warped by drift and volatility functions. Scaling: Wᵀᵗ =ᵈ √a·Wᵗ — self-similarity with Hurst H = ½.
陷阱
Real price paths are not Brownian: they jump, they cluster, and volatility itself has H ≈ 0.1 (rough), not ½. BM is the harmonic oscillator of finance — indispensable, and never actually the system.
df(t,Xᵗ) = (∂ᵗf + μ∂ₓf + ½σ²∂ₓₓf)dt + σ∂ₓf dW. The ½σ²∂ₓₓf term is the whole difference from the chain rule, and it comes from (dW)² = dt.
为何重要
The chain rule of a world where quadratic variation is nonzero. Every pricing PDE is Itô applied to a claim and then the drift set to zero by hedging. Gamma is ∂ₓₓf: the second-order term IS the option's convexity, and the source of its value.
陷阱
Itô requires continuous semimartingales. With jumps you need Itô-Lévy (an extra compensated-jump integral); with rough volatility the integrator is not a semimartingale at all and you need rough-path theory. Applying vanilla Itô outside its hypotheses is the most common silent error in the literature.
dX = μ(t,X)dt + σ(t,X)dW. Lipschitz + linear growth ⇒ strong solution, unique. Feller test decides whether X hits a boundary (why 2κθ>ξ² keeps Heston variance positive).
为何重要
The grammar in which every model in this knowledge base is written. Vasicek, CIR, Heston, SABR — all are SDEs distinguished only by their μ and σ.
陷阱
√v in the CIR/Heston diffusion is not Lipschitz at zero. Existence still holds (Yamada-Watanabe), but naive Euler discretization goes negative and crashes — hence Milstein, full-truncation, and the QE scheme. The math warned you; the code found out.
If ∂ᵗu + μ∂ₓu + ½σ²∂ₓₓu − ru = 0 with terminal condition u(T,x)=ψ(x), then u(t,x) = E[e⁻ʳ⁽ᵀ⁻ᵗ⁾ψ(Xᵗ)|Xᵗ=x].
为何重要
The bridge between PDEs and expectations — the reason you can price by Monte Carlo *or* by finite differences and get the same number. Every 'the price is a discounted expectation' statement is this theorem being invoked silently.
陷阱
The equivalence requires sufficient regularity and integrability. For payoffs with discontinuities (digitals) or unbounded growth, the naive interchange of expectation and derivative fails — which is exactly why pathwise Greeks break on digitals.
Independent stationary increments, càdlàg paths. Lévy-Khintchine: the characteristic function decomposes into drift + Gaussian + jump measure ν(dx). Variance Gamma, NIG, CGMY are the finance workhorses.
为何重要
Jumps are where fat tails come from without needing stochastic volatility. Short-dated smile steepness that diffusion cannot generate is generated instantly by a jump component.
陷阱
Markets with jumps are incomplete: you cannot hedge a jump with the underlying alone. The 'unique risk-neutral measure' vanishes, and every jump model's price is a choice among infinitely many Q's — a fact usually buried in the calibration.
Symmetric A = QΛQᵗ, real eigenvalues, orthogonal eigenvectors. Covariance matrices are PSD: λᵢ ≥ 0. Condition number κ = λₘₐₓ/λₘₐₖₖ measures how badly inversion amplifies error.
为何重要
PCA, risk factors, and portfolio optimization all reduce to eigendecomposition. Marchenko-Pastur gives the eigenvalue distribution of a *pure noise* covariance — everything inside that bulk is indistinguishable from noise.
陷阱
With N assets and T observations, sample covariance is nearly singular when N/T → 1. Markowitz then inverts a matrix whose smallest eigenvalues are pure estimation error, and amplifies them by 1/λ. This is *the* mechanism behind error-maximization — not a metaphor, a condition number.
Convex f on convex set: local min = global min. KKT conditions characterize constrained optima. Lagrangian duality gives bounds and, at strong duality, the shadow prices of the constraints.
为何重要
Portfolio construction, calibration, and most of ML training are convex or convexified. Mean-variance is a QP; risk parity is a convex program; SVI calibration is not convex and that is exactly why it is painful.
陷阱
Convexity in the *objective* says nothing about identifiability. A flat convex valley has a unique minimum that moves violently under tiny data perturbations — Heston calibration is convexity providing false comfort.
The four identities that generate every first-order condition in portfolio theory and Gaussian likelihood. Markowitz's solution w ∝ Σ⁻¹μ falls out of the first two in one line.
陷阱
Layout conventions (numerator vs denominator) transpose everything. Half the sign errors in quant papers are layout errors; the other half are forgetting that Σ is symmetric, which halves the derivative.
φₓ(u) = E[eᵢᵘₓ]. Carr-Madan: option price = FFT of a damped characteristic function. Pricing cost drops from one-strike-at-a-time to a whole strike vector per transform.
为何重要
Any model with a known characteristic function (Heston, VG, CGMY, rough Bergomi via approximation) prices in O(N log N). This is why affine models dominate production: not accuracy, tractability.
陷阱
The damping parameter α must sit inside a model-dependent admissible range or the integral diverges. Practitioners tune it by trial; the theory tells you the range. Also FFT gives a *grid* of strikes, not the strikes you want — interpolation error re-enters through the back door.
E[BᴴᵗBᴴᵔ] = ½(t²ᴪ + s²ᴪ − |t−s|²ᴪ). H > ½: persistent. H < ½: anti-persistent, rough. Not a semimartingale for H ≠ ½ — no Itô calculus, no equivalent martingale measure.
为何重要
Log-volatility is empirically fBm with H ≈ 0.1 across every asset class tested. This is the single most robust empirical finding in volatility modelling since the smile itself.
陷阱
fBm in the *price* admits arbitrage (that's why it was rejected in the 1990s); fBm in the *volatility* does not (volatility is not tradeable directly). The distinction took two decades to become common knowledge, and rough volatility only exists because of it.
Statistical models as manifolds; Fisher information as the metric tensor gᵢ₃ = E[∂ᵢlog p · ∂₃log p]. KL divergence is (locally) squared distance. Natural gradient follows the manifold, not the parameterization.
为何重要
Explains why Adam-style preconditioning works, why parameterization matters in calibration (SVI's parameters are a bad chart on a fine manifold), and gives Cramér-Rao a geometric meaning: curvature bounds estimator precision.
陷阱
Beautiful, and rarely load-bearing in production. Included because it is the correct language for a question practitioners ask constantly and answer badly: 'why does my model care which coordinates I fit it in?'
Ensemble average E[X] vs time average lim(1/T)∫Xᵗdt. They coincide only under ergodicity. Multiplicative dynamics (compounding!) are non-ergodic: E[growth] > typical growth, and the gap is ½σ².
为何重要
The mathematical root of Kelly: maximizing E[wealth] and maximizing the growth rate of *your* wealth are different problems, and only the second is yours. It is also why volatility drag is not a fee — it is the difference between two averages.
陷阱
Expected-value reasoning is the default in economics and is simply wrong for non-ergodic processes. The St. Petersburg paradox, the equity premium puzzle, and half of behavioral finance are what a time-average problem looks like when solved with ensemble tools.
The macro reference: regimes, transmission chains, the indicators that matter, and central-bank playbooks. Every entry gives the mechanism (机制) and where it traps you (陷阱). Fully cross-linked — follow the underlines.
Regimes & Cycles 周期与状态4
Growth-Inflation Quadrants 增长-通胀四象限
机制
The base regime map: rising/falling growth × rising/falling inflation gives four states, each favoring different assets — reflation (equities, commodities), stagflation (commodities, cash), deflation (bonds), goldilocks (equities, credit).
陷阱
Regime identification is only knowable with lag; the trade is positioning for the transition, not the state. Most quadrant frameworks die at the turning points they were built to catch.
Global Liquidity Cycle 全球流动性周期
机制
Aggregate central bank balance sheets + private credit creation + dollar funding conditions. Liquidity leads asset prices; the mechanism runs through collateral values and risk appetite, not textbook money supply.
陷阱
Liquidity is measured a dozen ways and the definitions disagree at turning points — pick your gauge before the trade, not after.
Credit Cycle 信用周期
机制
Expansion → leverage builds → underwriting degrades → default cycle → deleveraging → repeat. Credit spreads are the cycle's thermometer; the corporate refinancing wall is its calendar.
陷阱
The cycle is obvious in hindsight and contested in real time; spreads stay tight until they gap — carry until the steamroller.
Dollar Cycle 美元周期
机制
The dollar is the world's funding currency: dollar up = global tightening for everyone who borrowed in it. EM stress, commodity weakness, and reflexivity between dollar strength and dollar demand.
陷阱
Dollar cycles run years and reverse on policy divergence shifts that are only clear after the turn — the consensus dollar view is usually late-cycle.
The lag is the trap: by the time hikes visibly bite, the next easing cycle is already being priced. Trading the mechanism means trading the market's model of the mechanism.
QE / QT 量化宽松与紧缩
机制
Central bank buys duration → term premium compresses → portfolio rebalancing pushes investors out the risk curve. QT reverses it — slowly, until reserve scarcity makes it fast (repo, Sep 2019).
陷阱
QE's effect is contested even now; QT's floor (ample reserves) is only found by breaking something. The mechanism is discovered live, in production.
Verbal → rate policy → actual FX purchases. Effectiveness depends on whether intervention aligns with fundamentals or fights them; sterilized intervention against trend mostly burns reserves (BOJ 2022, successful only when Fed pivot aligned).
陷阱
Intervention levels become market targets — announcing a line invites the test of the line. See reflexivity.
Oil Shock Transmission 油价冲击传导
机制
Oil up → headline inflation → inflation expectations → central bank reaction → real income squeeze → demand destruction → oil down. The loop is self-limiting; the timing of each leg is not.
陷阱
Supply shocks and demand shocks look identical in price and opposite in trade construction — diagnose the shock before positioning the curve.
Indicators That Matter 关键指标5
Yield Curve Inversion 收益率曲线倒挂
机制
2s10s or 3m10y below zero has preceded every US recession since the 1960s. Mechanism: market prices future cuts below current policy = market expects the cycle to break.
图
陷阱
The lag runs 6–24 months and the signal fires once — un-inversion (bear steepening into weakness) is historically the closer recession signal. Inversion is the warning; steepening is the event.
IG and HY spreads over treasuries: the price of default risk and the credit cycle's real-time gauge. Spreads lead equities at turns more often than the reverse.
陷阱
Spread indices hide composition shifts — the index tightens while the weakest names quietly fall out of it. Survivorship inside the gauge itself.
Breakevens & Real Rates 盈亏平衡通胀与实际利率
机制
Breakeven = nominal minus TIPS yield: the market's inflation forecast. Real rates are the true price of money — gold, tech duration, and EM all trade off real rates, not nominals.
陷阱
Breakevens embed liquidity and risk premia, not pure expectation — in stress they say more about TIPS liquidity than inflation.
PMI & Diffusion Indices 采购经理指数
机制
Above/below 50 = expansion/contraction of breadth, not magnitude. New orders minus inventories is the forward-looking spread inside the number.
陷阱
Soft data diverges from hard data for quarters at a time; PMIs measure sentiment about activity, which reflexively feeds activity.
Term Premium 期限溢价
机制
Compensation for holding duration risk beyond expected rates. Unobservable — estimated (ACM, Kim-Wright), never measured. Rising term premium = bond vigilantes repricing fiscal or inflation risk.
陷阱
Every term premium model disagrees; the concept is indispensable and unmeasurable — a load-bearing fiction.
Dual mandate weighted by regime: inflation-fighting mode (2022) vs employment-protecting mode (2019). The function itself shifts — reading the Fed means reading which mandate currently dominates and what pain threshold ends it.
陷阱
The reaction function is reflexive: markets price the function, the Fed reacts to market pricing of it. Fed watching is a hall of mirrors with a policy rate at the end.
BOJ: YCC and the Yen Trilemma 日银与日元三难
机制
Yield curve control caps JGB yields → BOJ owns the curve → yen absorbs all the pressure. The trilemma: defend the peg, defend the currency, or import inflation — pick two, and one of them breaks.
陷阱
Exit from YCC is a one-way door priced in basis points until it's priced in percent. Positioning for BOJ normalization has been the widow-maker for two decades — until it wasn't.
PBoC Toolkit 人行工具箱
机制
RRR cuts, MLF, targeted lending, CNY fixing band. Quantity tools over price tools; policy transmits through state banks and window guidance, not market rates — Western central bank frameworks map poorly here.
陷阱
Chinese data requires its own verification layer; the policy signal is often in what's NOT eased. See the 12-vector integrity check methodology.
FX & Global Flows 汇率与资本流动3
Carry Trade 套息交易
机制
Borrow low-yield currency, park in high-yield. Profits from rate differential while spot holds; the yen has funded a generation of it. Carry is short volatility by construction.
陷阱
Carry unwinds are nonlinear: years of pennies, days of steamrollers. The funding currency rallies hardest exactly when everything else falls — correlation goes to one, against you.
Deficit countries import capital; the flow's composition (FDI vs portfolio vs hot money) determines fragility. Sudden stops, not deficits, cause crises.
陷阱
The US deficit is sustainable until reserve currency status isn't — a threshold with no ex-ante marker. Every EM crisis playbook mispredicts the US because the funding currency writes different rules.
Petrodollar & Reserve Recycling 石油美元与储备循环
机制
Commodity exporters earn dollars → recycle into treasuries and risk assets → funds the importer of the commodities. The loop's slow erosion (local-currency settlement, gold accumulation) is a decade trade, not a headline trade.
陷阱
De-dollarization is structurally real and perpetually overpriced as an event — the exit is measured in basis points per year.
Glossary · 宏观术语表8
Reflexivity 反身性
定义
Market prices change the fundamentals they supposedly reflect: prices → behavior → fundamentals → prices. Soros's frame and the reason macro models embed their own falsification — see the philosophy page for the full treatment.
Low-probability, high-impact events beyond what normal distributions permit. The black swan problem: the tails dominate long-run outcomes and are absent from the sample you calibrated on.
Nominal rate minus expected inflation — the true price of money. The single most important macro price: gold, duration, growth equities, and EM all reprice off real rate moves.
Liquidity 流动性 (macro sense)
定义
In macro: the ease of funding and collateral conditions systemwide, not single-asset depth. Liquidity crises are funding crises — assets are sold not because views changed but because someone's margin call arrived.
Risk Premium 风险溢价
定义
Expected excess return for bearing a risk: equity, term, credit, carry. Premia are harvestable, time-varying, and occasionally negative — the harvest pays until the regime that generated it ends.
A period where one set of correlations and reaction functions holds. All models are regime-conditional; the model's death certificate is dated the day the regime changed and diagnosed two quarters later.
Funding & Basis 资金与基差
定义
Gaps between related instruments (FX basis, Treasury cash-futures) that measure funding stress. Basis blowouts are the plumbing screaming before the living room floods — March 2020's first signal was in the pipes.
Volatility Regime 波动率状态
定义
Vol clusters and switches between calm and stress states. Short-vol strategies harvest the calm state and donate it back at the switch — see carry trade, same trade in different clothes.
Trader Handbook · 交易员手册
The rules that keep you in the game.
Hedge-fund desk know-how, distilled: sizing, construction, execution, discipline, psychology. Every entry gives the rule (法则) and the price of ignoring it (代价). Cross-linked into the Macro Codex and the λ Quant Cookbook.
Position Sizing & Risk 仓位与风控4
Position Sizing Before Conviction 仓位先于观点
法则
Size is the only variable fully under your control. Decide maximum loss per trade (in R, not dollars) before entry; conviction adjusts within that ceiling, never above it. Kelly gives the theoretical ceiling — professionals run quarter-to-half Kelly because parameter error compounds.
代价
The account-killer is never the thesis, it's the size. Every blowup post-mortem reads the same: right idea available at survivable size, taken at unsurvivable size.
Stop distance × position size = fixed R. Wide stop, small size; tight stop, larger size — same risk. Place stops where the thesis is invalidated, not where the pain starts; a stop at 'max pain' is a donation to whoever ran it.
代价
Moving a stop away from price is re-underwriting the trade at a worse price with worse information. If you wouldn't initiate here, you shouldn't be holding here.
Correlation Is Your Real Position 相关性才是真实仓位
法则
Five trades that all need the dollar lower are one trade at 5x size. Aggregate exposure by driver (real rates, liquidity, growth), not by ticker. Stress the book against regime shifts, not against yesterday's covariance.
代价
Diversification measured in calm markets is fiction — in stress, correlation goes to one precisely because everyone diversified the same way.
Drawdown Protocol 回撤纪律
法则
Pre-commit the ladder: at -5% cut gross by a third, at -10% halve it, at -15% flat and full stop for review. The ladder exists because judgment degrades exactly when it's most needed — you write the rules for the person you'll be at -12%, not the person you are today.
代价
Trading through a drawdown 'to make it back' converts a drawdown into a career event. The market doesn't know your high-water mark.
Trade Construction 交易构建4
Write the Thesis Before the Ticket 先写论点后下单
法则
One page: what the market misreads (misread), the mechanism that corrects it, the pressure point, the expression, and — mandatory — the falsification condition: what price or data kills it. Undated theses and unfalsifiable theses are opinions, not trades.
代价
If you can't state what would prove you wrong, you don't have a trade — you have an identity. Identities average down.
Expression > Direction 表达优于方向
法则
Right view, wrong instrument is a losing trade. Rank expressions by asymmetry: options when vol is cheap relative to the scenario, futures when timing confidence is high, spreads when the relative leg is the actual insight. The best expression often survives being early; the worst dies of carry before the thesis matures.
代价
Retail trades direction; desks trade the distribution. Paying theta for a thesis with no catalyst date is renting a house you may never occupy.
Asymmetry or Nothing 非对称或不做
法则
Minimum 3:1 payoff-to-risk at entry, honestly marked — using realistic exits, not fantasy targets. Convexity is the desk's structural edge: risking 1R for capped 1.5R requires a hit rate no one sustains.
代价
Asymmetry rots silently as price moves: the 3:1 at entry is 1:1 after the first leg up. Re-underwrite or take profit — holding a decayed asymmetry is a new trade you never approved.
Scaling In / Out 分批进出
法则
Enter in thirds: probe, confirm, complete — the market pays you information between tranches. Exit asymmetrically: take partials into strength at pre-set levels, trail the remainder. The goal is never the perfect exit; it's a repeatable one.
代价
Averaging down is scaling-in's evil twin: same mechanics, opposite information regime — you're adding because the market disagrees, funded by hope.
Execution Craft 执行工艺3
Don't Telegraph 隐藏足迹
法则
Iceberg what must be worked; randomize slice timing; never leave a resting order that maps your full intent at one price. In thin markets your order IS the market — market impact starts before your first fill, in the information your order leaks.
代价
Predictable execution is a subsidy to faster players. If your TWAP is guessable, it will be front-run by construction — see adverse selection.
Trade When Liquidity Trades 在流动性在场时交易
法则
Size executes at the opens, the closes, and the overlaps (London-NY). Off-hours fills are borrowed from tomorrow's slippage. For macro expressions, the event calendar is the liquidity calendar: CPI, FOMC, payrolls redraw the book within seconds.
代价
The fill you get at 3am Tokyo in EURUSD is not a price — it's a quote against you. Illiquidity converts good ideas into bad P&L via pure friction.
Slippage Is a Line Item 滑点入账
法则
Track implementation shortfall per trade: decision price vs achieved price. It's the desk's invisible tax — a strategy with 1.2 Sharpe on paper and 40bp round-trip slippage may be a zero. Measure it or it eats you unmeasured.
代价
Backtests without execution costs are marketing. The gap between simulated and realized P&L is almost always execution, not signal.
Desk Discipline 交易台纪律4
Pre-Trade Checklist 交易前清单
法则
Before any ticket: thesis written and falsifiable · size within R budget · correlation to existing book checked · expression ranked against alternatives · exit ladder pre-set · event calendar cleared. Sixty seconds that filter out the majority of future regrets.
代价
The checklist's enemy is urgency. A trade that can't survive sixty seconds of process was an impulse wearing a thesis.
The Journal Is the Edge 日志即优势
法则
Log every trade: thesis, size, entry, emotional state, exit, and the honest reason for the exit. Review weekly for patterns — the journal converts anecdotes into data about the only system you can't backtest: yourself.
代价
Un-journaled lessons repeat until the tuition is paid in size. Your memory launders your mistakes; the journal doesn't.
Post-Mortems Without Mercy 无情复盘
法则
Separate decision quality from outcome: good process losing money is variance; bad process making money is a loan from the market at usurious interest. Post-mortem winners as hard as losers — the most dangerous trades are the undeserved wins that size up the next mistake.
代价
Outcome bias is the desk's chronic disease: it promotes lucky recklessness and fires disciplined variance.
Pre-open: overnight moves, calendar, book risk vs plan. Session: execute the plan, log deviations. Post-close: P&L attribution — how much was thesis, how much was regime, how much was noise. The routine is boring by design; boredom is what discipline feels like from inside.
代价
Days without structure become P&L-watching, and P&L-watching becomes over-trading. The screen rewards activity; the account rewards selectivity.
Psychology & P&L 心理与损益3
Revenge Trading 报复性交易
法则
The sequence: loss → identity threat → urgent need to be made whole → size up on a worse idea. Circuit-breaker rule: after any 2R+ loss, mandatory flat period (hours, not minutes) before the next ticket. The market will still be there; the tilt won't.
代价
Losses want repayment from the same table that took the money. The account doesn't remember where losses came from — only the ego does.
Win-Streak Risk 连胜风险
法则
Confidence expands faster than edge. After a streak: audit whether recent wins were thesis or regime — a bull tape makes everyone's process look like alpha. Streaks are when sizing discipline earns its keep, because everything in you says the ceiling no longer applies.
代价
More accounts die in the euphoria after the streak than in the drawdown that follows — the drawdown merely collects what euphoria borrowed.
Flat Is a Position 空仓也是仓位
法则
No trade is a full allocation to optionality. When the regime is unreadable, when the book fights the calendar, when you're compromised (tired, tilted, distracted) — flat outperforms whatever you would have done. Sitting still is the hardest active decision on the desk.
代价
The pressure to 'do something' is the P&L of others (brokers, platforms, the audience) extracted from you. Edge is episodic; exposure shouldn't be constant.
Career & Meta 职业与元规则3
Survival Is the Strategy 生存即策略
法则
Compounding requires being present for it. Every rule above reduces to one constraint: never take a risk that removes you from the game — not in size, not in leverage, not in career terms. The trader who compounds 15% for twenty years beats almost everyone who ever printed a triple-digit year.
代价
Tail risk applies to careers, not just books. The spectacular year and the terminal year are frequently the same year.
Edge Decays — Audit It 优势会衰减
法则
Every edge has a half-life: crowding, regime change, structural repair of the inefficiency. Schedule the audit — quarterly, honestly: is realized expectancy tracking the model, and what's the evidence this still works? Retiring a dead strategy is a profit, not an admission.
代价
Strategies are defended longest by those who built them. Sunk cost plus identity is why desks run dead edges for years — see reflexivity applied to yourself.
Know What You Don't Trade 知所不为
法则
Define the negative space: instruments you don't understand, regimes you can't read, hours you don't work, sizes you never touch. The 'no' list is more stable than the 'yes' list and does more compounding work.
代价
Every legendary blowup involved someone excellent at X deciding they were probably also excellent at Y. Competence doesn't cross-collateralize.
Glossary · 交易术语表7
Edge 优势
定义
A repeatable, identifiable reason the expected value of your trades is positive: informational, analytical, structural, or behavioral. If you can't name which one it is, it's probably variance wearing a suit.
Expectancy 期望值
定义
(hit rate × avg win) − (loss rate × avg loss). The only long-run number that matters. Hit rate alone is vanity — a 30% hit rate with 4:1 payoffs is a career; 70% with inverted payoffs is a countdown.
R-Multiple R倍数
定义
P&L expressed in units of initial risk: risking $10k and making $30k = +3R. Denominating in R makes trades comparable across size and instrument, and turns the journal into a dataset.
Max Adverse Excursion 最大不利偏移
定义
How far a trade goes against you before resolving. MAE distributions across the journal reveal whether stops sit where trades actually fail — evidence-based stop placement instead of round-number folklore.
Hit Rate vs Payoff 胜率与赔率
定义
The fundamental trade-off pair: trend systems run low hit rates and fat payoffs; mean-reversion runs the mirror. Neither is superior — but each demands a different psychology, and mismatching temperament to system is a slow bleed.
Portfolio Heat 组合热度
定义
Sum of open risk across all positions (in R) if every stop is hit simultaneously. The book-level sizing constraint most retail traders have never computed — desks cap total heat before any single trade's merits are discussed.
Tilt 失控状态
定义
Emotionally compromised decision-making after losses (or wins). The trading version of the poker term. Tilt is not a character flaw; it's a physiological state — and the only reliable counter is pre-committed rules that don't consult your feelings.
Code & Algorithms · 编程与算法
Systems that survive production.
Algorithms, trading-systems engineering, quant Python, infrastructure, and ML-for-markets. Every entry: the point (要点) and the trap (陷阱). Cross-linked into λ Quant, Macro, and the Handbook.
Algorithms & Complexity 算法与复杂度6
Big-O in Practice 复杂度实战
要点
O(1) hash lookup, O(log n) binary search, O(n log n) sort, O(n²) nested loops. The rule on a trading system: anything touching the hot path (tick processing, signal eval) must be O(1) or O(log n); O(n) scans belong in batch jobs.
陷阱
Big-O hides constants: a cache-friendly O(n) array scan routinely beats a pointer-chasing O(log n) tree in real hardware. Measure, don't recite.
Hash Maps 哈希表
要点
The workhorse: O(1) average lookup/insert. In market data: symbol → order book, order id → order state. Python dict, JS object/Map — most business logic is hash map choreography.
陷阱
Worst case O(n) on collision floods; and iteration order assumptions differ by language — Python dicts preserve insertion order, others don't. Never rely on it across systems.
Heaps & Priority Queues 堆与优先队列
要点
O(log n) insert/extract-min. Canonical in matching engines (best bid/ask), event schedulers in backtesters, top-K queries. Python heapq, or two heaps for a live order book.
陷阱
A heap gives you the top, not sorted order — repeatedly popping to 'sort' is O(n log n) and destroys the structure. Wrong tool for range queries; that's a balanced tree's job.
Dynamic Programming 动态规划
要点
Break a problem into overlapping subproblems, cache the answers. In finance: optimal execution (Almgren-Chriss discretized), American option exercise (backward induction on trees), Kelly with constraints.
陷阱
DP's trap is state-space explosion — three state variables and your table no longer fits in memory. The art is finding the minimal sufficient state, not writing the recursion.
Graph Algorithms 图算法
要点
BFS/DFS for reachability, Dijkstra for shortest paths, topological sort for dependency ordering. In practice: currency arbitrage = negative cycle detection (Bellman-Ford on log prices), settlement chains, dependency graphs in build systems.
陷阱
Triangular arbitrage via Bellman-Ford is the classic interview answer and a production trap: by the time you detect the cycle, it's gone. The algorithm is right; the latency assumption is fiction.
Sorting: When It Matters 排序的真实场景
要点
You almost never write a sort — you choose one: Timsort (Python/Java default) exploits pre-sorted runs, radix beats comparison sorts on fixed-width keys (timestamps!). Sorting a day of ticks by exchange timestamp: radix wins big.
陷阱
Sorting inside a loop is the most common accidental O(n² log n) in quant code. Sort once, index forever.
Trading Systems Engineering 交易系统工程6
Backtesting Architecture 回测架构
要点
Two schools: vectorized (pandas/numpy, fast, fine for signals on bars) vs event-driven (tick-by-tick simulation, order lifecycle, realistic fills). Rule: research in vectorized, validate in event-driven before capital.
陷阱
Vectorized backtests silently peek: same-bar entry+exit, fills at close prices you couldn't have known. The gap between the two architectures IS your lookahead bias, quantified.
The two backtest killers: using information not yet available (revised data, close prices intraday), and testing on today's index constituents (companies that died are gone from the sample). Point-in-time databases exist precisely for this.
陷阱
The most dangerous lookahead is subtle: normalizing by a full-sample mean, tuning on the whole set then 'validating' on part of it. If Sharpe > 3 in backtest, hunt for the leak before celebrating.
Timestamps Are Hard 时间戳之难
要点
Exchange time vs receive time vs process time — three clocks, three stories. Always store UTC + exchange timezone separately; DST transitions have corrupted more P&L attributions than any bug class. Nanosecond precision matters at HFT, milliseconds for everyone else.
陷阱
Joining two data sources on timestamp without specifying WHICH timestamp is a silent alignment error — your 'signal' may be the data vendor's clock skew.
Order Book Data 订单簿数据
要点
L1 = best bid/ask, L2 = depth by level, L3 = individual orders. Storage explodes at L2+: a liquid future does millions of updates/day. Snapshot + incremental deltas is the standard; rebuild logic must handle gaps and crossed books.
陷阱
Backtesting market-making on L1 data is fantasy — queue position, the thing that decides your fills, is invisible above L3. Know what your data can and cannot answer.
Data Pipeline Discipline 数据管道纪律
要点
Raw → validated → adjusted → research-ready, each stage immutable and versioned. Corporate actions (splits, dividends) adjust historically; a price series without adjustment metadata is a lie waiting for a join.
陷阱
Silent forward-fill is the pipeline's carbon monoxide: missing data becomes stale data becomes a mean-reversion signal that trades gaps in your vendor's coverage.
State & Recovery 状态与恢复
要点
A trading process dies mid-session: what does restart look like? Event-sourcing (replay the log) or checkpoint+journal. Positions must reconcile against the broker, not against your own memory of what you sent.
陷阱
The bug is never in the happy path. Systems fail at reconnect, partial fill during restart, duplicate order on retry — design the crash first, the strategy second.
Python for Quant Python量化实战4
Pandas Patterns That Scale Pandas模式
要点
Vectorize or die: .apply() with a Python lambda is a for-loop in a trench coat. groupby-transform for cross-sectional ops, merge_asof for point-in-time joins (THE quant join), categoricals for symbol columns — 10x memory savings.
陷阱
Chained indexing (df[a][b] = x) silently writes to a copy — the SettingWithCopyWarning everyone ignores is telling you your backtest may be reading unmodified data.
NumPy Vectorization 向量化
要点
Think in arrays: rolling windows via stride tricks or numba, broadcasting instead of loops, einsum for anything tensor-shaped. A 1000x speedup from removing one Python loop is normal, not exceptional.
陷阱
Premature vectorization of unreadable one-liners costs more in debugging than it saves in runtime. Vectorize the hot loop the profiler found, not the code you suspect.
Async & Concurrency 异步与并发
要点
asyncio for I/O-bound (websocket feeds, REST polling), multiprocessing for CPU-bound (parallel backtests), threads mostly for legacy blocking libs. The GIL means Python threads don't parallelize computation — a fact rediscovered weekly.
陷阱
Async code that touches shared state without locks works perfectly in testing and corrupts positions in production. Message-passing (queues) over shared memory, always.
Types, Tests, Contracts 类型/测试/契约
要点
Type hints + mypy catch the None-slips-through bug class before runtime. Property-based testing (hypothesis) finds edge cases you didn't imagine: negative prices, empty frames, DST days. A pricing function without tests is an opinion.
陷阱
100% coverage of the wrong assertions is theater. Test the invariants that matter: P&L conservation, position reconciliation, no-arbitrage bounds on your own outputs.
Production & Infrastructure 生产与基建4
Deploy Discipline 部署纪律
要点
The boring sequence wins: build → test → deploy → verify → (rollback path ready). PM2 for Node process management, nginx as reverse proxy, systemd for daemons. Never edit in production; the server is a cattle, not a pet.
陷阱
The deploy that skips `npm run build` ships yesterday's code with today's confidence. If the sequence isn't a script, it isn't a sequence — it's a mood.
Logging & Observability 日志与可观测
要点
Structured logs (JSON), correlation ids across services, log levels that mean something. For trading: every order event logged with full context BEFORE the action — the log is your flight recorder when the exchange disputes a fill.
陷阱
Logging inside the hot loop at DEBUG level is a latency tax you pay forever. And logs without timestamps in UTC are puzzles, not records.
Secrets & Keys 密钥管理
要点
API keys in environment variables or a vault, never in code, never in git history (git filter-repo exists because everyone learns this late). Separate keys per environment; trading keys get IP whitelists and withdrawal locks.
陷阱
The leaked key isn't the one you committed — it's the one in the .env you copied to a backup, the notebook output, the error trace sent to a logging SaaS.
Failure Modes 故障模式设计
要点
Timeouts on every external call, exponential backoff with jitter, circuit breakers, idempotency keys on order submission. The network WILL partition mid-order; 'exactly once' is a lie — design for 'at least once + dedupe'.
陷阱
Retry without idempotency is how one order becomes five. The double-fill from an aggressive retry loop has bankrupted more small shops than bad strategies have.
ML for Markets 机器学习×市场4
Overfitting Is the Default 过拟合是默认态
要点
Financial data: low signal-to-noise, non-stationary, one history. Any sufficiently flexible model WILL memorize noise. Defenses: fewer parameters than you want, regularization, and skepticism proportional to backtest beauty.
陷阱
The model with 12 features and Sharpe 4 in-sample is not a discovery — it's a fitting exercise. De Prado's estimate: most published factor findings are false.
Standard K-fold leaks: overlapping samples share information across the train/test boundary. Purged K-fold (drop samples near the boundary) + embargo periods. Walk-forward is the honest default: train on past, test on strictly-after.
陷阱
Shuffled CV on time series is lookahead with extra steps — the most common fatal flaw in ML-for-trading papers and Kaggle-trained hires.
Any feature computed with future information: full-sample z-scores, labels leaking into features via joins, target encoding fit on the whole set. The tell: performance too good, live results at random.
陷阱
Leakage hides in preprocessing more than in features — the scaler fit on train+test is invisible in the code diff and fatal in production.
Non-Stationarity 非平稳性
要点
The market that generated your training data no longer exists. Retraining schedules, regime detection (HMM, change-point), and ensembles weighted by recency are mitigations — not solutions. There is no solution.
陷阱
A model's silent decay looks exactly like bad luck for months. Log prediction-vs-realized continuously; the divergence chart is your model's vital signs.
Glossary · 工程术语表6
Idempotency 幂等性
定义
An operation safe to repeat: applying it twice equals applying it once. The property that makes retries safe — order submission without an idempotency key is a loaded gun.
Race Condition 竞态条件
定义
Outcome depends on uncontrolled timing between concurrent operations. In trading: two threads reading position, both deciding to hedge, double hedge. Locks, queues, or single-writer designs are the cures.
Profiling 性能剖析
定义
Measuring where time is actually spent before optimizing. cProfile/py-spy for Python. The profiled hot spot is almost never where intuition pointed — optimize evidence, not vibes.
Technical Debt 技术债
定义
Speed borrowed from the future at compound interest. Some debt is rational (prototype to validate edge); unlogged debt is how a codebase becomes archaeology. Track it like leverage.
Vectorization 向量化
定义
Replacing explicit loops with array operations executed in compiled code. The single highest-leverage performance skill in quant Python — and the reason numpy exists.
Event Sourcing 事件溯源
定义
Store the sequence of events, derive state by replay. Order lifecycle as an append-only log: auditability, crash recovery, and time-travel debugging for free.
AI Frontier · 人工智能前沿
The machine, demystified.
LLMs, transformers, reinforcement learning, and the frontier — what each piece actually does and where the marketing ends. Cross-linked into Code and λ Quant.
LLM & Transformers 大模型与变换器5
Attention Mechanism 注意力机制
公式
Attention(Q,K,V) = softmax(QKᵗ/√dₖ)V · multi-head: h parallel projections, concat, project. Complexity O(n²d); FlashAttention makes it IO-aware, exact, and memory-linear.
图
要点
Q·K similarity decides where information flows; V carries the content. Self-attention lets every token read every other token in one step — the O(n²) matrix that replaced recurrence and made parallel training possible.
陷阱
O(n²) in sequence length is the architecture's tax: context windows are expensive by construction. Every 'infinite context' claim is an approximation (sparse, linear, sliding) trading exactness for reach.
Attention + FFN + residual connections + layer norm, stacked. Decoder-only (GPT lineage) won the generative war: next-token prediction on internet-scale text turns out to be a general-purpose learning objective.
陷阱
The architecture is 2017-vintage and nearly unchanged — the gains since are data, scale, and post-training. Attributing capability jumps to architectural magic misreads where the leverage actually is.
L(N,D) ≈ E + A/Nα + B/Dβ, α≈0.34, β≈0.28 (Chinchilla). Compute-optimal: D∗ ≈ 20·N — twenty tokens per parameter. Kaplan's L(C) ∝ C⁻0⋅05 set the pre-Chinchilla trajectory.
要点
Loss falls as a power law in parameters, data, and compute (Kaplan, then Chinchilla: most models were undertrained, not undersized). Compute-optimal ratios reshaped the field: data became the binding constraint.
陷阱
Power laws in loss ≠ power laws in capability — downstream abilities emerge in jumps the loss curve doesn't show. Extrapolating the curve tells you the loss, not what the model can do.
BPE/SentencePiece chop text into subword units. The model never sees characters — it sees token ids. Why LLMs miscount letters, why Chinese costs more tokens per word, why 'strawberry' has three r's is hard.
陷阱
Tokenizer choices are frozen at pretraining and haunt everything downstream: arithmetic, rhyming, code indentation. Many 'reasoning failures' are tokenization artifacts wearing a costume.
Autoregressive generation recomputes nothing: keys/values of past tokens are cached. Memory scales with context × layers — the real constraint on serving long contexts. Speculative decoding, batching, quantization are the serving trinity.
陷阱
Latency-per-token and throughput trade against each other in batch serving; the demo is fast because it's alone. Production inference economics, not model quality, decide what ships.
Next-token prediction over trillions of tokens. The loss is simple; the engineering is not: data curation and dedup matter more than architecture tweaks. The base model is a simulator of its corpus, nothing more and nothing less.
陷阱
Data contamination silently inflates every benchmark — the model has often seen the test. Treat leaderboard deltas under a few points as measurement noise.
RLHF: maxₚ E[rφ(x,y)] − β·KL(πₚ||πᵗᵗᵗ). DPO collapses it: L = −logσ(β[logπθ(yₜ|x)/πᵗ(yₜ|x) − logπθ(yₗ|x)/πᵗ(yₗ|x)]) — preference optimization without an explicit reward model.
要点
Reward model from human preferences, then policy optimization (PPO) against it — or skip the RL and optimize preferences directly (DPO). This is what turned base-model autocomplete into an assistant.
陷阱
Optimizing a learned reward invites reward hacking: the policy exploits the reward model's blind spots. Sycophancy is not a bug of alignment — it's the reward model's preference, faithfully maximized.
Policy gradient: ∇J = E[∇logπθ(a|s)·A(s,a)]. PPO clips the ratio: min(rᵗA, clip(rᵗ,1±ε)A), ε≈0.2 — trust region by scissors. Q-learning: Q(s,a) ← Q + α[r + γmax Q(s′,·) − Q].
要点
Agent, environment, reward: policy gradient (REINFORCE, PPO) learns behavior from delayed feedback; Q-learning learns state-action values. Deep RL cracked Go and Atari; in markets it meets non-stationarity and mostly loses.
陷阱
Reward design IS the problem: agents optimize the metric, not the intent. Sparse rewards don't train; dense rewards get hacked. RL for trading founders on a regime-shifting environment with one non-repeatable history.
W′ = W₀ + BA, B∈Rᵗ×ʳ, A∈Rʳ×ᵗ, rank r ≪ d. Trainable params drop ~10,000x on GPT-3-scale; merged at inference = zero latency cost. QLoRA: 4-bit base + LoRA = 65B on one 48GB GPU.
要点
Full fine-tuning updates everything; LoRA freezes weights and trains low-rank adapters — 100x fewer trainable parameters, mergeable, stackable. The default for domain adaptation on a budget.
陷阱
Fine-tuning teaches style and format far better than it teaches facts — knowledge injection via fine-tuning is unreliable; that's what retrieval is for. Catastrophic forgetting taxes every gradient step.
L = α·CE(y, σ(zₜ/T)) + (1−α)·CE(y, labels), temperature T softens the teacher's logits — the 'dark knowledge' lives in the wrong-answer probabilities.
要点
Student model trained on teacher outputs (logits or generations). How capability compresses downmarket: frontier-model behavior at a fraction of the inference cost. The moat question of the decade — see the distillation-moat thesis.
陷阱
The student inherits the teacher's blind spots plus its own compression artifacts. Distilling from distillations compounds drift — the photocopier-of-a-photocopier problem at model scale.
Retrieve relevant chunks, stuff them in context, generate grounded answers. Embedding search + reranking + chunking strategy. The standard fix for knowledge freshness and hallucination on private corpora.
陷阱
RAG quality is retrieval quality: bad chunking or embedding mismatch and the model confidently synthesizes from irrelevant context. Most 'hallucinations' in RAG systems are retrieval failures upstream.
LLM in a loop: plan, call tools, observe, iterate. Function calling, code execution, browsing. Reliability compounds inversely: a 95%-per-step agent fails 40% of 10-step tasks — the multiplication problem is the field's wall.
陷阱
Agent demos cherry-pick the happy path. Production agents need verification layers, checkpoints, and human gates precisely because errors compound — architecture for failure, not for the demo.
The discipline above prompting: what enters the window, in what order, with what structure — system prompts, memory compression, pointer-based storage, kernel files. Managing the model's working memory as an engineered resource.
陷阱
Context is not free attention: models attend unevenly (lost-in-the-middle), and stale context poisons more than it informs. Curation beats accumulation — the art is what you leave out.
You cannot improve what you cannot measure: golden sets, LLM-as-judge, regression suites on real failure cases. The eval set is the actual spec of your system — everything else is vibes.
陷阱
LLM-as-judge inherits judge biases (verbosity, position, self-preference). And public benchmarks are marketing surfaces — internal evals on your own distribution are the only ones that predict your production.
The model outputs fluent falsehoods because it models plausibility, not truth. Mitigations: retrieval grounding, verification layers, uncertainty prompting, structured citation. Elimination is not on the menu; management is.
陷阱
Confidence and correctness are uncorrelated at the output layer — the fluency that makes LLMs useful is the same property that makes their errors persuasive. Verification-first architecture is the honest response.
Chain rule applied through the computation graph: gradients flow backward, weights update. One algorithm, unchanged since the 1980s, underneath everything from MNIST to GPT.
陷阱
Vanishing/exploding gradients shaped a decade of architecture design (residuals, normalization, careful init). When training diverges, the answer is usually plumbing, not theory.
Adam: mᵗ=β₁m+(1−β₁)g, vᵗ=β₂v+(1−β₂)g², θ←θ−η·m̂/(√v̂+ε). AdamW decouples weight decay from the gradient — the fix that mattered.
要点
SGD → momentum → Adam/AdamW as default. Warmup + cosine decay is the standard schedule. Learning rate is the single most important hyperparameter — everything else is second-order.
陷阱
Adam's defaults hide a weight-decay bug fixed by AdamW; copied training scripts propagate superstitions. Tune LR first, believe nothing else until it's swept.
Dropout, weight decay, data augmentation, early stopping — all ways to buy generalization by constraining fit. In deep learning, scale itself regularizes: big models generalize better than classical theory predicted (double descent).
陷阱
Financial data inverts the deep-learning instinct: tiny effective sample sizes mean classical overfitting discipline applies with full force — see overfitting in the Code tab.
similarity(a,b) = a·b/(‖a‖‖b‖). Contrastive training (InfoNCE): pull positives together, push negatives apart in the batch — CLIP's entire trick at web scale.
要点
Meaning as geometry: words, sentences, images mapped to vectors where distance ≈ similarity. The substrate of retrieval, recommendation, clustering, and RAG. king − man + woman ≈ queen was the demo; vector databases are the industry.
陷阱
Embeddings encode the training distribution's biases and blind spots; out-of-domain similarity is confidently wrong. Domain-specific fine-tuned embeddings routinely beat bigger general ones.
Test-time scaling: accuracy ∝ log(inference compute) on verifiable tasks. Process reward (per-step) beats outcome reward for credit assignment — Let's Verify's core result. STaR: bootstrap on self-generated correct rationales.
要点
Chain-of-thought made thinking visible; o1-style models made it trainable — RL on reasoning traces, spending inference compute to buy accuracy. The scaling axis moved from pretraining to test time.
陷阱
Longer thinking helps verifiable domains (math, code) most; open-ended judgment gains less. And visible reasoning is not faithful reasoning — the chain can be post-hoc theater over a different computation.
y = Σᵢ G(x)ᵢ·Eᵢ(x), G = softmax(top-k(x·Wₖ)) — route to k of N experts, k≪N. Active params per token ≈ k/N of total; the sparse trillion.
要点
Sparse activation: route each token to a few expert FFNs among many. Decouples parameter count from inference cost — how frontier models got huge without proportional serving bills.
陷阱
Routing is learned and imperfect; load balancing fights training instability. Parameter counts became marketing: a sparse trillion is not a dense trillion.
Vision, audio, text in one model: shared embedding spaces, cross-attention over image patches. The interface implication is larger than the benchmark one — screenshots, charts, and documents become native inputs.
陷阱
Vision-language models read charts worse than they claim: axis misreads and numeric hallucination persist. For financial charts, extraction-then-reason beats direct visual QA.
Learn the environment's dynamics, plan inside the learned simulation (Dreamer lineage, video-generation-as-physics). The bet: prediction of consequences is the substrate of general agency.
陷阱
Photorealistic video ≠ causal understanding — generated physics violates conservation laws pixel-beautifully. The gap between rendering and modeling is the field's open wound.
Pair neural generation with symbolic checking: code that must compile, proofs that must verify, claims that must ground to sources. The reliability path for high-stakes domains — generation proposes, verification disposes.
陷阱
The verifier is only as good as its coverage; unverifiable domains (strategy, taste, markets) get no such safety net. Where verification is impossible, epistemic honesty is the only remaining layer — the ZMACRO premise.
Cryptography, threat models, AI system security, and operations. Every entry: the definition (定义), the point (要点), where it breaks (陷阱), and the source (文献). Cross-linked into AI and Code.
The primitive under signatures, Merkle trees, commitments, and proof-of-work. Collision resistance is the strongest property and the first to fall — MD5 broke in 2004, SHA-1 in 2017 (SHAttered), both by collision, not preimage.
陷阱
Length-extension attacks on Merkle-Damgård constructions (SHA-256) let an attacker compute H(m‖pad‖m′) knowing only H(m) — this is why HMAC exists and why naive H(secret‖message) MACs are broken. Sponge constructions (SHA-3) are immune.
ECDSA over secp256k1 (Bitcoin, Ethereum); Ed25519 (EdDSA, deterministic); Schnorr (linear, aggregatable — BIP-340). Verify: given (r,s), m, pubkey P, check the curve equation holds.
要点
Authentication without shared secrets. Schnorr's linearity enables signature aggregation and MuSig — the reason Taproot exists. Ed25519 is deterministic: no per-signature randomness to leak.
陷阱
ECDSA nonce reuse leaks the private key algebraically — two signatures with the same k solve for d in one line. Sony's PS3 fell to exactly this in 2010. RFC 6979 deterministic nonces are the fix, and are still not universally adopted.
Argon2id (memory-hard, side-channel resistant), scrypt, bcrypt, PBKDF2. Cost parameters: time, memory, parallelism. Never a bare hash.
要点
Passwords must be slow to guess. Memory-hardness defeats GPU/ASIC parallelism — the entire point of Argon2id winning the Password Hashing Competition.
陷阱
PBKDF2 with a low iteration count is a rounding error to a GPU farm. And a KDF protects at rest; it does nothing against phishing, credential stuffing from other breaches, or a compromised process reading plaintext in memory.
Forward secrecy means yesterday's traffic stays private even if today's long-term key leaks. ECDHE gives it; static RSA never did — which is why TLS 1.3 deleted it.
陷阱
0-RTT data is replayable by design. Anything sent in 0-RTT must be idempotent — a fact routinely ignored, turning a latency optimization into a replay attack surface.
Compromise a dependency, not the target. SolarWinds (build system), event-stream (npm maintainer handover), xz-utils CVE-2024-3094 (multi-year social engineering into a compression library shipped in sshd).
要点
The highest-leverage attack in modern software: one upstream compromise reaches every downstream consumer. SBOMs, reproducible builds, and pinned hashes are the structural defences.
陷阱
Pinning versions is not pinning code — a tag can be moved. Pin by content hash. And xz proved that a patient adversary can spend two years becoming the trusted maintainer; no technical control detects earned trust being spent.
Timing, power, cache (Flush+Reload, Prime+Probe), speculative execution (Spectre, Meltdown). The secret leaks through the physics of the computation, not its output.
要点
Constant-time implementations are mandatory for anything touching key material: no secret-dependent branches, no secret-dependent memory indices. `crypto_verify` exists for this reason.
陷阱
A `==` comparison on an HMAC leaks the correct prefix length through timing. Every hand-rolled auth check that returns early on first mismatch is a side channel. Spectre showed the CPU itself is the attack surface.
Authentication: who are you. Authorization: what may you do. OAuth 2.0 is a delegation framework, not an authentication protocol — OIDC adds the identity layer on top.
要点
Most breaches are authorization failures, not cryptographic ones. IDOR (insecure direct object reference) is #1 on the OWASP API list: the token is valid, the object isn't yours.
陷阱
Using OAuth access tokens as identity proof is the classic confused-deputy error — a token proves delegation, not who the bearer is. Every 'Login with X' built on bare OAuth 2.0 has this bug.
No implicit trust from network location. Every request authenticated, authorized, and encrypted. BeyondCorp (Google), NIST SP 800-207. The perimeter is dead; identity is the perimeter.
要点
Replaces the castle-and-moat model that fails the moment one internal host is compromised. Microsegmentation limits lateral movement — the difference between an incident and a breach.
陷阱
Zero trust is an architecture, not a product, and it is sold as a product. Bolting an identity proxy in front of a flat internal network buys a login page, not segmentation.
Untrusted input reaches the model's instruction channel. Direct (user types it) or indirect (model reads a poisoned webpage, email, or document). There is no reliable separation of instruction and data in a single token stream.
要点
The defining unsolved problem of LLM agents. Mitigations: privilege separation (the model never holds the capability), dual-LLM patterns, output filtering, human confirmation on side-effectful actions.
陷阱
It is not patchable by better prompting. 'Ignore previous instructions' filters are trivially bypassed by encoding, translation, or indirection. Treat every model output derived from untrusted input as untrusted — the same discipline as SQL injection, before parameterized queries existed.
Inject crafted samples into the training corpus so the model learns an attacker-chosen behaviour on a trigger. Poisoning ~0.01% of a web-scale dataset is sufficient for targeted backdoors.
要点
Web-scraped pretraining data is attacker-writable by construction. Expired domains in curated datasets can be re-registered and repopulated — a documented, cheap attack.
陷阱
Backdoors survive fine-tuning and are near-undetectable by benchmark evaluation, because the trigger is off-distribution by design. You cannot test for a behaviour whose activation condition you don't know.
Query the API, reconstruct the weights or the training data. Membership inference: was this record in the training set? Extraction: distill a functional copy for a fraction of the training cost.
要点
The model is the asset; the API is a leak. Rate limiting, output perturbation, and watermarking are partial defences. Differential privacy bounds membership inference at a measurable utility cost.
陷阱
Distillation from a frontier API is model extraction with a business plan. And DP-SGD's ε values used in practice (ε≈8) provide far weaker guarantees than the formalism suggests to non-specialists.
An LLM with tools is an LLM with a shell. Threat surface = the union of every tool's capability. Confused deputy: the agent has permissions the user shouldn't be able to invoke via natural language.
要点
The right frame: the model is an untrusted planner, and the tool layer is the security boundary. Capabilities must be scoped per-task, not per-session. Irreversible actions require out-of-band confirmation.
陷阱
Reliability compounds against you: a 95%-per-step agent fails ~40% of 10-step tasks, and a security failure need only happen once. Demos hide this; production doesn't.
HSMs, KMS, envelope encryption, rotation, escrow. Split knowledge and dual control for root keys. Shamir's Secret Sharing: k-of-n reconstruction, information-theoretically secure below threshold.
要点
Cryptography reduces the problem of protecting data to the problem of protecting keys — and then most systems fail at the second half. The key's lifecycle is the actual security boundary.
陷阱
A key in an environment variable is a key in every crash dump, every `ps` output, every logging SaaS. And rotation without revocation is theatre: the old key still decrypts the old ciphertext.
Dwell time is the metric: median time from compromise to detection. Logs are evidence only if they are immutable, timestamped in UTC, and shipped off-host before the attacker reaches them.
要点
Assume breach. The question is not whether an adversary gets in but how long they operate unobserved. Canary tokens, honeypots, and behavioural baselines beat signature matching against a motivated attacker.
陷阱
Alert fatigue is an availability attack on your analysts. A detection rule that fires a thousand times a day trains the team to ignore the one time it matters.
STRIDE (spoofing, tampering, repudiation, information disclosure, DoS, elevation). Or the four questions: what are we building, what can go wrong, what will we do, did we do a good job.
要点
Security is a property of a system in a context, not a checklist. The exercise forces you to name the adversary — a nation-state, a script kiddie, and a disgruntled insider demand different architectures.
陷阱
'Our threat model is everyone' means you have no threat model. Without a named adversary with named capabilities and named goals, every control is equally justified and none is prioritised.
Consensus, on-chain derivatives, zero-knowledge, and protocol risk. Every entry: the definition (定义), the mechanism (机制), where it breaks (陷阱), and the source (文献). Cross-linked into ν and Macro.
Consensus & Settlement 共识与结算4
Proof of Work 工作量证明
定义
Find nonce such that H(block‖nonce) < target. Difficulty retargets to hold block time constant. Security budget = block reward × price; an attacker must out-spend it.
机制
Nakamoto consensus: the longest chain is the one with most accumulated work. Finality is probabilistic — 6 confirmations is a convention, not a theorem. Settlement assurance grows with depth and with the cost of reorganisation.
陷阱
51% is not a threshold, it is a price. Selfish mining is profitable below 50% (Eyal-Sirer). And 'energy waste' misframes it: the energy IS the security, denominated in dollars per reorg.
Validators bond capital; misbehaviour is slashed. Ethereum: Casper FFG finality gadget over LMD-GHOST fork choice. Two-thirds honest stake ⇒ economic finality in two epochs (~12.8 min).
机制
Security budget decouples from energy and attaches to the staked asset. Slashing makes equivocation cost capital rather than merely forgoing reward — this is what fixes nothing-at-stake.
陷阱
Long-range attacks require weak subjectivity: a new node must trust a recent checkpoint from outside the protocol. PoS finality is economic, not physical — an attacker who can acquire and burn ⅓ of stake can halt the chain.
Probabilistic (PoW: reorg cost grows with depth) vs economic (PoS: slashing makes reversion cost ⅓ of stake) vs absolute (BFT: finality in one block, at the price of liveness under partition).
机制
The number that matters for anyone settling value. Exchanges' confirmation policies are a direct pricing of reorg risk against withdrawal latency.
陷阱
CAP applies: you cannot have finality and liveness under partition. BFT chains halt; Nakamoto chains fork and heal. Which failure you prefer is a business decision disguised as a technical one.
Value extractable by reordering, inserting, or censoring transactions within a block. Sandwich attacks, arbitrage, liquidations. PBS (proposer-builder separation) separates who orders from who proposes.
机制
MEV is not a bug: it is the on-chain analogue of order-flow payment and front-running, made explicit and auctioned. Flashbots turned a latency race into a sealed-bid auction, reducing chain congestion.
陷阱
MEV centralises: builders with better order flow win, and the builder market concentrates. Censorship resistance degrades when a handful of builders construct most blocks — a documented, measurable trend.
Constant product: x·y=k. Price impact for trade Δx: Δy = y·Δx/(x+Δx). IL for price ratio r: 2√r/(1+r) − 1 — always ≤ 0 versus holding.
机制
A passive market maker with no order book. Uniswap v3's concentrated liquidity turns an LP position into a portfolio of range orders — mathematically, a short-gamma payoff around the range.
陷阱
'Impermanent' is marketing. It is permanent the moment you withdraw at a different price, and it is precisely the premium an LP sells: LPs are short volatility, paid in fees. Fee income must exceed realised variance × exposure, or the position loses.
No expiry. Funding rate f pegs perp to index: longs pay shorts when perp > index. f ≈ clamp(premium + interest, ±cap), settled every 8h (or continuously on-chain).
机制
The dominant crypto derivative by volume. Funding is a directly observable, tradeable carry — the market's price of leverage, and one of the cleanest sentiment gauges that exists.
陷阱
Funding is not arbitrage-free carry: it is a mechanism, not a no-arbitrage condition. It can persist far from theoretical carry for weeks. And cascading liquidations mean the peg holds until it violently doesn't.
Fully-collateralised (no margin call, capital inefficient) vs margined (oracle-dependent liquidation). Pricing via oracle-fed BSM or via AMM (Lyra, Panoptic's perpetual options).
机制
Composability: an option token is an ERC-20 that other protocols can accept as collateral. This is the genuine structural advantage over CeFi — not price, not fees.
陷阱
Every margined on-chain option is a bet on an oracle. Options liquidity is thin, and the vol surface it implies is a liquidity artefact more than a forecast. Compare with the CeFi surface before trusting it.
Off-chain data on-chain: Chainlink (aggregated node network), Pyth (first-party publishers, pull-based), TWAP (on-chain, manipulation-resistant but stale).
机制
The bridge between the deterministic machine and the world. Every collateralised protocol's solvency reduces to its oracle's correctness and latency.
陷阱
The oracle problem is unsolved and often the entire attack surface: Mango Markets ($114M, 2022) was an oracle manipulation, not a code bug. TWAP resists manipulation by being slow — and a slow oracle is a free option for the liquidator's counterparty.
Prove knowledge of w such that C(x,w)=1, revealing nothing about w. SNARKs: succinct, needs trusted setup (Groth16) or universal setup (PLONK). STARKs: transparent, post-quantum, larger proofs.
机制
Verification is exponentially cheaper than computation — the entire basis of ZK rollups. Also enables private state: prove solvency without revealing the balance sheet.
陷阱
'Zero knowledge' in rollups is a misnomer: they use succinctness, not privacy. And a trusted setup is a trusted setup — the toxic waste must actually be destroyed, and you cannot verify that it was.
Execute off-chain, post data on-chain. Optimistic: assume validity, 7-day fraud-proof window. ZK: prove validity, minutes to finality. Both inherit L1 data availability and settlement.
机制
The scaling answer that keeps security: the L1 is the court, the L2 is the venue. EIP-4844 blobs cut data cost by an order of magnitude and reshaped L2 economics overnight.
陷阱
Almost every rollup still has an upgrade multisig — a trusted third party wearing a trustless costume. Read L2Beat's stage classification before believing a security claim.
If data is withheld, no one can prove fraud. DA sampling: light clients sample random chunks; with erasure coding, sampling k chunks gives near-certainty the whole block is available.
机制
The unglamorous constraint that determines whether a rollup is a rollup or a database with a Merkle root. Celestia, EigenDA, and blobs are all answers to this one question.
陷阱
'Validium' means the DA is off-chain, which means the operator can freeze your funds by withholding data. It is a different trust model, marketed as a cheaper rollup.
Code is law, including the bugs. The DAO (2016, reentrancy) forced a hard fork and created ETC. Formal verification, invariant testing (Echidna, Foundry fuzzing), and staged rollouts with caps are the mature defences.
陷阱
An audit is a point-in-time opinion, not a guarantee, and most exploited protocols were audited. Economic exploits (not code bugs) dominate losses now — the code does exactly what it says, and what it says is exploitable.
Lock-and-mint, burn-and-mint, or liquidity network. Trust assumption ranges from an n-of-m multisig to a light client. Ronin ($624M), Wormhole ($326M), Nomad ($190M) — bridges are the single largest loss category.
机制
A bridge is a bank whose vault is a multisig. The security of a wrapped asset is the security of the weakest bridge that can mint it, not of the chain it sits on.
陷阱
Cross-chain composability multiplies attack surface: an asset bridged twice inherits both bridges' trust assumptions. Vitalik's argument against cross-chain applications is a security argument, not a tribal one.
Emission schedule, sinks, vote-escrow (ve) lockups, treasury runway. Governance attack cost = cost of acquiring quorum vs value extractable from the treasury.
机制
A token is a claim on a cash flow, a governance right, or a Schelling point — and the design must say which. ve-models trade liquidity for alignment; they concentrate power in whoever locks longest.
陷阱
If the cost to buy quorum is less than the treasury, the treasury is a bounty. Beanstalk lost $182M to a flash-loan governance attack executed in a single block — the vote was entirely legitimate.
Howey (US securities), MiCA (EU, in force 2024), FATF Travel Rule, and the sanctions perimeter (OFAC / Tornado Cash). Custody, transfer, and market-making each attract different regimes.
机制
The binding constraint on any on-chain business, and the one most protocol teams model last. Where a product touches fiat, a licensed counterparty is not optional.
陷阱
'Sufficiently decentralised' is a regulatory hope, not a legal test — no statute defines it. Building on the assumption that decentralisation grants immunity has ended in enforcement, repeatedly.
The master index of the entire knowledge base — 251 entries across nine domains, every node hyperlinked, every branch collapsible. Click any leaf to jump straight to it.
σᵣᵉᵍ = √((252/n)·Σrᵢ²) for close-to-close. Better: Parkinson (H/L range), Garman-Klass (OHLC), Yang-Zhang (handles gaps + drift). Realized variance = Σrᵢ² converges to quadratic variation <X>ᵗ as Δt→0.
用途
The only volatility that is a measurement rather than an inference. Range estimators are 5–8x more efficient than close-to-close: same accuracy from one day that C2C needs a week to reach.
陷阱
High-frequency realized variance is contaminated by microstructure noise — bid-ask bounce inflates it. Sampling at 5-minute bars is the folk-remedy; realized kernels and two-scale estimators are the honest fix. And RV is backward-looking by construction: it tells you what happened, priced as if it will.
The same estimator as RV, applied over a trailing window (20d, 60d, 252d). EWMA weights it: σ²ᵗ = λσ²ᵗ₋₁ + (1−λ)r²ᵗ₋₁, λ=0.94 daily (RiskMetrics).
用途
The naive forecast. Its only virtue: it is the benchmark everything else must beat, and it frequently is not beaten.
陷阱
Window choice IS the model: a 20-day HV is a different instrument from a 252-day HV. Quoting 'historical vol' without the window is quoting nothing. Rolling windows also create phantom regime shifts as large moves drop out of the sample — the volatility falls because the past changed, not the present.
The single most robust harvest in derivatives: option sellers are paid for bearing crash risk. Variance swaps monetize it directly; short strangles and covered calls monetize it with path dependence bolted on.
陷阱
The premium is compensation, not free money — the 15% of months pay for the 85%. Selling variance is a short position in the fourth moment; the Sharpe looks superb until the return distribution's left tail arrives and collects. See fat tails, and Kelly for why full-size is suicide.
σᶠᵤᵈ²(T₁,T₂) = [σ²(T₂)T₂ − σ²(T₁)T₁] / (T₂ − T₁) — bootstrapped from the total-variance term structure.
用途
What the surface implies about volatility between two future dates. Calendar spreads and forward-start options trade it. Negative forward variance = calendar arbitrage present in your surface.
陷阱
Local vol models reproduce today's surface exactly and get forward vol structurally wrong — they mean-revert the smile to flat. Pricing a cliquet with local vol is choosing to be exactly right about today and wrong about tomorrow.
In Heston, ξ is the diffusion coefficient of the variance process; VVIX is its market analogue on VIX options. Volga is the position-level exposure to it.
用途
Governs smile curvature (the wings) independently of skew (the tilt). High ξ = fat implied distribution = expensive wings. Vol-of-vol spikes precede vol spikes more often than the reverse.
陷阱
ξ and κ are jointly ill-identified in Heston calibration — the surface constrains their ratio far better than either level. Fitting them separately produces parameter series that jump without the surface moving.
σᵢᵐᵧ(K,T): a two-dimensional field over strike and maturity. Quoted in delta-space in FX (25ΔRR, 25ΔBF, ATM), in strike-space in equities, in moneyness k = ln(K/F) for modelling. Total variance w(k,τ) = σ²τ is the arbitrage-natural coordinate.
用途
Not a surface of volatilities — a surface of prices wearing volatility's clothing. Every model is judged by whether it can generate this shape *and* the way it moves. Fitting the shape is undergraduate; fitting the dynamics is the job.
陷阱
Interpolating in σ instead of w violates calendar constraints. Interpolating in K instead of k breaks under spot moves. The coordinate choice is a modelling decision that most implementations make by accident.
σ(K) convex in K, minimum near ATM, both wings elevated. Canonical in FX majors, where up and down are symmetric by construction (EURUSD down = USDEUR up).
用途
Prices excess kurtosis: the market pays up for both tails relative to lognormal. Volga is long here; butterflies express it.
陷阱
A pure smile with no tilt implies zero spot-vol correlation. That is an FX phenomenon, not a general one — importing FX smile intuition into equity index vol is the classic cross-asset error.
∂σ/∂k < 0: downside strikes carry higher IV. Measured as 25Δ risk-reversal (σ₂₅∆ᶜₐₜₜ − σ₂₅∆ᶜᵘᵗ) or as the ATM slope. Equity indices, permanently, since October 1987.
用途
The price of the leverage effect and crash risk. In Heston it is generated by ρ < 0; in jump models by negative jump mean. Vanna is the position-level exposure. Skew steepens in stress before spot moves — it is a leading indicator disguised as a price.
陷阱
Index skew is far steeper than single-name skew: the difference is implied correlation, not a mispricing. Dispersion trades live in that gap and die when correlation goes to one.
The asymmetric limit: one wing elevated, the other flat or inverted. Equity index puts bid, calls offered — a monotone decreasing σ(K) rather than a convex curve. Commodities often show the mirror (calls bid: supply-shock risk is to the upside).
图
用途
The honest name for what equity vol actually looks like. 'Smile' is a textbook artifact; 'smirk' is the SPX surface. The direction of the smirk tells you which tail the market fears — and that flips by asset class.
陷阱
Modelling a smirk with a symmetric-smile model (pure stochastic vol, ρ=0) requires an unreasonable vol-of-vol to fit the wings, which then destroys the term structure. Skew wants ρ; wings want ξ. Confusing them is the standard calibration failure.
σ(τ) at fixed moneyness. Contango (upward) in calm regimes: short-dated vol cheap, long-dated anchored to long-run mean. Backwardation (inverted) in stress: near-term panic exceeds long-run expectation.
图
用途
The VIX futures curve is this object, tradeable. Roll yield in contango is the structural short-vol harvest that ate XIV in February 2018 — the curve inverted and the ETN's rebalance mechanism did the rest.
陷阱
Term structure of skew is a separate object from term structure of ATM vol, and it decays much faster. Short-dated skew is steep in a way no diffusion model can generate without jumps or roughness — see rough volatility.
Sticky strike: σ(K) fixed as S moves. Sticky delta (sticky moneyness): σ(k) fixed, so the smile translates with spot. Sticky local vol: implied by Dupire, skew moves twice the spot.
用途
The regime determines your true delta. Under sticky delta, the BSM delta is wrong by vanna·(∂σ/∂S); traders apply a skew-adjusted delta. Which rule holds is an empirical question that changes with the regime.
陷阱
Assuming the wrong stickiness rule produces a delta hedge that is systematically biased in one direction. It is invisible in a flat tape and lethal in a trend. Most retail options analytics quote sticky-strike deltas without saying so.
Δ = ∂V/∂S = Φ(d₁) for a call, Φ(d₁)−1 for a put. Under BSM, d₁ = [ln(S/K) + (r + σ²/2)τ] / (σ√τ).
用途
Hedge ratio and the market's risk-neutral probability of finishing ITM (approximately — Φ(d₂) is the exact one). Delta-neutral books are the desk's baseline state.
陷阱
Delta is not a probability; conflating Φ(d₁) with Φ(d₂) is a first-week error that survives into P&L. And delta is unstable exactly where it matters — near the strike, near expiry, gamma eats you.
ν = ∂V/∂σ = Sφ(d₁)√τ = Ke⁻ʳᵗφ(d₂)√τ · identical for calls and puts (put-call parity has no σ term).
用途
Sensitivity to implied volatility. Peaks ATM, scales with √τ — long-dated options are volatility instruments first, directional instruments second.
陷阱
Vega is quoted per volatility point but the surface does not move in parallel. Summing vega across strikes and tenors as one number is the classic vega-bucketing sin — hedge the surface, not the scalar. ν is also not a true Greek: σ is a model parameter, not a state variable.
Θ = −Sφ(d₁)σ/(2√τ) − rKe⁻ʳᵗΦ(d₂) for a call. The decay term and the discount term.
用途
Time decay: what a long option pays for gamma. The BSM PDE says it exactly: Θ + ½σ²S²Γ + rSΔ = rV — theta is the rent on gamma.
陷阱
Theta is not smooth: weekend decay, holiday calendars, and the pin-risk cliff at expiry. Backtests that decay linearly by calendar day mis-time the entire final week.
Rate sensitivity. Ignorable in a 0% world, decisive for long-dated options, LEAPS, and anything with meaningful carry. Returned from irrelevance in 2022.
陷阱
Rho hides the funding assumption. For FX options there are two rates and the 'rho' you compute depends on which currency you call domestic — Garman-Kohlhagen, not BSM.
Γ = ∂²V/∂S² = φ(d₁)/(Sσ√τ) · identical for calls and puts. Peaks ATM and explodes as τ→0.
图
用途
Convexity of the position. The gamma-theta trade IS options trading: long gamma pays when realized variance exceeds implied, financed by theta. Discrete hedging P&L ≈ ½ΓS²(σᵣᵉᵍ₂ − σᵢᵐᵧ₂)δt summed over rebalances.
陷阱
Short gamma near expiry is a short position in the second derivative of your own solvency. The pin at expiry, the gap through the strike overnight — gamma risk is convexity risk and it is not linear in size.
Vanna = ∂Δ/∂σ = ∂ν/∂S = −φ(d₁)d₂/σ · the cross-derivative that ties spot and vol together.
用途
How delta moves when volatility moves, and how vega moves when spot moves. The engine of skew: if vol rises as spot falls, your delta hedge is systematically wrong in one direction. Risk-reversal exposure lives here.
陷阱
Vanna-hedging with vanillas is expensive and imperfect. Most skew P&L that traders attribute to 'the market' is un-hedged vanna leaking through their delta program.
Volga = ∂ν/∂σ = ν·d₁d₂/σ. Zero ATM; positive in both wings — the smile's curvature exposure.
用途
Convexity in volatility. Long volga = long vol-of-vol: butterflies and strangles profit when the smile steepens. Vanna-Volga pricing turns these two Greeks into a market-consistent smile correction for exotics.
陷阱
Volga is why a vega-neutral book still bleeds through a vol spike. Vega-flat and volga-short is the standard structure of an option seller weeks before the loss event.
The overnight and intraweek drift of your hedges. Charm is why a book delta-hedged at Friday's close opens Monday off-hedge with no move in spot. Speed matters for large barrier and digital books.
陷阱
These are ignored until expiry week, when they dominate. Options market makers do not hedge the Greeks they can name — they hedge the ones that dominate their current P&L attribution.
σᵢᵐᵧ solves BSM(σ) = market price. Newton-Raphson converges in ~3 iterations from a Brenner-Subrahmanyam seed: σ₀ ≈ (√(2π/τ))·C/S.
用途
Not a forecast — a price quoted in the wrong units. The market's fear, supply-demand imbalance, and model error, all compressed into one number that everyone pretends is a volatility.
陷阱
IV is model-dependent by definition: it is the number that makes a known-false model reproduce the observed price. Comparing IV across models or across underlyings with different dynamics is comparing dialects, not quantities.
The market's rejection of lognormality: crash risk and leverage effect priced into strikes. Skew is the price of the correlation between returns and volatility (ρ in Heston), and the market's memory of black swans.
陷阱
A skew that is flat is not an arbitrage — it is a market with no crash memory or no put demand. Fitting a smile with a model that cannot generate it (BSM) and then trading the residual is fitting your own error.
Butterfly: ∂²C/∂K² ≥ 0 (implied density non-negative). Calendar: total variance w = σ²τ non-decreasing in τ. Vertical: −1 ≤ ∂C/∂K ≤ 0.
用途
The three constraints any admissible surface must satisfy. Breidenband: violation of the butterfly condition means the fitted implied density goes negative — the surface is not just wrong, it is impossible.
陷阱
Naive interpolation across strikes and tenors (splines, RBF) violates these routinely. SVI parameterization was built specifically to be arbitrage-free by construction — use a parameterization, not a fit.
Raw SVI: w(k) = a + b[ρ(k−m) + √((k−m)² + σ²)], where w = total variance, k = log-moneyness. Five parameters per slice.
用途
The industry standard for arbitrage-free surface fitting. Gatheral's SSVI extends it across tenors with a single θ(τ) term structure — calendar-arbitrage-free by construction.
陷阱
SVI parameters are not economically interpretable and can jump between refits with nearly identical surfaces. Fit stability, not fit quality, is what breaks production surface engines.
Fair variance = (2eʳᵗ/τ)[∫₀ᶜ P(K)/K² dK + ∫ᶜᶠ C(K)/K² dK]. Model-free: a strip of options weighted 1/K² replicates variance exactly.
用途
The one clean result in this whole field: variance is tradeable without a model. VIX is this integral on SPX, discretized. Volatility swaps, by contrast, require a model (convexity adjustment).
陷阱
The replication assumes a continuum of strikes and no jumps. Jumps break it — realized variance swap P&L in a crash is not the integral you replicated. VIX is a variance, not a volatility, and its square root is quoted.
dS = μS dt + √v S dW₁ · dv = κ(θ−v)dt + ξ√v dW₂ · <dW₁,dW₂> = ρdt. Feller: 2κθ > ξ² keeps v > 0.
用途
Semi-closed-form via characteristic function and Fourier inversion (Carr-Madan FFT). ρ generates skew, ξ generates smile curvature, κ controls term-structure decay of both.
陷阱
Calibration is ill-posed: many (κ,θ,ξ,ρ,v₀) fit today's surface nearly equally well and imply wildly different forward smiles. Feller is violated in most real calibrations, and the model is used anyway.
dF = σFβ dW₁, dσ = νσ dW₂, <dW₁,dW₂> = ρdt. Hagan's asymptotic implied-vol formula is what the market actually quotes.
用途
β sets backbone dynamics (β=1 lognormal, β=0 normal), ν is vol-of-vol, ρ the skew. Swaption cubes are quoted in SABR parameters, not prices.
陷阱
Hagan's expansion produces arbitrageable densities at low strikes — it goes negative. Shifted SABR and ZABR patch it. The formula everyone quotes is an approximation whose error is largest exactly where post-2015 rates live.
Volatility as fractional Brownian motion with Hurst H ≈ 0.1: log-vol increments have scaling ‖logσᵗ₊∆ − logσᵗ‖ ∝ Δᴪ. Empirically robust across every asset tested.
用途
Explains the steep short-dated skew that classical SV models structurally cannot generate (they decay as √τ, the market decays as τᴪ⁻ᶜ₀⋅₅). Rough Bergomi is the practical implementation.
陷阱
Non-Markovian: no PDE, no fast calibration, simulation is expensive. And the microstructural origin of H≈0.1 remains contested — the empirical regularity is far more secure than its explanation.
Dupire local vol: σᴱᵒᶜ²(K,T) = [∂C/∂T + rK∂C/∂K] / [½K²∂²C/∂K²] — the unique diffusion reproducing today's surface exactly.
用途
LV fits vanillas perfectly and gets forward smile wrong. SV gets dynamics right and vanillas approximately. LSV (local-stochastic) multiplies a leverage function onto SV to recover exact vanilla fit — the production standard for exotics.
陷阱
Choosing LV to price a forward-start or cliquet is choosing to be exactly right about today and structurally wrong about tomorrow. The model that fits best is not the model that hedges best.
Knock-out value = vanilla − reflected vanilla (image method under BSM with constant σ). Delta and gamma go discontinuous at the barrier; near-barrier gamma can exceed the vanilla's by orders of magnitude.
用途
The hedge is impossible in the limit: as spot approaches the barrier near expiry, required rebalancing frequency diverges. Traders hedge with a barrier shift and price the gap risk explicitly.
陷阱
Barrier P&L is dominated by the vol surface's local behavior at the barrier, not the ATM level. Pricing barriers with a flat vol is not conservative — it is arbitrary.
Digital call = −∂C/∂K = e⁻ʳᵗΦ(d₂). Replicated by a tight call spread; as the spread narrows, delta diverges.
用途
The clean statement that Φ(d₂) is the risk-neutral ITM probability. Pin risk at expiry: the digital's delta is a delta function at the strike — unhedgeable at the instant it matters.
陷阱
The market prices digitals with a skew adjustment (the call-spread's two strikes see different vols); using flat-vol Φ(d₂) systematically misprices every digital in a skewed market.
Bump-and-revalue: Δ ≈ [V(S+h) − V(S−h)]/2h. Pathwise: ∂V/∂θ = E[∂payoff/∂θ]. Likelihood ratio: differentiate the density, not the payoff. Adjoint AD: all Greeks in ~4x the cost of one price.
用途
For Monte Carlo, bumping produces noise that swamps the signal for second-order Greeks. Pathwise fails on discontinuous payoffs (digitals); LRM handles them but has higher variance. AAD is the production answer.
陷阱
Choosing h in a bump: too large and you measure curvature, too small and you measure floating-point noise. The optimal h scales as εᴪ for a k-th derivative — and nobody computes it, they guess.
Fixed leg PV = Σᵢ N·K·τᵢ·D(tᵢ) · Float leg PV = N·[D(T₀) − D(Tₙ)] (single-curve). Par swap rate: S = [D(T₀) − D(Tₙ)] / A(t), where the annuity A(t) = ΣᵢτᵢD(tᵢ).
用途
The plumbing of fixed income: exchange fixed for floating on a notional never exchanged. $500tn+ notional outstanding globally. The annuity A(t) is the swap's natural numeraire and the reason the swap rate is a martingale under the annuity measure — which is what makes swaptions tractable at all.
陷阱
Post-2008, single-curve is dead: discount with OIS, project with the term rate. The 'swap rate' now depends on which curve you project and which you discount — and the basis between them is a traded instrument. Pre-crisis textbooks silently assume they are the same curve.
Black-76 under the annuity measure: V = A(t)·[S·Φ(d₁) − K·Φ(d₂)], d₁ₖ = [ln(S/K) ± ½σ²τ]/(σ√τ). Payer = call on the swap rate; receiver = put.
图
用途
The option to enter a swap. Changing numeraire to the annuity A(t) makes the forward swap rate a martingale and collapses the problem to Black. Quoted as a *cube*: expiry × tenor × strike. Bermudan swaptions (callable at multiple dates) are the model-risk epicenter of any rates desk.
陷阱
The swap rate is a *basket* of forward LIBORs, so lognormal LIBOR and lognormal swap rates are mutually inconsistent — both market models cannot both be exactly right. Bermudan swaption prices vary by percentage points across models that all calibrate to the same European swaptions.
A cap = Σ caplets, each a call on a forward rate: Caplet = NτD(Tᵢ₊₁)·[FΦ(d₁) − KΦ(d₂)] under the Tᵢ₊₁-forward measure. Each caplet has its own numeraire.
用途
Protection against rising rates, decomposed into a strip of independent options. Cap *vol* quotes are flat vols (one σ repricing the whole strip); caplet vols are the stripped term structure. The bootstrapping from one to the other is a daily production job.
陷阱
Flat cap vol is not a volatility — it is a price quoted in volatility units, and it is not comparable across strikes or maturities. Stripping caplet vols from cap quotes is ill-posed and every desk does it slightly differently.
df(t,T) = α(t,T)dt + σ(t,T)dW. No-arbitrage forces the drift: α(t,T) = σ(t,T)∫ᵗᶠσ(t,u)du. The entire forward curve is the state variable.
用途
The unifying framework: specify forward-rate volatility, and the drift is *determined*, not chosen. Every short-rate model (Vasicek, Hull-White, CIR) is an HJM model with a particular σ(t,T). The drift condition is the term-structure analogue of risk-neutral pricing.
陷阱
Generic HJM is non-Markovian — the state is an infinite-dimensional curve, so no PDE and no recombining tree. Only special σ forms (separable, exponential) collapse to finite-dimensional Markov states. Everything tractable is a special case.
dFᵢ/Fᵢ = μᵢ(t)dt + σᵢ(t)dWᵢ · each forward rate lognormal under *its own* forward measure. Under a common measure the drift μᵢ is a state-dependent sum — the famous LMM drift term.
用途
The model that made market practice and theory agree: caplets price by Black *exactly*, by construction. Swaptions require an approximation (Rebonato / Hull-White). The industry standard for exotics on the curve.
陷阱
High-dimensional (one factor per forward rate), no closed-form swaptions, and simulation-only. The drift term makes naive Euler discretization arbitrageable — Glasserman-Zhao showed you must discretize in the martingale variables, not the rates.
Post-2008: discount factor Dᵀᵢᵔ(t) from the OIS curve; forward rates F(t;Tᵢ,Tᵢ₊₁) projected from a tenor-specific curve. The 3M-6M basis, the OIS-LIBOR spread, and the cross-currency basis are all traded, not zero.
用途
The single largest structural change to derivatives pricing in fifty years. Collateralized trades discount at the collateral rate (CSA rate). A trade's value now depends on the *collateral agreement*, not just the payoff — identical trades under different CSAs have different values.
陷阱
The transition from LIBOR to SOFR/€STR broke the tenor-basis logic: risk-free overnight rates have no term credit component to bootstrap. Legacy models that hard-code a LIBOR-like tenor structure quietly misprice the fallback spread.
A CMS pays the swap rate S(T) at T, not over the swap's life. Under the T-forward measure S is not a martingale (its natural numeraire is the annuity). Adjustment ≈ S₀·σ²T·[−A′(S₀)/A(S₀)]·S₀ — a second-order correction from the numeraire mismatch.
用途
CMS spread options, range accruals, and every structured note referencing a long-tenor rate at a single date. The adjustment is pure change of measure: the same rate has a different expectation under the annuity and forward measures, and the gap is convexity.
陷阱
The standard replication argument prices the adjustment from a strip of swaptions across all strikes — and the wings, where liquidity is worst, dominate the integral. The convexity adjustment is a bet on the tails of the swaption smile, sold as a small correction.
Bachelier (normal) model: dF = σₙdW. Call = (F−K)Φ(d) + σₙ√τ·φ(d), d = (F−K)/(σₙ√τ). No lognormal constraint — F may go negative. Shifted lognormal: dF = σ(F+s)dW, displacement s > 0.
用途
Since 2015, EUR and JPY rates traded below zero and Black-Scholes-style lognormal quoting simply stopped working — ln(F/K) is undefined for F < 0. The market migrated to normal vols for rates. Bachelier's 1900 thesis, rejected as unrealistic for a century, became the market convention.
陷阱
Normal and lognormal vols are not interchangeable: σₙ ≈ σₗₙ·F only near ATM, and the conversion breaks in the wings. Legacy risk systems that store one vol number per instrument, with the convention implicit in the code, mispriced entire books during the 2015-16 transition. SABR needed a shift or a free boundary for the same reason.
Par spread solves: s·ΣᵢΔᵢD(tᵢ)Q(tᵢ) = (1−R)∫D(u)(−dQ(u)). Premium leg = protection leg. Credit triangle approximation: s ≈ λ·(1−R).
图
用途
Insurance on default, and the market's cleanest read on credit risk. The credit triangle says a 500bp spread with 40% recovery implies a hazard rate λ ≈ 8.3%/yr. Post-2009 Big Bang: fixed coupons (100/500bp) plus upfront, standardized so contracts are fungible.
陷阱
Spread and recovery are jointly unidentifiable from a single CDS quote — you can only extract λ·(1−R). Every hazard rate you have ever seen was produced by *assuming* R = 40%. And the accrued-on-default term is usually dropped from textbook formulas, which biases λ low.
Q(t) = exp(−∫₀ᵗλ(u)du) · λ(t)dt = P(default in [t,t+dt] | survived to t). Bootstrapped from the CDS term structure exactly like a yield curve from swaps.
用途
The reduced-form primitive: default is the first jump of a Cox process with intensity λ. Duffie-Singleton's recovery-of-market-value trick makes defaultable bonds price like default-free bonds discounted at r + λ(1−R) — a spread, not a new equation.
陷阱
λ is risk-neutral, not real-world. The gap between Q-hazard (from CDS) and P-hazard (from Moody's default studies) is the credit risk premium, and it is enormous: implied 5yr IG default probabilities run 3-8x historical. Using CDS spreads as default forecasts is a category error.
Equity = call on firm assets: E = V·Φ(d₁) − De⁻ʳᵗ·Φ(d₂). Default at T iff Vᵗ < D. Distance-to-default DD = [ln(V/D) + (μ−½σᶦ²)T]/(σᶦ√T); PD = Φ(−DD).
用途
Default as an *economic* event, not an exogenous jump: the firm defaults because assets fall below liabilities. The engine of Moody's KMV / EDF. Credit spread and equity vol become mechanically linked — this is why capital-structure arbitrage exists.
陷阱
Structural models produce near-zero short-dated spreads (a diffusion cannot cross the barrier instantly) while the market prices 50-100bp at 1yr. First-passage (Black-Cox) and jumps patch it. The 'credit spread puzzle' is largely this modelling artifact meeting a genuine liquidity premium.
Tranche loss = [L(t) − Kᴱ]⁺ − [L(t) − Kᵘ]⁺ — a call spread on the portfolio loss. Equity (0-3%), mezz (3-7%), senior. Gaussian copula: default times τᵢ = Qᵢ⁻¹(Φ(Xᵢ)), Xᵢ = √ρ·M + √(1−ρ)·εᵢ.
图
用途
Correlation, tranched and sold. The senior tranche is short a deep-OTM option on systemic default; the equity tranche is long correlation. Base correlation is the market's quoting convention — the implied vol of the credit world, and just as model-dependent.
陷阱
Li's Gaussian copula has *zero tail dependence*: as correlation → 1 it still under-prices simultaneous default. Senior tranches were rated on this. The model did not fail in 2008 — it worked exactly as specified, on a specification that assumed away the event.
Compound correlation: the single ρ repricing each tranche — non-monotone, sometimes has no solution for mezz. Base correlation: the ρ repricing each *equity* tranche [0,K], strictly increasing in K by construction.
用途
The credit market's admission that one correlation cannot price all tranches. Base correlation exists so the mezz tranche has a unique solution. It is a *quoting device*, not a parameter — interpolating it across bespoke portfolios is unsound and was done universally.
陷阱
A base-correlation curve that is not concave admits arbitrage (negative implied tranche loss density). The 2005 correlation crisis (GM/Ford downgrade) inverted the equity-mezz relationship and blew up every desk that had hedged mezz with equity on a flat-correlation assumption.
CDX.NA.IG / iTraxx Europe: equally-weighted portfolios of 125 single names. Index-to-intrinsic skew = index spread − theoretical spread from constituent CDS — persistently non-zero.
用途
The liquid instrument in credit. Index options (payer/receiver swaptions on the index) with the front-end protection adjustment. The skew is a liquidity and technicals measure, and it is *tradeable* as an index arbitrage.
陷阱
Index arbitrage is only theoretically riskless: replicating 125 single-name CDS incurs bid-ask that usually exceeds the skew, and the index has a defined credit-event settlement that single names do not exactly match. The 'arb' is a bet on convergence, funded through carry.
Payoff on the average: A = (1/n)ΣSᵗᵢ. Arithmetic average is not lognormal — no closed form. Geometric average IS lognormal: exact Black-Scholes-type formula, used as a control variate.
用途
Averaging kills terminal manipulation and lowers vol by roughly 1/√3 — cheaper than a vanilla, which is why corporates hedge FX flows with them. Turnbull-Wakeman and Curran give moment-matched approximations good to a few bps.
陷阱
Vega is much smaller than vanilla and the Greeks change character as fixings accumulate: after the last fixing the option is a delta-1 forward. A hedging program calibrated on day one is wrong by expiry, systematically.
Lookback pays Sᵗ − min₀ₕᵗₕᶧ Sᵘ (floating strike). Cliquet = sum of forward-starting options with periodic caps/floors: Σ max(min(rᵢ, cap), floor), rᵢ = Sᵗᵢ/Sᵗᵢ₋₁ − 1.
用途
Lookbacks are the price of perfect hindsight, closed-form under BSM. Cliquets are the retail structured-note workhorse and are *pure forward-skew* products: their value depends almost entirely on the forward smile, which vanillas barely constrain.
陷阱
Pricing a cliquet with local vol is a category error: LV fits today's smile and predicts a forward smile that flattens, systematically underpricing the product. This mispricing cost desks real money in 2008. The instrument exists to arbitrage the modeller's choice.
Knock-out on observation dates if S > barrier, paying coupon; else continue; at maturity a down-and-in put activates below the protection barrier. Short a barrier put, long a digital coupon strip.
用途
The dominant retail structured product in Asia and Europe by volume. Investors are *paid* to sell crash protection and be called away. Desk risk: massive short-vega concentrated at the barrier, plus a short-correlation position in worst-of baskets.
陷阱
The dealer is left long the tail and short the body of vol. As spot approaches the autocall barrier near an observation date, the dealer's delta and vega flip sign discontinuously — the hedging flows are large enough to be self-fulfilling. Structured-product hedging is a documented driver of index vol dynamics.
Payoff on minᵢ(Sᵢᵗ/Sᵢ₀). Value is decreasing in correlation: at ρ=1 the worst-of is a vanilla on the single index; at ρ=0 the minimum is dragged down by independent draws.
用途
Short correlation, packaged. Worst-of autocalls harvest the correlation risk premium (implied > realized dispersion, usually). The Greeks include *cross-gammas* ∂²V/∂Sᵢ∂S₃ that no single-asset intuition prepares you for.
陷阱
Correlation is not observable and not tradeable directly. Implied correlation is backed out of index vs single-name vol — and it goes to one exactly when the worst-of investor needs it not to. This is the same failure mode as the CDO, wearing an equity costume.
Vol swap pays (σᵣᵉᵍ − Kᶦ)×N. But E[√V] ≠ √E[V] — by Jensen, Kᶦ < √Kᶦᶜᴸ. The convexity adjustment ≈ −Var(V)/(8·E[V]ᶜᶜᶜ) requires a model for vol-of-vol.
用途
The instrument clients want (linear in volatility) versus the one that replicates (variance). The entire spread between them is Jensen's inequality made tradeable, and it is why vol swaps are a *model-dependent* product while variance swaps are not.
陷阱
Selling a vol swap and hedging with a variance swap leaves you short vol-of-vol — a position that looks flat and is not. The 'convexity adjustment' is a euphemism for the model risk you just took on.
Quanto forward = F·exp(−ρₖᶜσₖσᶜτ). Payoff in domestic currency at a *fixed* FX rate; the drift adjustment is the price of that guarantee.
用途
Foreign asset, domestic payoff, no FX exposure for the client — and a cross-asset correlation exposure for the dealer. Nikkei-quanto structures are the classic. The adjustment is pure ρₖᶜ, an unobservable, unhedgeable-with-vanillas parameter.
陷阱
Everything hinges on a correlation you can only estimate historically. Quanto desks are systematically short the equity-FX correlation and discover its instability in exactly the crises where the structures were sold as safe.
CVA = (1−R)∫₀ᶠ EE(t)·dPD(t)·D(t) · where EE(t) = Eᵪ[max(Vᵗ,0)] is expected positive exposure. CVA is a *call option on the exposure*, struck at zero, written on your counterparty's default.
用途
The price of your counterparty defaulting when the trade is in your favour. Basel III made it a capital charge. Every derivative price is now Vₘₕₖ − CVA + DVA − FVA − KVA − MVA — the XVA stack.
陷阱
CVA requires simulating the *whole netting set* forward and pricing every trade at every node — a nested Monte Carlo. The industry answer is AAD plus regression (Longstaff-Schwartz), and it remains the single largest compute line in a bank.
Exposure and counterparty default probability positively correlated: dependence between Vᵗ and τ. Selling CDS protection on a sovereign to a bank in that sovereign is the textbook case.
用途
CVA computed under independence understates the charge, sometimes by multiples. Modelled by correlating the default intensity with the exposure driver (Hull-White stochastic intensity) or via a copula on (τ, V).
陷阱
The correlation is unobservable and the effect is largest exactly in the tail where you have no data. Regulators impose an α multiplier (1.4) as an admission that nobody can model this properly.
DVA = gain from *your own* default. FVA = cost of funding the uncollateralized hedge. Hull-White (2012) argued FVA is not a valuation adjustment but a wealth transfer to shareholders — and got publicly attacked by every trading desk in the world.
用途
The most honest controversy in derivatives: booking a profit when your own credit deteriorates (DVA) is accounting-legal and economically absurd. Banks reported billion-dollar DVA swings through 2011-12 and then largely stopped.
陷阱
There is still no consensus on whether FVA belongs in the price or in the funding desk's P&L. The valuation of a derivative now depends on *who holds it* — which is a direct violation of the law of one price that the entire theory assumed.
A collateralized trade discounts at the CSA rate (the collateral's remuneration rate). Cheapest-to-deliver optionality: a multi-currency CSA gives the poster an option on which currency to post.
用途
Collateral converts credit risk into liquidity risk. The CSA is a derivative embedded in the CSA. Post-2008 clearing mandates moved most vanilla flow to CCPs where the CSA is standardized — and concentrated the tail risk into the clearing house.
陷阱
'Risk-free' discounting depends on the collateral agreement, which is negotiated per-counterparty. Two identical swaps with different CSAs are different instruments. Pre-crisis systems that store one price per trade cannot represent this and were rebuilt from scratch.
SIMM / historical VaR-based IM posted bilaterally under UMR. MVA = cost of funding IM over the trade's life = ∫ IM(t)·spread·D(t)dt.
用途
IM is not returned as collateral you can rehypothecate — it is a funding cost for the life of the trade, and it made many long-dated uncleared trades uneconomic. The regulation reshaped which products exist.
陷阱
MVA requires forward-simulating a risk measure (IM) inside a Monte Carlo, i.e. a VaR inside a simulation inside a pricing engine. This is where computational finance meets its practical ceiling — and why AAD stopped being an optimization and became a requirement.
Backward induction on simulated paths: regress discounted continuation value on basis functions of the state, exercise when immediate payoff > fitted continuation. E[Vᵗ₊₁|ℱᵗ] ≈ Σβₖψₖ(Sᵗ).
图
用途
The algorithm that made American and Bermudan options priceable by Monte Carlo, and therefore made high-dimensional callables (Bermudan swaptions, CVA) tractable at all. The single most important numerical result in derivatives since finite differences.
陷阱
The regression uses the *same paths* for the exercise rule and the valuation — this biases the price *high*. Honest implementations use separate paths for policy and pricing, giving a low-biased estimate; the true price is bracketed, not computed.
Crank-Nicolson on the pricing PDE; ADI for 2D (stochastic vol, two-asset). Stability: implicit unconditionally stable, explicit needs Δt < Δx²/(2σ²S²).
用途
Superior to Monte Carlo for low dimensions with early exercise or barriers: exact Greeks from the grid, no simulation noise, barriers handled by grid alignment. Anything ≤ 3 factors should be a PDE.
陷阱
Crank-Nicolson oscillates on discontinuous payoffs (digitals) — Rannacher time-stepping (two fully-implicit half-steps) is the standard fix that is omitted in half of all implementations. Barrier misalignment with the grid prices a *different barrier* than the contract.
Sobol sequences: discrepancy O((log N)ᵈ/N) vs O(1/√N) for pseudo-random. Brownian bridge construction concentrates variance in the first few dimensions where QMC is most effective.
用途
The difference between an overnight batch and an intraday risk run. Antithetic variates, control variates (geometric Asian for arithmetic), importance sampling for deep-OTM. Standard practice, unevenly implemented.
陷阱
QMC's advantage collapses in high effective dimension unless you reorder the dimensions (Brownian bridge / PCA construction). Naive Sobol on a 360-step path is barely better than pseudo-random, and everyone benchmarks it that way and concludes QMC doesn't work.
Adjoint (reverse-mode) AD computes *all* sensitivities in O(1) × the cost of one price, independent of the number of inputs. Bump-and-revalue is O(n) × the price.
用途
For a book with 10,000 risk factors, this is a 10,000× speedup. It converted XVA from a monthly report into a real-time desk tool. Giles-Glasserman's 'Smoking Adjoints' brought it from aerospace into finance.
陷阱
AAD differentiates the *implementation*, not the mathematics. If your code has an `if` on an exercise decision, AAD differentiates through the branch and silently produces the wrong Greek at the boundary. Payoff smoothing is a prerequisite, not an optimization.
minᶜ Σᵢwᵢ(Vᵐᵐḣḣḣ(θ) − Vᵐᴱḏḏḏ)² + λ·R(θ). Ill-posed in Hadamard's sense: the solution may not be unique and does not depend continuously on the data.
用途
Every model in this page must be calibrated, and calibration is not a fitting exercise — it is the inversion of a compact operator. Tikhonov regularization (the λR(θ) term) is what makes the answer stable; the penalty is a *prior*, chosen and rarely stated.
陷阱
A perfect fit to today's prices with unstable parameters is worse than a good fit with stable ones: your Greeks come from ∂V/∂θ·∂θ/∂market, and if ∂θ/∂market is unbounded, so is your hedge. Fit quality is a vanity metric; parameter stability is the production metric.