TradingView strategy research

Crisis alpha: predefined stress windows and strategy attribution

Crisis alpha describes returns earned during market stress, often discussed in relation to managed futures and trend following. It is a conditional performance claim, not a promise of protection in every selloff. To test it, define stress using information available at the time, record the position already held, and separate subsequent trading gains from earlier losses and costs. A profitable stress window can coexist with a losing full-period strategy.

See the decision guide

Stress performance depends on the path into the event

In Correction or Crisis?, Kathryn Kaminski explains why crisis duration and prior positioning matter for managed futures. A strategy positioned for the preceding trend can lose during a sudden reversal. Sustained moves leave more time to adapt. This mechanism is narrower than saying that trend following profits whenever equities fall.

  • AQR's Tail Risk Hedging: Contrasting Put and Trend Strategies distinguishes direct put protection from indirect trend exposure. Their costs and response to market stress differ; neither label alone establishes the payoff of a particular implementation.
  • Positive return during a stress window is not automatically regression alpha. A claim of risk-adjusted alpha also needs a specified factor model, estimation sample and uncertainty. This page measures conditional returns and dollar attribution.
  • The single-symbol experiment below uses the chart asset as its stress proxy. It does not establish crisis protection for a diversified portfolio, or reproduce a managed futures index.

Define a stress event without knowing its eventual bottom

Use standard daily candles and a fixed data-adjustment policy. At close t, let H(t) be the highest close over the latest 60 available bars, including t, and D(t) = close(t) / H(t) - 1. The illustrative trigger is D(t) <= -10% while the event detector is armed. Its thresholds are research choices, not an economic definition of every crisis.

  • The reset uses a rolling high. An old peak leaving the 60-bar window can permit rearming without a return to that old price; this is intentional and should be logged.
  • A peak-to-trough chart can describe a historical crisis, but its final trough was unknown at the peak. Keep that retrospective description separate from an implementable forward-window rule.
  • These windows can contain recovery sessions. Calling only the losing sessions a crisis would remove exactly the reversals that can hurt a trend strategy.
DecisionPredeclared policy
Information setRequire complete positive-price history for both the stress lookback and the trend signal. No future peak, trough or recovery date enters the trigger.
WindowLabel the next 20 available daily return intervals after the trigger close. The trigger-day loss remains outside this forward window and must still appear in the full-sample report.
OverlapIgnore additional triggers during an active window. Do not extend an event because the decline continues.
RearmAfter a window ends, require a later close with D > -5% before arming again. A new event then requires another D <= -10% observation.
Incomplete sampleMark an event with fewer than 20 remaining observations as censored. Report it separately from completed-window averages, without removing its P&L from the full equity path.

Keep the trend rule independent of the stress label

The baseline compares the current close with the close 50 bars earlier. A higher close requests 100 shares long, a lower close requests 100 shares short, and equality requests flat. Decisions occur at confirmed daily closes; orders normally fill at the following open under the declared settings. The stress detector labels outcomes and never authorizes a trade.

  • The strategy starts flat after warm-up, holds a fixed share count between direction changes and has no stop-loss order. It uses 100,000 units of starting capital in the chart currency. The illustrative 100-share quantity is not a risk target or a suitable size for every instrument.
  • Record three timestamps: trigger close, first subsequent short decision and short fill. If already short, report the position at detection instead of inventing a negative delay. If no short fill occurs within the window, report that explicitly.
  • A shorter lookback can respond earlier but can also reverse more often in sideways markets. Compare delays, turnover and net losses together; speed alone does not measure protection.
  • For stocks or ETFs, verify borrow availability and corporate-action treatment separately. Fixed share sizing can exceed available capital as prices change. Inspect rejected orders and margin liquidations before interpreting returns.

Pine v6: trade one symbol and label forward stress intervals

Run this on a standard one-day stock or ETF chart with a point value of one. The plots expose the stress classification, position and marked equity change for bar-by-bar review. The script does not calculate a cross-asset portfolio or a statistical alpha estimate. Keep the event settings fixed when comparing trend lookbacks.

  • Commission is 0.10% of transacted notional. A reversal from +100 to -100 shares sells 200 shares and pays commission on all 200. Add adverse slippage scenarios in Strategy Properties; do not deduct the same fill-price slippage again in an external ledger.
  • An event ending does not liquidate or reset the strategy. The final dataset position remains open and contributes marked P&L. A truncated event has fewer observations; retain its partial result separately.
  • The interval guard cannot detect synthetic candles or an entirely missing vendor session. Check chart type and session completeness. A syntax pass does not verify borrow, liquidity, rejected orders or the absence of margin calls.
