🚀 Jumpstart 2027: Custom, Secure AI Workflows to Adopt Now. Reserve your spot →

Chris Parmer

Chris Parmer

2026-11-16

NumPy demo

Fast array math and simulation in Python, with Dash and Plotly

TL;DR

  • NumPy is the array library almost every scientific Python package is built on. Travis Oliphant created it in 2005 by merging the earlier Numeric and numarray libraries, and version 2.5.5 came out on November 15, 2026.
  • In Dash apps, NumPy does the math on grids of numbers: risk and pricing models, Monte Carlo simulations, signal and image processing, and anything with matrices. It's fast enough to recompute in a callback every time someone moves a slider.
  • With a coding agent you describe the calculation and the agent writes the array code. This post lists the NumPy capabilities worth naming, the prompts we used and other apps you can build.
  • Our example is Risk Desk, a portfolio risk app built with an agent on 22 years of daily prices for 11 exchange-traded funds (ETFs).

What is NumPy?

Most analysis in science, engineering, finance and medicine ends up as arrays: days by assets, hours by sensors, patients by time points, pixels by bands. NumPy stores each of those as one block of numbers and applies an operation to the whole block in compiled code, so you write returns @ weights instead of a loop. Statistics, linear algebra, random numbers, Fourier transforms and rolling windows are all built in, and pandas, SciPy, scikit-learn and Plotly all accept NumPy arrays directly.

That makes NumPy the engine for Dash apps like these:

  • Simulation apps that run thousands of scenarios at once, from portfolio paths to battery dispatch or dosing schedules.
  • Risk and pricing tools built on covariance matrices, percentiles and vectorized formulas.
  • Signal and image apps that treat a sensor log or a microscope image as an array for filters, spectra and masks.
  • Engineering calculators that solve linear systems and fit models with np.linalg.

You don't need to remember NumPy's syntax to build any of them. Ask a coding agent to "simulate 50,000 ten-day paths with NumPy" and it writes the rng.integers and np.prod calls. What you bring is the domain question and enough NumPy vocabulary to ask for the right thing.

What's possible

When you brief a coding agent, these are the NumPy capabilities worth naming:

  • Array math without loops: a @ b, np.cumprod, np.prod(axis=...), and broadcasting for whole tables at once.
  • Statistics: np.quantile and np.percentile for bands and tails, np.cov and np.corrcoef for covariance and correlation, np.maximum.accumulate for running peaks and drawdowns.
  • Linear algebra: np.linalg.cholesky for correlated simulations, np.linalg.eigh for principal components, np.linalg.lstsq for regressions and np.linalg.solve for linear systems.
  • Random numbers: np.random.default_rng(seed) with standard_normal, integers, choice, chisquare and multivariate_normal, repeatable with a seed.
  • Windows and lookups: sliding_window_view for rolling statistics, np.searchsorted to find dates, datetime64 for calendar math.
  • Sorting and counting: np.argsort(..., descending=True) for rankings, np.unique and np.bincount for counts.

How to build a portfolio risk app with NumPy

Risk Desk is the app a portfolio manager or risk analyst would keep on a second monitor: set the weights, then see the risk, the tails, what moves together, how the portfolio would have done in past market periods and whether the risk model holds up. It runs on adjusted daily closes from Yahoo Finance for 11 ETFs covering US and international stocks, real estate, energy and health care stocks, bonds of several maturities, and gold. We deployed it privately to Plotly Cloud.

Start with the skeleton:

Prompt: Build a Dash app called Risk Desk with Plotly charts in a clean light theme (Inter font, purple accents). Load prices.csv (date plus one adjusted close per ETF: SPY EFA EEM VNQ XLE XLV AGG IEF TLT SHY GLD) into NumPy arrays: dates as datetime64[D], prices as a float64 array (days x assets), daily simple returns. Left sidebar: portfolio value in $M, a "history used for risk" dropdown (1, 2, 5, 10, 20 years, use np.searchsorted on the dates) and one weight input per ETF, scaled to 100%. Main area: five tabs, Overview, Monte Carlo, Correlations, Stress tests, Backtest. Keep all math in a separate risk.py using NumPy only.

