TradingView Backtesting

Portfolio scenario analysis: joint shocks and repricing assumptions

Portfolio scenario analysis applies a specified set of market changes to the same holdings and compares their revalued total with one initial portfolio value. Define the horizon, prices, implied volatilities, currency rates and valuation models before calculating P&L. Correlation changes affect joint distributions and some product valuations; they do not create an extra loss for stocks and single-underlying vanilla options once all their valuation inputs are fixed.

See the decision guide

Freeze holdings, units and the valuation clock

All positions below are invented and already owned at the valuation instant. The reporting currency is USD. The option is a hypothetical European put on the same non-dividend-paying stock, with strike $100, 0.25 years remaining and a multiplier of 100. Interest rates are zero. Its initial model value is $3.987761 per share, or $398.776117 per contract. This is a theoretical mark, not an exchange quote.

  • The premium is already reflected in the owned option and remaining cash. Do not deduct $398.78 again from scenario P&L. This is a mark-to-market change from today, not profit since an earlier purchase.
  • Both scenarios occur immediately: no time passes, the option still has 0.25 years remaining, quantities stay fixed, and there are no trades, dividends, external cash flows or accrued interest.
  • For a multi-day scenario, reduce remaining maturity by the specified horizon, account for cash flows and financing, and handle expiry or exercise explicitly. Do not apply a time-decay loss to this instantaneous example.
HoldingQuantity and initial inputInitial USD value
StockLong 100 shares at $100$10,000.00
European putLong 1 contract; IV 20% per year$398.78
Euro cashEUR 1,000; EUR/USD = 1.100 USD per EUR$1,100.00
Dollar cash$5,000 after acquiring the holdings$5,000.00
TotalV0, calculated before rounding$16,498.78

Apply all inputs in each scenario together

Scenario A combines a stock decline, a rise in implied volatility and euro weakness. Scenario B combines a stock rally, lower implied volatility and euro strength. These are deliberately chosen teaching assumptions. The correlation is between stock returns and changes in EUR/USD, specified for a separate joint-return risk model; a single observed pair of price changes cannot itself estimate correlation.

  • A change from 20% to 40% IV is 20 percentage points, equivalent to a 100% relative increase. Enter volatility as 0.40 in the formula, not 40.
  • For an actual book, document strike and maturity mappings for the volatility surface, rate curves, FX quote direction and each factor dependency. Shocking one flat IV is only the simplified assumption for this one option.
  • Choose coherent joint assumptions before reviewing the loss. Combining unrelated historical extremes can create a state that never occurred; evaluating each factor alone can miss a joint exposure.
InputInitial stateA: decline and higher IVB: rally and lower IV
Stock price$100$80 (-20%)$110 (+10%)
Put annualized IV20%40% (+20 percentage points)15% (-5 percentage points)
EUR/USD, USD per EUR1.1001.045 (-5%)1.155 (+5%)
Stock/FX return correlation0.200.80-0.30
Remaining option maturity0.25 years0.25 years0.25 years
Rates and dividendsZeroZeroZero

Reprice the option and reconcile every contribution

With zero rates and dividends, the Black-Scholes European put is P = K N(-d2) - S N(-d1), where d1 = [ln(S/K) + 0.5 σ²T] / (σ√T), d2 = d1 - σ√T, and N is the standard normal cumulative distribution. Here K = 100 and T = 0.25. Portfolio value is V = 100S + 100P + 1,000F + 5,000, where F is USD per EUR. Scenario P&L is Vscenario - V0.

  • Calculate totals with unrounded values. The A put mark is $21.185930 per share and the B mark is $0.380756. Rounded displayed contributions can differ from displayed totals by one cent.
  • The option response is nonlinear. Its delta changes as price moves, and changing IV also changes its value. A small-move delta or delta-vega approximation is useful for attribution checks, but a 20% price shock should be repriced with the chosen model.
  • Do not add a price-only option P&L to an IV-only option P&L and assume the sum is exact. Repricing each factor sequentially creates order-dependent attribution; the joint final value remains the comparison that reconciles.
