Browse documentation
Docs/Functionality

Quantitative finance models

Use explicit inputs, method conventions, and independent checks when turning a financial calculation into a scenario model. The changes on this page are authored for the 0.66.5 draft; they…

Quantitative finance models

Use explicit inputs, method conventions, and independent checks when turning a financial calculation into a scenario model. The changes on this page are authored for the 0.66.5 draft; they require a matching application build.

Start a finance workflow

Choose the Quantitative Finance experience and open a starter. Use the I/O panel for declared inputs, readable results, method notes, and saved scenarios. Display formats change presentation, not the stored calculation precision. Fixed-point patterns such as 0.0000 and percent patterns such as 0.00% appear in these readouts. Stored formatting overrides win. This adapter does not extend dynamic formats or richer spreadsheet formatting patterns.

Group worksheet cells presents a complete rectangular readout as a table in I/O. The portfolio starter keeps its asset labels beside the weights and risk contributions while you scroll across columns. Select a value to inspect the original cell; clear the checkbox to return to individual output rows. Grouping uses only the listed cells and does not change formulas, precision, exports or result status. Sparse selections and single rows stay as individual outputs; table previews are bounded to 500 cells and 12 columns.

Starter Review workflow
finance-options-hedging European prices, Greek units, implied volatility and parity; save a baseline, change spot, and compare captured results.
finance-portfolio-risk Allocation status, annual return/volatility, contribution residuals, empirical tail conventions, and a numeric worksheet allocation table.
finance-research-simulation Actual seeded GBM paths, sample estimate/SE/95% interval, reference residual, and synthetic CAPM with HC1/Newey-West covariance. Path count and seed must be whole numbers.
finance-coupon-curve Constructed coupon prices, exact recovered annual spot rates, and instrument repricing diagnostics.
finance-option-convergence Explicit three-grid PDE comparison against a vanilla closed form; additional solves run only in this separate convergence model.
finance-credit-exposure Five annual intervals of unilateral CVA, marginal default mass, recovery and deterministic exposure assumptions.

The QP comparison in the portfolio starter uses the existing inverse-volatility allocation approximation and displays its actual risk contributions. It does not claim equal risk contributions. The simulation starter uses actual seeded paths; the separately named VAR_MONTE_CARLO uses deterministic normal-quantile positions and is not a random-path simulator.

Save a baseline with selected results, edit inputs, and use Compare with baseline to compare historical captures. Restore a scenario to apply its inputs. Comparison alone does not restore them. A .gridoc document retains supported source and saved study state. Captures disclose missing runtime and external-data identity and are not a cross-version replay guarantee. The portfolio worksheet's scalar allocation cells support numeric values exports; rich solver and regression records retain their explicit export limitations.

Numeric array inputs in I/O use JSON rows: [[0.06,0.09,0.12]] for a row vector, or [[0.0225,0.006],[0.006,0.04]] for a matrix. Keep every entry finite and preserve the model's dimensions. Invalid JSON is rejected before changing the input; a numeric array with the wrong dimensions is diagnosed by the finance calculation. Other structured input kinds remain source edits. Reset an input to remove its stored override and recover the authored value. Structured reports open in inspection rather than pretending to be scalar text.

Result inspection reuses the function catalog's method disclosure. Historical VaR uses an inclusive linearly interpolated return quantile; historical ES averages all observations at or below that threshold, including ties. CVA uses marginal interval default probabilities. The credit example derives each mass as the difference between successive survival probabilities, with loss given default equal to one minus recovery.

Portfolio input contracts

PORTFOLIO_RETURN and PORTFOLIO_BETA require equally sized, nonempty numeric vectors. Row and column vectors are accepted. Signed weights are supported; these valuation functions do not impose the optimizer's long-only constraint.

PORTFOLIO_VOLATILITY, CONTRIBUTION_TO_RISK, DIVERSIFICATION_RATIO, MARGINAL_VAR, and COMPONENT_VAR require an N × N covariance for N weights. The portfolio optimizer diagnoses a covariance size mismatch with the expected and observed dimensions, separately from a nonpositive risk-aversion control. Both PORTFOLIO_QP_WEIGHTS and .REPORT require a nonempty numeric row or column of expected returns and an N × N numeric covariance matrix for those N assets. Blanks, text, booleans and nested arrays are rejected before generic matrix conversion; a two-dimensional expected-return matrix is not flattened into a different asset list. The report records the actual shared-solver backend and stopping controls. The retired projected-gradient implementation is no longer the method used by these builtins. Errors report the expected and observed dimensions. Ragged matrices, nonfinite values, text, blanks, and nested arrays are rejected instead of silently removing positions. This changes the previous permissive behavior for malformed inputs. It does not change valid portfolio formulas or the numerical method.

Shape and finite-value checks do not certify that a supplied matrix is a statistically appropriate covariance estimate or positive semidefinite. The choice of observations, estimator, annualization, and conditioning remains part of the model. Optimizer status and covariance diagnostics should be reviewed separately from portfolio valuation.