Overview: value at risk and where the risk comes from

Risk Desk overview: KPI cards for 1-day 99% VaR $1.90M, expected shortfall $2.42M, volatility 10.2% and SPY with 44% of the risk; a grouped bar chart of weight against share of risk per ETF; and a histogram of 502 daily P&Ls with the VaR line

The first tab answers the two questions a risk meeting starts with: how much could we lose on a bad day (the value at risk, or VaR), and which holdings drive it. The bar chart puts each fund's weight next to its share of the risk, which is where surprises show up: US stocks carry 44% of the risk, far more than their weight.

Prompt: On the Overview tab, use NumPy to compute for the selected window: the portfolio's daily P&L (returns @ weights x value), 1-day 99% historical VaR with np.quantile, expected shortfall as the mean loss beyond VaR, annualized volatility from np.cov(returns, rowvar=False) * 252, and each asset's Euler risk contribution w * (cov @ w) / sigma. Show four KPI cards, a grouped horizontal bar chart of weight vs share of risk sorted with np.argsort(..., descending=True), and a histogram of daily P&L with a dashed VaR line.

Monte Carlo: three ways to simulate the tails

Risk Desk Monte Carlo tab: a 10-day 99% VaR of $4.44M from a historical bootstrap of 50,000 paths, a histogram of simulated P&L with VaR and expected shortfall lines, and a table comparing bootstrap, normal and Student-t simulations

This tab simulates 50,000 ten-day paths for all 11 funds three ways, by resampling real days, from a normal model and from a fat-tailed Student-t model, so you can see how much the choice of model moves the answer. Here's the core of it:

rng = np.random.default_rng(7)
paths = r[rng.integers(0, len(r), size=(50_000, 10))] # (paths, days, assets): resample whole days
growth = np.prod(1 + paths, axis=1) # compound each asset over the 10 days
pnl = (growth - 1) @ w * 100e6 # portfolio P&L for every path
var_99 = -np.quantile(pnl, 0.01)

Prompt: On the Monte Carlo tab, add a method radio (historical bootstrap, normal, Student-t with 4 degrees of freedom), a horizon slider (1-20 trading days) and a confidence dropdown (95, 99, 99.5%). Simulate 50,000 paths with np.random.default_rng(seed): bootstrap with rng.integers to pick whole historical days (keeping cross-asset co-movement), normal with np.linalg.cholesky of the covariance and rng.standard_normal, Student-t by scaling the normal draws with rng.chisquare. Compound with np.prod(1 + paths, axis=1), then apply the weights. Show the P&L histogram with VaR and ES lines, and a table of all three methods with their run times.

Correlations: what moves together

Risk Desk Correlations tab: a correlation heatmap of the 11 ETFs over two years, loadings of the first two principal components, and the average pairwise correlation over trailing one-year windows from 2005 to 2026

A correlation heatmap and a principal component analysis (PCA) with np.linalg.eigh show which funds really diversify each other. Over the last two years, the first component alone explains 41% of the variation across the 11 funds, and the line chart below tracks how the stock and bond relationship has shifted since 2005.

Prompt: On the Correlations tab, compute np.corrcoef(returns, rowvar=False) for the window and show it as an annotated heatmap (blue-white-pink, fixed at -1 to 1). Run np.linalg.eigh on it, sort eigenvalues with np.argsort(vals, descending=True), and show the explained-variance share and a grouped bar chart of the first two components' loadings (flip signs so each is mostly positive). Below, plot the average off-diagonal correlation (np.triu_indices) over trailing 252-day windows, stepping 21 days, for the full history.

Stress tests: replay past periods on today's weights

Risk Desk Stress tests tab: portfolio paths through five historical scenarios, each ETF's return during the 2022 rate shock with energy stocks up 44.5% and everything else down, and a table of returns and drawdowns per scenario

The stress tab replays five historical windows on today's weights, using np.searchsorted to find the dates and np.maximum.accumulate for the worst drawdown. It's a quick way to see which holdings helped in which kind of market, for example that bonds cushioned stocks in 2008 but fell alongside them in 2022.