ComponentInitial valueA value / P&LB value / P&L
Stock$10,000.00$8,000.00 / -$2,000.00$11,000.00 / +$1,000.00
Put contract$398.78$2,118.59 / +$1,719.82$38.08 / -$360.70
Euro cash$1,100.00$1,045.00 / -$55.00$1,155.00 / +$55.00
Dollar cash$5,000.00$5,000.00 / $0.00$5,000.00 / $0.00
Portfolio$16,498.78$16,163.59 / -$335.18$17,193.08 / +$694.30
P&L / initial portfolio valueSame denominator for both-2.0316%+4.2082%

Correlation belongs in the joint model, not an extra P&L row

The stock, euro cash and this single-underlying European put have no cross-asset correlation input in their valuation formulas. Holding S, IV, F, maturity and rates fixed while changing only correlation leaves their total value unchanged. At expiry the vanilla payoff also depends on terminal price and strike, not a separately imposed correlation penalty. Before expiry, IV still matters.

  • Correlation affects how often joint price moves occur in a modeled distribution and how a portfolio risk measure changes. It can also be a direct pricing input for multi-asset contracts such as basket options. A barrier or liquidation rule requires a path; endpoint P&L alone does not resolve its outcome.
  • As an isolated covariance illustration, retain only the initial $10,000 stock exposure and $1,100 euro exposure. Assume annualized physical return volatility of 20% and 10%, respectively, for this linear risk calculation. These physical-volatility assumptions are separate from the put IV inputs above.
  • The annualized dollar standard deviation is sqrt[(10,000 × 0.20)² + (1,100 × 0.10)² + 2ρ(10,000 × 0.20)(1,100 × 0.10)]. It is $2,024.87 at ρ = 0.20, $2,089.04 at 0.80 and $1,969.80 at -0.30. Exposures and volatilities stay fixed here to isolate correlation.
  • Those figures exclude the put and are not the full portfolio risk, scenario losses or VaR. A full distribution model must also specify marginal returns, tails, option repricing and the horizon. For more factors, a valid correlation matrix must be positive semidefinite; changing pairwise entries independently can violate that requirement.

Reproduce the values with Python standard-library math

The code below computes the independent educational example outside TradingView and Backtest Deep Report. It uses unrounded marks, handles expiry and zero volatility, and rejects non-finite or invalid inputs. It is a zero-rate, zero-dividend European model; it does not price American early exercise or estimate executable liquidation proceeds.

Python 3; no packages required; quantities remain fixedpython
from math import erf, isfinite, log, sqrt

def put(s, k, t, iv):
    if not all(isfinite(x) for x in (s, k, t, iv)):
        raise ValueError("Inputs must be finite")
    if s <= 0 or k <= 0 or t < 0 or iv < 0:
        raise ValueError("Require positive prices and nonnegative time/IV")
    if t == 0 or iv == 0:
        return max(k - s, 0.0)  # zero rates and dividends
    n = lambda x: (1 + erf(x / sqrt(2))) / 2
    d1 = (log(s / k) + 0.5 * iv**2 * t) / (iv * sqrt(t))
    d2 = d1 - iv * sqrt(t)
    return k * n(-d2) - s * n(-d1)

def value(s, iv, fx):
    if not isfinite(fx) or fx <= 0:
        raise ValueError("FX must be positive USD per EUR")
    return 100*s + 100*put(s, 100, 0.25, iv) + 1000*fx + 5000

def stock_fx_sd(rho):
    if not isfinite(rho) or not -1 <= rho <= 1:
        raise ValueError("Correlation must be between -1 and 1")
    return sqrt(2000**2 + 110**2 + 2*rho*2000*110)

v0 = value(100, 0.20, 1.100)
print(f"Initial USD value: {v0:.2f}")
for name, s, iv, fx, rho in [
    ("A", 80, 0.40, 1.045, 0.80),
    ("B", 110, 0.15, 1.155, -0.30),
]:
    v = value(s, iv, fx)  # rho does not enter this valuation
    print(name, f"value={v:.2f}, pnl={v-v0:.2f}, return={100*(v/v0-1):.4f}%")
    print(f"Separate stock/FX risk illustration: {stock_fx_sd(rho):.2f}")

assert put(80, 100, 0, 0.40) == 20
assert put(110, 100, 0.25, 0) == 0
assert abs(v0 - 16498.776116767447) < 1e-8

Historical stress replay and hypothetical stress answer different questions