The orange window starts on the bar after detection. Syntax validation checks the source, not trading performance. Zero slippage is a transparent baseline assumption, not an execution estimate.pine
//@version=6
strategy("Crisis alpha: signal and event audit", overlay = true,
     initial_capital = 100000, pyramiding = 0,
     margin_long = 100, margin_short = 100,
     commission_type = strategy.commission.percent, commission_value = 0.10,
     slippage = 0, calc_on_every_tick = false,
     calc_on_order_fills = false, process_orders_on_close = false)

int trendBars = input.int(50, "Trend lookback", minval = 1, maxval = 2000)
int stressBars = input.int(60, "Stress high lookback", minval = 2, maxval = 2000)
int windowBars = input.int(20, "Forward event bars", minval = 1, maxval = 252)
float triggerPct = input.float(10.0, "Trigger drawdown (%)", minval = 0.1, maxval = 99.0)
float resetPct = input.float(5.0, "Rearm drawdown (%)", minval = 0.1, maxval = 99.0)
int shares = input.int(100, "Shares per direction", minval = 1)
if not timeframe.isdaily or timeframe.multiplier != 1
    runtime.error("Use a standard one-day candle chart.")
if syminfo.pointvalue != 1
    runtime.error("This example requires a point value of one per share.")
if resetPct >= triggerPct
    runtime.error("Rearm drawdown must be smaller than trigger drawdown.")
if na(close) or close <= 0
    runtime.error("Positive closing prices are required.")

bool ready = bar_index + 1 >= math.max(stressBars, trendBars + 1)
float highClose = ta.highest(close, stressBars)
float drawdown = ready ? close / highClose - 1.0 : na
int direction = ready ? (close > close[trendBars] ? 1 : close < close[trendBars] ? -1 : 0) : 0
var int remaining = 0
var bool armed = true
bool inWindow = remaining > 0
bool trigger = false

if barstate.isconfirmed and ready
    if inWindow
        remaining -= 1
    else
        if close > highClose * (1.0 - resetPct / 100.0)
            armed := true
        if armed and close <= highClose * (1.0 - triggerPct / 100.0)
            trigger := true
            armed := false
            remaining := windowBars
    if direction == 1 and strategy.position_size <= 0
        strategy.entry("Long", strategy.long, qty = shares)
    else if direction == -1 and strategy.position_size >= 0
        strategy.entry("Short", strategy.short, qty = shares)
    else if direction == 0 and strategy.position_size != 0
        strategy.close_all(comment = "Equal reference price")

bgcolor(inWindow ? color.new(color.orange, 85) : na, title = "Forward stress window")
plotshape(trigger, title = "Stress detected at close", style = shape.triangledown,
     location = location.abovebar, color = color.orange, size = size.tiny)
plot(ready ? (inWindow ? 1 : 0) : na, "Stress interval: 1 or 0", display = display.data_window)
plot(drawdown * 100.0, "Rolling drawdown (%)", display = display.data_window)
plot(strategy.position_size, "Shares held at close", display = display.data_window)
plot(strategy.equity - strategy.equity[1], "Marked equity change", display = display.data_window)

A delayed short can earn money after the trigger and still lose overall

This invented ledger uses a three-bar trend lookback and a three-bar event window to keep every step visible. All other event thresholds match the baseline. Assume valid earlier history with no close above 100 in the 60-bar window. The closes at days -2, -1 and 0 are 80, 85 and 100. Start the ledger at day 0 with 100,000 cash, buy 100 shares at 100 and pay 10 commission. The inherited long is a stated initial condition, not a claim that the script enters at that close.

  • Assume each open equals the previous close, no slippage, and no borrow fees, financing, dividends, taxes or interest. The first short fills at day 4 open, after one complete post-trigger daily interval has already lost 400. Do not assign that short to day 2 or day 3.
  • The forward event covers days 3 through 5: gross P&L = -400 + 400 + 400 = +400. Reversing 200 shares at 84 costs 200 × 84 × 0.001 = 16.80. Event net P&L = +383.20.
  • Equity at the trigger close is 100,000 - 10 - 800 - 400 = 98,790. Event net return = 383.20 / 98,790 = +0.3879%. The chart asset falls from 88 to 76, a price return of -13.6364%; this is not an exposure-matched portfolio comparison.
  • Full ledger net P&L = -800 - 10 - 16.80 = -826.80, or -0.8268% of starting equity. The profitable forward window did not recover the earlier losses. The short remains open at day 5; there is no invented liquidation fee.
Day and closePosition during this intervalDecision at closeGross P&L
1: 92+100 shares92 > 80: remain long; D = -8%.-800
2: 88+100 shares88 > 85: remain long; D = -12%, trigger.-400
3: 84+100 shares84 < 100: request short for day 4.-400
4: 80-100 shares, reversed at open 8480 < 92: remain short.+400
5: 76-100 shares76 < 88: remain short; mark open position.+400

