OPEN-SOURCE SCRIPT

Cumulative Returns by Session [BackQuant]

230
Cumulative Returns by Session [BackQuant]
What this is
This tool breaks the trading day into three user-defined sessions and tracks how much each session contributes to return, volatility, and volume. It then aggregates results over a rolling window so you can see which session has been pulling its weight, how streaky each session has been, and how sessions relate to one another through a compact correlation heatmap.
We’ve also given the functionality for the user to use a simplified table, just by switching off all settings they are not interested in.
imagen
How it works
1) Session segmentation
You define APAC, EU, and US sessions with explicit hours and time zones. The script detects when each session starts and ends on every intraday bar and records its open, intraday high and low, close, and summed volume.
2) Per-session math
At each session end the script computes:
  • Return — either Percent: (Close−Open)÷Open×100(Close − Open) ÷ Open × 100(Close−Open)÷Open×100 or Points: (Close−Open)(Close − Open)(Close−Open), based on your selection.
  • Volatility — either Range: (High−Low)÷Open×100(High − Low) ÷ Open × 100(High−Low)÷Open×100 or ATR scaled by price: ATR÷Open×100ATR ÷ Open × 100ATR÷Open×100.
  • Volume — total volume transacted during that session.

imagen
3) Storage and lookback
Each day’s three session stats are stored as a row. You choose how many recent sessions to keep in memory. The script then:
  • Builds cumulative returns for APAC, EU, US across the lookback.
  • Computes averages, win rates, and a Sharpe-like ratio avgreturn÷avgvolatilityavg return ÷ avg volatilityavgreturn÷avgvolatility per session.
  • Tracks streaks of positive or negative sessions to show momentum.
  • Tracks drawdowns on cumulative returns to show worst runs from peak.
  • Computes rolling means over a short window for short-term drift.

4) Correlation heatmap
Using the stored arrays of session returns, the script calculates Pearson correlations between APAC–EU, APAC–US, and EU–US, and colors the matrix by strength and sign so you can spot coupling or decoupling at a glance.
imagen
What it plots
  • Three lines: cumulative return for APAC, EU, US over the chosen lookback.
  • Zero reference line for orientation.
  • A statistics table with cumulative %, average %, positive session rate, and optional columns for volatility, average volume, max drawdown, current streak, return-to-vol ratio, and rolling average.
  • A small correlation heatmap table showing APAC, EU, US cross-session correlations.


How to use it
  • Pick the asset — leave Custom Instrument empty to use the chart symbol, or point to another symbol for cross-asset studies.
  • Set your sessions and time zones — defaults approximate APAC, EU, and US hours, but you can align them to exchange times or your workflow.
  • Choose calculation modes — Percent vs Points for return, Range vs ATR for volatility. Points are convenient for futures and fixed-tick assets, Percent is comparable across symbols.
  • Decide the lookback — more sessions smooths lines and stats; fewer sessions makes the tool more reactive.
  • Toggle analytics — add volatility, volume, drawdown, streaks, Sharpe-like ratio, rolling averages, and the correlation table as needed.


Why session attribution helps
Different sessions are driven by different flows. Asia often sets the overnight tone, Europe adds liquidity and direction changes, and the US session can dominate range expansion. Separating contributions by session helps you:
  • Identify which session has been the main driver of net trend.
  • Measure whether volatility or volume is concentrated in a specific window.
  • See if one session’s gains are consistently given back in another.
  • Adapt tactics: fade during a mean-reverting session, press during a trending session.


Reading the tables
  • Cumulative % — sum of session returns over the lookback. The sign and slope tell you who is carrying the move.
  • Avg Return % and Positive Sessions % — direction and hit rate. A low average but high hit rate implies many small moves; the reverse implies occasional big swings.
  • Avg Volatility % — typical intrabars range for that session. Compare with Avg Return to judge efficiency.
  • Return/Vol Ratio — return per unit of volatility. Higher is better for stability.
  • Max Drawdown % — worst cumulative give-back within the lookback. A quick way to spot riskiness by session.
  • Current Streak — consecutive up or down sessions. Useful for mean-reversion or regime awareness.
  • Rolling Avg % — short-window drift indicator to catch recent turnarounds.
  • Correlation matrix — green clusters indicate sessions tending to move together; red indicates offsetting behavior.


Settings overview
Basic
  • Number of Sessions — how many recent days to include.
  • Custom Instrument — analyze another ticker while staying on your current chart.

Session Configuration and Times
  • Enable or hide APAC, EU, US rows.
  • Set hours per session and the specific time zone for each.

Calculation Methods
  • Return Calculation — Percent or Points.
  • Volatility Calculation — Range or ATR; ATR Length when applicable.

Advanced Analytics
  • Correlation, Drawdown, Momentum, Sharpe-like ratio, Rolling Statistics, Rolling Period.

Display Options and Colors
  • Show Statistics Table and its position.
  • Toggle columns for Volatility and Volume.
  • Pick individual colors for each session line and row accents.


Common applications
  • Session bias mapping — find which window tends to trend in your market and plan exposure accordingly.
  • Strategy scheduling — allocate attention or risk to the session with the best return-to-vol ratio.
  • News and macro awareness — see if correlation rises around central bank cycles or major data releases.
  • Cross-asset monitoring — set the Custom Instrument to a driver (index future, DXY, yields) to see if your symbol reacts in a particular session.


Notes
This indicator works on intraday charts, since sessions are defined within a day. If you change session clocks or time zones, give the script a few bars to accumulate fresh rows. Percent vs Points and Range vs ATR choices affect comparability across assets, so be consistent when comparing symbols.

Session context is one of the simplest ways to explain a messy tape. By separating the day into three windows and scoring each one on return, volatility, and consistency, this tool shows not just where price ended up but when and how it got there. Use the cumulative lines to spot the steady driver, read the table to judge quality and risk, and glance at the heatmap to learn whether the sessions are amplifying or canceling one another. Adjust the hours to your market and let the data tell you which session deserves your focus.

Exención de responsabilidad

La información y las publicaciones que ofrecemos, no implican ni constituyen un asesoramiento financiero, ni de inversión, trading o cualquier otro tipo de consejo o recomendación emitida o respaldada por TradingView. Puede obtener información adicional en las Condiciones de uso.