Historical stress applies measured changes from a named past interval to a stated portfolio. Hypothetical stress imposes an analyst-defined shock or path, including combinations absent from the available history. The BIS stress-testing principles call for coherent scenarios and consideration of both historical events and hypothetical future events. Neither method assigns a probability merely by producing a loss.

  • For example, a replay labeled February 19 through March 23, 2020 must obtain and document the factor changes over those exact dates. The invented A shock above is not that replay and is not a measured COVID-period result.
  • When mapping a historical percentage price move onto today's holdings, preserve its jointly observed FX and volatility context where data exist. Specify whether you transplant the changes instantaneously or simulate the elapsed interval; those choices change option maturity and P&L.
  • If the current instrument did not exist in the episode, disclose a justified proxy or record the scenario as unavailable. Replacing a missing historical IV surface with a chosen flat IV turns that part into a hypothetical assumption.
  • A backtest with no comparable crisis does not establish resilience to a future crisis. Even a well-documented replay omits future mechanisms, market structure changes and unmodeled exposures.
MethodRequired evidenceInterpretation and failure mode
Historical factor replayExact start/end dates, synchronized prices, FX, rates and IV observations; mapping to current holdingsCurrent holdings exposed to a recorded episode. Missing IV or proxy instruments limit fidelity.
Hypothetical joint shockExplicit factor vector, horizon, narrative, pricing models and omitted risksConditional result under chosen assumptions. A severe-looking label does not prove plausibility or coverage.
Historical strategy backtestPoint-in-time signals, orders, capital, costs and actual data coverageRules replayed through past data. Different holdings and trades make this different from stressing today's book.

Separate model marks from liquidation and funding

The table reports mid-model valuation before execution costs. Closing the positions can produce a different result because spreads, available depth, market impact and timing change under stress. A long put can gain theoretical value while the cash needed elsewhere in the account is unavailable until it is sold or settled.

  • For a liquidation version, value long positions at realizable bids and shorts at asks, include fees and FX conversion costs, and state how much can trade at each price. Subtract only incremental costs not already embedded in those marks.
  • Record margin calls, collateral haircuts and funding needs on a timeline if they matter. A final positive portfolio value does not prove the account could fund every interim obligation.
  • American exercise, discrete dividends, volatility skew and term structure require appropriate models and contract data. A single flat-IV European put is an intentionally narrow example.
  • Report material excluded risks and failed valuations beside the result. Do not silently replace a missing mark with zero, omit an unpriced holding or claim the worst of two scenarios bounds future losses.

Use TradingView exports for the strategy evidence they contain

TradingView strategy exports provide simulated trades and performance information. They do not by themselves supply today's complete cross-asset holdings, option contract specifications, IV surfaces or synchronized FX marks. Its native strategy orders apply to the chart instrument. Reading external symbols does not create a native multi-asset scenario engine.

  • Backtest Deep Report parses trade IDs, entry/exit timestamps, prices, quantity, net P&L and excursions from supported List of Trades CSV exports. Reconcile the original trade count, currency and net P&L before using the report. Keep strategy settings and raw exports alongside it.
  • Its implemented net profit and closed-trade equity drawdown summarize those exported trades. They are not the instantaneous portfolio repricing, joint correlation model or intraday funding test shown here. If TradingView supplies a workbook, preserve it and export the relevant trade sheet to a compatible CSV.
  • Maintain a separate position inventory and valuation input file for this scenario analysis. The Python calculation is independent; this page does not claim the report has a built-in multi-asset scenario engine.
  • Pine Script AI Coding Agent can help draft explicit strategy rules and parameters for review and validation. It does not make a scenario probable or supply missing historical option data. Test the resulting strategy separately from the portfolio valuation.
Where Pineify fits

Backtest Deep Report

Inspect supported metrics from a TradingView trade CSV, then keep holdings-based scenario repricing in a separate documented calculation.

Also useful: Pine Script AI Coding Agent. Draft and review strategy rules for a TradingView test. Verify generated code and trade behavior before interpreting its results.

Review Backtest Deep Report

Frequently asked questions

Educational scenario analysis, not investment advice. All holdings, prices, volatilities, correlations and calculated results in the example are hypothetical. Model values are not executable quotes; historical and hypothetical stresses do not guarantee future outcomes or limit losses.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.