Prompt: On the Stress tests tab, replay these windows on today's weights: 2008 financial crisis (2007-10-09 to 2009-03-09), 2020 COVID sell-off (2020-02-19 to 2020-03-23), 2022 rate shock (2022-01-03 to 2022-10-12), 2013 taper tantrum and 2018 Q4 sell-off. Find the rows with np.searchsorted, build the path with np.cumprod(1 + returns @ w), and the worst drawdown with np.maximum.accumulate. Show all paths on one chart (x = trading days from the start), a bar chart of each ETF's return in the selected scenario, and a table.

Backtest: does the VaR model hold up?

Risk Desk Backtest tab: daily returns since 2006 against a rolling 500-day 99% historical VaR, with 76 breaches against 50 expected, a Kupiec test p-value of 0.001, and a bar chart of breaches by year peaking at 21 in 2008

A 99% VaR should be breached on about 1% of days, and this tab checks that against every day since 2006 with Kupiec's test. The lookback dropdown shows how much the answer depends on history: a 500-day window fails the test, and a 1,000-day window passes. The rolling VaR needs no Python loop:

win = np.lib.stride_tricks.sliding_window_view(port_returns[:-1], 500) # one row per day, no copy
var = -np.quantile(win, 0.01, axis=1) # one VaR per day
breaches = port_returns[500:] < -var

Prompt: On the Backtest tab, compute a rolling historical VaR of the portfolio's daily return with np.lib.stride_tricks.sliding_window_view(returns[:-1], lookback) and np.quantile(..., axis=1), with no Python loop. Compare it to the next day's return, count breaches, and run Kupiec's proportion-of-failures test with math.erfc for the p-value. Plot returns as gray dots, -VaR as a line and breaches in pink, plus breaches by year against expected, using np.bincount on datetime64[Y]. Lookback 250/500/1000.

Other apps you can build with NumPy

  • Energy: a battery dispatch simulator that runs a year of hourly prices through charge and discharge rules with np.cumsum and np.clip.
  • Finance: an options pricing app that values thousands of contracts at once with vectorized Black-Scholes formulas and Monte Carlo paths.
  • Pharma: a dosing simulator that evaluates a pharmacokinetic model for a grid of doses and patients with broadcasting.
  • Engineering: a vibration monitoring app that computes spectra of accelerometer logs with np.fft.rfft on sliding windows.
  • Science: an imaging app that treats each microscope or satellite image as an array for masks, histograms and band math.

Many of these pair NumPy with the algorithms in our SciPy demo, and our guide to Python packages for data covers the rest of the series.

What's new in NumPy 2.5

NumPy 2.5.0 came out on June 21, 2026, and 2.5.5 on November 15, 2026. It supports Python 3.12 to 3.14. From the release notes:

  • Descending sorts: np.sort and np.argsort take descending=True. Risk Desk uses it to rank risk contributions and principal components.
  • Faster np.searchsorted for many keys at once, up to 20 times faster for hundreds of thousands of keys.
  • Faster reductions and better free threading: quicker np.sum, np.any and np.all on small and medium arrays, and ufuncs that scale better on free-threaded Python.
  • Removals and deprecations: numpy.distutils is gone, and setting an array's shape or dtype attribute is deprecated (use np.reshape or .view).

Running NumPy apps on Plotly Cloud and Dash Enterprise

What we learned deploying Risk Desk, which applies the same way on Dash Enterprise:

  • Load once, compute per callback. The price history loads into NumPy arrays when the app starts, and every callback recomputes from those arrays in milliseconds, so you don't need to cache results.
  • Seed every simulation. np.random.default_rng(7) makes each Monte Carlo repeatable, so two people looking at the same weights see the same numbers.
  • Pin NumPy in requirements.txt. Risk Desk pins numpy==2.5.5 so descending=True exists in production, since it's new in 2.5.

FAQ

bluesly
x
instagram
youtube
medium
fcaebook

Product

© 2026
Plotly. All rights reserved.
Cookie Preferences
aicpa/soc2