Change only the recovery path and the same signal fails

Keep days 0 through 3, the trigger and the initial equity unchanged. Replace the final two closes with 94 and 100. Every open still equals the preceding close. The event definition must retain this rebound even though its terminal price recovers the earlier peak.

  • Event gross P&L = -400 - 1,000 + 600 = -800. Two reversals cost 200 × 84 × 0.001 + 200 × 94 × 0.001 = 35.60. Event net P&L = -835.60, or -0.8458% of the same 98,790 trigger equity.
  • Full ledger net P&L is -1,200 - 800 - 10 - 35.60 = -2,045.60, or -2.0456%. The underlying returns to 100, but the strategy locks in losses while changing direction. A recovered index does not imply a recovered strategy.
  • A gap from 84 directly to 94 at day 4 open would be another experiment: the old long owns the overnight move, and the short fills at the new open. Recompute the ledger rather than treating the closing-price example as evidence about gap fills.
IntervalPosition and observed ruleGross P&L
Day 3: 88 to 84Still long; the short decision occurs at the close.-400
Day 4: 84 to 94Short from open 84; 94 > day 1 close 92, so request long.-1,000
Day 5: 94 to 100Long from open 94; mark equity at close 100.+600

Reconcile attribution before reporting conditional returns

For each daily interval, split gross trading P&L into the shares held overnight times (open - previous close), plus shares held after the open fill times (close - open). Then deduct actual transaction costs and any financing or borrow charges. This decomposition applies to the example's open-only fills and point value of one; more complex execution needs a fill-level ledger.

  • In the continued-decline example, the long contributes -1,600 and the short +800 across the full path. Costs total 26.80. Within the event, the long contributes -400 and the short +800. Reporting only short profits would hide both entry delay and earlier exposure.
  • Outside-window net P&L is -1,210 in either example. It includes the initial fee and the first two losses. Sideways non-event periods can add repeated reversal losses and commissions; a strategy cannot fund those losses with an assumed future crisis payoff.
  • Condition on a frozen external benchmark when studying portfolio protection. Apply the same timestamps to every constituent, reconcile contract rolls, currencies and cash returns, then aggregate actual holdings. A collection of independently scaled chart reports is not a financed portfolio backtest.
  • A few events provide little evidence about future crises. Report event dependence and censored windows; do not treat overlapping daily observations as independent crisis samples. Changes to thresholds or the benchmark are new experiments.
ReportRequired calculation or interpretation
Additive contributionsSum dollar P&L inside and outside event intervals, then divide each by the same initial equity. Include costs once. These contributions reconcile to full-period net return when there are no cash flows.
Event returnFor event k, use (ending marked equity - trigger-close equity) / trigger-close equity, with positive starting equity and no external flows. This denominator differs from additive contribution.
Conditional summaryList each completed event, then report count, mean, median, worst return and fraction profitable. If no event qualifies, report unavailable rather than zero.
Non-event behaviorReport net return, drawdown, time invested and turnover outside the windows. These intervals include pre-trigger declines, sideways churn and some recoveries.
SensitivityCompare a small declared set of trend lookbacks on identical windows. Retain losing trials and test later dates without changing the event definition.

Use Pineify after the event protocol is fixed

Pine Script AI Coding Agent can help revise the observable rule and its audit plots. Review order timing and validate the generated source. Strategy Optimizer can compare exposed input combinations in TradingView strategy reports. Its overall ranking does not calculate this page's conditional event attribution for you.

  • Freeze the stress lookback, thresholds and window length. Compare only predeclared trend lengths first, with the same symbol, dates, quantity and cost assumptions. Archive all trials, not just the highest-return row.
  • Reconcile the report with the daily marked-equity and event labels. Keep research records for unavailable borrow, rejected orders and incomplete windows. Evaluate later dates only after fixing the parameter choice.
  • Multi-asset managed futures and option hedges require additional execution and portfolio accounting. This page provides one chart strategy; neither its Pine code nor an optimizer search establishes multi-asset crisis protection.
Where Pineify fits

Pine Script AI Coding Agent

Draft or revise the trend rule and event labels as reviewable Pine code, then audit timing and syntax before interpreting any return.

Also useful: Strategy Optimizer. Compare exposed trend inputs in TradingView strategy reports while keeping event labels fixed. Reconcile conditional returns separately.

Draft the stress-window research script

Frequently asked questions

Educational research, not investment advice. All price paths and returns on this page are hypothetical arithmetic, not historical or live performance. Trading, including short selling, can produce substantial losses. Syntax validation does not establish profitability or protection during a crisis.

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.