The portfolio QP performs an additional numerical check before solving. It symmetrizes the matrix as documented, normalizes by its largest absolute entry, and applies a pivoted Schur-complement check with tolerance 64 × ε × N, where ε is f64 machine epsilon. A materially indefinite residual block produces a covariance error, rather than claiming the allocation constraints are infeasible. Semidefinite rank-deficient matrices remain allowed. This numerical check does not provide an exact convexity certificate. Its work belongs to the selected optimization call; ordinary portfolio valuations do not perform it.

Bootstrap a coupon-bond curve

BOOTSTRAP_ZERO_CURVE.EXACT(prices, coupons, maturities, face, frequency) sequentially solves discount factors and returns annual effective spot rates. The vectors must be finite, numeric, nonempty, and equal in length. Coupons are annual rates expressed as decimals; prices use the same monetary scale as face. Maturities are in years, strictly increasing, and aligned to the coupon frequency. Frequency is a positive integer from 1 to 365.

This method assumes regular coupons, valuation on the common schedule origin, no accrued interest, and redemption at face. Every earlier coupon date of a coupon-bearing bond needs an already solved discount factor. If a date is missing, Grid identifies it and stops. Zero-coupon bonds can have gaps because they need only their maturity discount factor. The function performs no interpolation and does not infer irregular schedules or settlement calendars.

For instrument k, Grid first discounts earlier coupons with the solved nodes, then solves the maturity discount factor from the remaining price. Positive discount factors above one are permitted, supporting negative rates. A nonpositive solved discount factor is rejected. Annual effective spot rates are computed as discount_factor^(-1/maturity) - 1; coupon frequency does not change this output-rate convention.

Open examples/canonical/finance-coupon-curve.grid for a constructed 3%, 4%, 5% annual curve. The example builds source prices from all cash flows, recovers the curve, and supplies an explicit repricing report.

Review a curve report

BOOTSTRAP_ZERO_CURVE.REPORT accepts the same arguments and returns a grid.finance.curve.v1 record containing the method, rate convention, coupon frequency, schedule assumptions, and one record per instrument:

  • maturity in years and annual coupon rate;
  • source price and solved discount factor;
  • annual effective spot rate;
  • repriced price and repricing residual in the source-price units.

A near-zero repricing residual confirms agreement with the supplied instrument prices. It is not evidence that the market model, an interpolation method, or an irregular cash-flow schedule has been validated. Report construction is explicit: requesting the rates alone does not retain report objects or run extra solves.

Existing approximate curve formulas

BOOTSTRAP_ZERO_CURVE retains its legacy approximation for compatibility. It treats each instrument independently using face plus one coupon at maturity and ignores earlier coupon cash flows. This can differ materially from a coupon-bond bootstrap. To migrate, explicitly change to .EXACT, check the schedule contract, compare source-instrument repricing, and retain the prior model if its outputs are needed for historical comparison.

Option-price boundaries and sensitivities

BLACK_SCHOLES returns intrinsic value at expiry and the discounted deterministic payoff at positive maturity with zero volatility. Spot and strike remain positive; time and volatility must be nonnegative; rates and all numeric inputs must be finite. Invalid option types remain errors.

The Greek functions require strictly positive time and volatility. They explicitly report unavailable sensitivity at either boundary, including at-the-money payoff kinks, rather than assigning a misleading zero derivative. This is a restricted derivative domain even where a one-sided limit could be defined. For ordinary interior points, delta is per unit of spot, gamma per squared unit of spot, vega and rho per 1.00 volatility/rate change, and theta uses annual calendar-time decay.

An empty automatic sensitivity list does not establish a zero derivative. Inspection distinguishes a smooth zero, unsupported differentiation, and an undefined derivative. Black-Scholes retains its input lineage and points to the dedicated Greek functions when automatic coverage is unavailable.

BS_IMPLIED_VOL reports volatility as unidentifiable at expiry because the payoff no longer depends on it. At positive maturity it returns zero for a price within the documented lower-bound tolerance, 1e-10 times the maximum of one, absolute price, and the discounted upper price bound. Other prices must lie within no-arbitrage bounds and the supported volatility bracket from zero to 5.0. Finite numerical tolerance is not evidence of calibration accuracy against market quotes.

Regression design orientation

REGRESS accepts a single-regressor row or column vector with one value per response. For several regressors, supply an N × K matrix with observations in rows and regressors in columns. A multivariate matrix is never silently transposed. Shape errors state the expected observation count, actual shape, and the possible TRANSPOSE remedy. Covariance-estimator choices and their corrections remain part of the returned regression result.

Name bounds and inspect evaluation success

Names consisting only of letters followed by digits can be interpreted as worksheet addresses. For example, Lower95 exceeds the supported column range. Use Lower_95 or LowerBound for a confidence bound. Current compiler diagnostics identify the token, explain the address interpretation, and suggest an underscore. The address interpretation and remedy already existed before the finance implementation. Repeated parser probes now produce one message per invalid source occurrence; distinct occurrences retain their own spans.

For API-driven research, inspect the result's ok field, diagnostics, and returned error values. An HTTP-success response can contain a failed admission or calculation. The function browser's computation summary distinguishes request success from successful calculations; missing results do not establish success.

Older runtimes cannot execute the new dotted identities. A Grid archive preserves the model but does not install the required runtime version. For spreadsheet handoffs, consult Exporting to Excel: Grid-specific functions may require an explicitly static values export.