ValueAtTime█ OVERVIEW
This library is a Pine Script® programming tool for accessing historical values in a time series using UNIX timestamps . Its data structure and functions index values by time, allowing scripts to retrieve past values based on absolute timestamps or relative time offsets instead of relying on bar index offsets.
█ CONCEPTS
UNIX timestamps
In Pine Script®, a UNIX timestamp is an integer representing the number of milliseconds elapsed since January 1, 1970, at 00:00:00 UTC (the UNIX Epoch ). The timestamp is a unique, absolute representation of a specific point in time. Unlike a calendar date and time, a UNIX timestamp's meaning does not change relative to any time zone .
This library's functions process series values and corresponding UNIX timestamps in pairs , offering a simplified way to identify values that occur at or near distinct points in time instead of on specific bars.
Storing and retrieving time-value pairs
This library's `Data` type defines the structure for collecting time and value information in pairs. Objects of the `Data` type contain the following two fields:
• `times` – An array of "int" UNIX timestamps for each recorded value.
• `values` – An array of "float" values for each saved timestamp.
Each index in both arrays refers to a specific time-value pair. For instance, the `times` and `values` elements at index 0 represent the first saved timestamp and corresponding value. The library functions that maintain `Data` objects queue up to one time-value pair per bar into the object's arrays, where the saved timestamp represents the bar's opening time .
Because the `times` array contains a distinct UNIX timestamp for each item in the `values` array, it serves as a custom mapping for retrieving saved values. All the library functions that return information from a `Data` object use this simple two-step process to identify a value based on time:
1. Perform a binary search on the `times` array to find the earliest saved timestamp closest to the specified time or offset and get the element's index.
2. Access the element from the `values` array at the retrieved index, returning the stored value corresponding to the found timestamp.
Value search methods
There are several techniques programmers can use to identify historical values from corresponding timestamps. This library's functions include three different search methods to locate and retrieve values based on absolute times or relative time offsets:
Timestamp search
Find the value with the earliest saved timestamp closest to a specified timestamp.
Millisecond offset search
Find the value with the earliest saved timestamp closest to a specified number of milliseconds behind the current bar's opening time. This search method provides a time-based alternative to retrieving historical values at specific bar offsets.
Period offset search
Locate the value with the earliest saved timestamp closest to a defined period offset behind the current bar's opening time. The function calculates the span of the offset based on a period string . The "string" must contain one of the following unit tokens:
• "D" for days
• "W" for weeks
• "M" for months
• "Y" for years
• "YTD" for year-to-date, meaning the time elapsed since the beginning of the bar's opening year in the exchange time zone.
The period string can include a multiplier prefix for all supported units except "YTD" (e.g., "2W" for two weeks).
Note that the precise span covered by the "M", "Y", and "YTD" units varies across time. The "1M" period can cover 28, 29, 30, or 31 days, depending on the bar's opening month and year in the exchange time zone. The "1Y" period covers 365 or 366 days, depending on leap years. The "YTD" period's span changes with each new bar, because it always measures the time from the start of the current bar's opening year.
█ CALCULATIONS AND USE
This library's functions offer a flexible, structured approach to retrieving historical values at or near specific timestamps, millisecond offsets, or period offsets for different analytical needs.
See below for explanations of the exported functions and how to use them.
Retrieving single values
The library includes three functions that retrieve a single stored value using timestamp, millisecond offset, or period offset search methods:
• `valueAtTime()` – Locates the saved value with the earliest timestamp closest to a specified timestamp.
• `valueAtTimeOffset()` – Finds the saved value with the earliest timestamp closest to the specified number of milliseconds behind the current bar's opening time.
• `valueAtPeriodOffset()` – Finds the saved value with the earliest timestamp closest to the period-based offset behind the current bar's opening time.
Each function has two overloads for advanced and simple use cases. The first overload searches for a value in a user-specified `Data` object created by the `collectData()` function (see below). It returns a tuple containing the found value and the corresponding timestamp.
The second overload maintains a `Data` object internally to store and retrieve values for a specified `source` series. This overload returns a tuple containing the historical `source` value, the corresponding timestamp, and the current bar's `source` value, making it helpful for comparing past and present values from requested contexts.
Retrieving multiple values
The library includes the following functions to retrieve values from multiple historical points in time, facilitating calculations and comparisons with values retrieved across several intervals:
• `getDataAtTimes()` – Locates a past `source` value for each item in a `timestamps` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified timestamps.
• `getDataAtTimeOffsets()` – Finds a past `source` value for each item in a `timeOffsets` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified millisecond offsets behind the current bar's opening time.
• `getDataAtPeriodOffsets()` – Finds a past value for each item in a `periods` array. Each retrieved value's timestamp represents the earliest time closest to one of the specified period offsets behind the current bar's opening time.
Each function returns a tuple with arrays containing the found `source` values and their corresponding timestamps. In addition, the tuple includes the current `source` value and the symbol's description, which also makes these functions helpful for multi-interval comparisons using data from requested contexts.
Processing period inputs
When writing scripts that retrieve historical values based on several user-specified period offsets, the most concise approach is to create a single text input that allows users to list each period, then process the "string" list into an array for use in the `getDataAtPeriodOffsets()` function.
This library includes a `getArrayFromString()` function to provide a simple way to process strings containing comma-separated lists of periods. The function splits the specified `str` by its commas and returns an array containing every non-empty item in the list with surrounding whitespaces removed. View the example code to see how we use this function to process the value of a text area input .
Calculating period offset times
Because the exact amount of time covered by a specified period offset can vary, it is often helpful to verify the resulting times when using the `valueAtPeriodOffset()` or `getDataAtPeriodOffsets()` functions to ensure the calculations work as intended for your use case.
The library's `periodToTimestamp()` function calculates an offset timestamp from a given period and reference time. With this function, programmers can verify the time offsets in a period-based data search and use the calculated offset times in additional operations.
For periods with "D" or "W" units, the function calculates the time offset based on the absolute number of milliseconds the period covers (e.g., `86400000` for "1D"). For periods with "M", "Y", or "YTD" units, the function calculates an offset time based on the reference time's calendar date in the exchange time zone.
Collecting data
All the `getDataAt*()` functions, and the second overloads of the `valueAt*()` functions, collect and maintain data internally, meaning scripts do not require a separate `Data` object when using them. However, the first overloads of the `valueAt*()` functions do not collect data, because they retrieve values from a user-specified `Data` object.
For cases where a script requires a separate `Data` object for use with these overloads or other custom routines, this library exports the `collectData()` function. This function queues each bar's `source` value and opening timestamp into a `Data` object and returns the object's ID.
This function is particularly useful when searching for values from a specific series more than once. For instance, instead of using multiple calls to the second overloads of `valueAt*()` functions with the same `source` argument, programmers can call `collectData()` to store each bar's `source` and opening timestamp, then use the returned `Data` object's ID in calls to the first `valueAt*()` overloads to reduce memory usage.
The `collectData()` function and all the functions that collect data internally include two optional parameters for limiting the saved time-value pairs to a sliding window: `timeOffsetLimit` and `timeframeLimit`. When either has a non-na argument, the function restricts the collected data to the maximum number of recent bars covered by the specified millisecond- and timeframe-based intervals.
NOTE : All calls to the functions that collect data for a `source` series can execute up to once per bar or realtime tick, because each stored value requires a unique corresponding timestamp. Therefore, scripts cannot call these functions iteratively within a loop . If a call to these functions executes more than once inside a loop's scope, it causes a runtime error.
█ EXAMPLE CODE
The example code at the end of the script demonstrates one possible use case for this library's functions. The code retrieves historical price data at user-specified period offsets, calculates price returns for each period from the retrieved data, and then populates a table with the results.
The example code's process is as follows:
1. Input a list of periods – The user specifies a comma-separated list of period strings in the script's "Period list" input (e.g., "1W, 1M, 3M, 1Y, YTD"). Each item in the input list represents a period offset from the latest bar's opening time.
2. Process the period list – The example calls `getArrayFromString()` on the first bar to split the input list by its commas and construct an array of period strings.
3. Request historical data – The code uses a call to `getDataAtPeriodOffsets()` as the `expression` argument in a request.security() call to retrieve the closing prices of "1D" bars for each period included in the processed `periods` array.
4. Display information in a table – On the latest bar, the code uses the retrieved data to calculate price returns over each specified period, then populates a two-row table with the results. The cells for each return percentage are color-coded based on the magnitude and direction of the price change. The cells also include tooltips showing the compared daily bar's opening date in the exchange time zone.
█ NOTES
• This library's architecture relies on a user-defined type (UDT) for its data storage format. UDTs are blueprints from which scripts create objects , i.e., composite structures with fields containing independent values or references of any supported type.
• The library functions search through a `Data` object's `times` array using the array.binary_search_leftmost() function, which is more efficient than looping through collected data to identify matching timestamps. Note that this built-in works only for arrays with elements sorted in ascending order .
• Each function that collects data from a `source` series updates the values and times stored in a local `Data` object's arrays. If a single call to these functions were to execute in a loop , it would store multiple values with an identical timestamp, which can cause erroneous search behavior. To prevent looped calls to these functions, the library uses the `checkCall()` helper function in their scopes. This function maintains a counter that increases by one each time it executes on a confirmed bar. If the count exceeds the total number of bars, indicating the call executes more than once in a loop, it raises a runtime error .
• Typically, when requesting higher-timeframe data with request.security() while using barmerge.lookahead_on as the `lookahead` argument, the `expression` argument should be offset with the history-referencing operator to prevent lookahead bias on historical bars. However, the call in this script's example code enables lookahead without offsetting the `expression` because the script displays results only on the last historical bar and all realtime bars, where there is no future data to leak into the past. This call ensures the displayed results use the latest data available from the context on realtime bars.
Look first. Then leap.
█ EXPORTED TYPES
Data
A structure for storing successive timestamps and corresponding values from a dataset.
Fields:
times (array) : An "int" array containing a UNIX timestamp for each value in the `values` array.
values (array) : A "float" array containing values corresponding to the timestamps in the `times` array.
█ EXPORTED FUNCTIONS
getArrayFromString(str)
Splits a "string" into an array of substrings using the comma (`,`) as the delimiter. The function trims surrounding whitespace characters from each substring, and it excludes empty substrings from the result.
Parameters:
str (series string) : The "string" to split into an array based on its commas.
Returns: (array) An array of trimmed substrings from the specified `str`.
periodToTimestamp(period, referenceTime)
Calculates a UNIX timestamp representing the point offset behind a reference time by the amount of time within the specified `period`.
Parameters:
period (series string) : The period string, which determines the time offset of the returned timestamp. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the `referenceTime` value's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
referenceTime (series int) : The millisecond UNIX timestamp from which to calculate the offset time.
Returns: (int) A millisecond UNIX timestamp representing the offset time point behind the `referenceTime`.
collectData(source, timeOffsetLimit, timeframeLimit)
Collects `source` and `time` data successively across bars. The function stores the information within a `Data` object for use in other exported functions/methods, such as `valueAtTimeOffset()` and `valueAtPeriodOffset()`. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
source (series float) : The source series to collect. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: (Data) A `Data` object containing collected `source` values and corresponding timestamps over the allowed time range.
method valueAtTime(data, timestamp)
(Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest timestamp closest to the specified `timestamp`. Callable as a method or a function.
Parameters:
data (series Data) : The `Data` object containing the collected time and value data.
timestamp (series int) : The millisecond UNIX timestamp to search. The function returns data for the earliest saved timestamp that is closest to the value.
Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to the specified `timestamp` ("int").
valueAtTime(source, timestamp, timeOffsetLimit, timeframeLimit)
(Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to the specified `timestamp`. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timestamp (series int) : The millisecond UNIX timestamp to search. The function returns data for the earliest bar whose timestamp is closest to the value.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : (simple string) Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to the specified `timestamp` ("int").
- The current bar's `source` value ("float").
method valueAtTimeOffset(data, timeOffset)
(Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest saved timestamp closest to `timeOffset` milliseconds behind the current bar's opening time. Callable as a method or a function.
Parameters:
data (series Data) : The `Data` object containing the collected time and value data.
timeOffset (series int) : The millisecond offset behind the bar's opening time. The function returns data for the earliest saved timestamp that is closest to the calculated offset time.
Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to `timeOffset` milliseconds before the current bar's opening time ("int").
valueAtTimeOffset(source, timeOffset, timeOffsetLimit, timeframeLimit)
(Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to `timeOffset` milliseconds behind the current bar's opening time. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffset (series int) : The millisecond offset behind the bar's opening time. The function returns data for the earliest bar's timestamp that is closest to the calculated offset time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to `timeOffset` milliseconds before the current bar's opening time ("int").
- The current bar's `source` value ("float").
method valueAtPeriodOffset(data, period)
(Overload 1 of 2) Retrieves value and time data from a `Data` object's fields at the index of the earliest timestamp closest to a calculated offset behind the current bar's opening time. The calculated offset represents the amount of time covered by the specified `period`. Callable as a method or a function.
Parameters:
data (series Data) : The `Data` object containing the collected time and value data.
period (series string) : The period string, which determines the calculated time offset. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
Returns: ( ) A tuple containing the following data from the `Data` object:
- The stored value corresponding to the identified timestamp ("float").
- The earliest saved timestamp that is closest to the calculated offset behind the bar's opening time ("int").
valueAtPeriodOffset(source, period, timeOffsetLimit, timeframeLimit)
(Overload 2 of 2) Retrieves `source` and time information for the earliest bar whose opening timestamp is closest to a calculated offset behind the current bar's opening time. The calculated offset represents the amount of time covered by the specified `period`. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
period (series string) : The period string, which determines the calculated time offset. The specified argument must contain a unit and an optional multiplier (e.g., "1Y", "3M", "2W", "YTD"). Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple containing the following data:
- The `source` value corresponding to the identified timestamp ("float").
- The earliest bar's timestamp that is closest to the calculated offset behind the current bar's opening time ("int").
- The current bar's `source` value ("float").
getDataAtTimes(timestamps, source, timeOffsetLimit, timeframeLimit)
Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to one of the UNIX timestamps specified in the `timestamps` array. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
timestamps (array) : An array of "int" values representing UNIX timestamps. The function retrieves `source` and time data for each element in this array.
source (series float) : The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each item in the `timestamps` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
getDataAtTimeOffsets(timeOffsets, source, timeOffsetLimit, timeframeLimit)
Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to one of the time offsets specified in the `timeOffsets` array. Each offset in the array represents the absolute number of milliseconds behind the current bar's opening time. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
timeOffsets (array) : An array of "int" values representing the millisecond time offsets used in the search. The function retrieves `source` and time data for each element in this array. For example, the array ` ` specifies that the function returns data for the timestamps closest to one day and one week behind the current bar's opening time.
source (float) : (series float) The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each offset specified in the `timeOffsets` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
getDataAtPeriodOffsets(periods, source, timeOffsetLimit, timeframeLimit)
Retrieves `source` and time information for each bar whose opening timestamp is the earliest one closest to a calculated offset behind the current bar's opening time. Each calculated offset represents the amount of time covered by a period specified in the `periods` array. Any call to this function cannot execute more than once per bar or realtime tick.
Parameters:
periods (array) : An array of period strings, which determines the time offsets used in the search. The function retrieves `source` and time data for each element in this array. For example, the array ` ` specifies that the function returns data for the timestamps closest to one day, week, and month behind the current bar's opening time. Each "string" in the array must contain a unit and an optional multiplier. Supported units are:
- "Y" for years.
- "M" for months.
- "W" for weeks.
- "D" for days.
- "YTD" (Year-to-date) for the span from the start of the current bar's year in the exchange time zone. An argument with this unit cannot contain a multiplier.
source (float) : (series float) The source series to analyze. The function stores each value in the series with an associated timestamp representing its corresponding bar's opening time.
timeOffsetLimit (simple int) : Optional. A time offset (range) in milliseconds. If specified, the function limits the collected data to the maximum number of bars covered by the range, with a minimum of one bar. If the call includes a non-empty `timeframeLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
timeframeLimit (simple string) : Optional. A valid timeframe string. If specified and not empty, the function limits the collected data to the maximum number of bars covered by the timeframe, with a minimum of one bar. If the call includes a non-na `timeOffsetLimit` value, the function limits the data using the largest number of bars covered by the two ranges. The default is `na`.
Returns: ( ) A tuple of the following data:
- An array containing a `source` value for each identified timestamp (array).
- An array containing an identified timestamp for each period specified in the `periods` array (array).
- The current bar's `source` value ("float").
- The symbol's description from `syminfo.description` ("string").
Returns
Overnight vs Intra-day Performance█ STRATEGY OVERVIEW
The "Overnight vs Intra-day Performance" indicator quantifies price behaviour differences between trading hours and overnight periods. It calculates cumulative returns, compound growth rates, and visualizes performance components across user-defined time windows. Designed for analytical use, it helps identify whether returns are primarily generated during market hours or overnight sessions.
█ USAGE
Use this indicator on Stocks and ETFs to visualise and compare intra-day vs overnight performance
█ KEY FEATURES
Return Segmentation : Separates total returns into overnight (close-to-open) and intraday (open-to-close) components
Growth Tracking : Shows simple cumulative returns and compound annual growth rates (CAGR)
█ VISUALIZATION SYSTEM
1. Time-Series
Overnight Returns (Red)
Intraday Returns (Blue)
Total Returns (White)
2. Summary Table
Displays CAGR
3. Price Chart Labels
Floating annotations showing absolute returns and CAGR
Color-coded to match plot series
█ PURPOSE
Quantify market behaviour disparities between active trading sessions and overnight positioning
Provide institutional-grade attribution analysis for returns generation
Enable tactical adjustment of trading schedules based on historical performance patterns
Serve as foundational research for session-specific trading strategies
█ IDEAL USERS
1. Portfolio Managers
Analyse overnight risk exposure across holdings
Optimize execution timing based on return distributions
2. Quantitative Researchers
Study market microstructure through time-segmented returns
Develop alpha models leveraging session-specific anomalies
3. Market Microstructure Analysts
Identify liquidity patterns in overnight vs daytime sessions
Research ETF premium/discount mechanics
4. Day Traders
Align trading hours with highest probability return windows
Avoid overnight gaps through informed position sizing
Market Performance by Yearly Seasons [LuxAlgo]The Market Performance by Yearly Seasons tool allows traders to analyze the average returns of the four seasons of the year and the raw returns of each separate season.
🔶 USAGE
By default, the tool displays the average returns for each season over the last 10 years in the form of bars, with the current session highlighted as a bordered bar.
Traders can choose to display the raw returns by year for each season separately and select the maximum number of seasons (years) to display.
🔹 Hemispheres
Traders can select the hemisphere in which they prefer to view the data.
🔹 Season Types
Traders can select the type of seasons between meteorological (by default) and astronomical.
The meteorological seasons are as follows:
Autumn: months from September to November
Winter: months from December to February
Spring: months from March to May
Summer: months from June to August
The astronomical seasons are as follows:
Autumn: from the equinox on September 22
Winter: from the solstice on December 21
Spring: from the equinox on March 20
Summer: from the solstice on June 21
🔹 Displaying the data
Traders can choose between two display modes, average returns by season or raw returns by season and year.
🔶 SETTINGS
Max seasons: Maximum number of seasons
Hemisphere: Select NORTHERN or SOUTHERN hemisphere
Season Type: Select the type of season - ASTRONOMICAL or METEOROLOGICAL
Display: Select display mode, all four seasons, or any one of them
🔹 Style
Bar Size & Autofit: Select the size of the bars and enable/disable the autofit feature
Labels Size: Select the label size
Colors & Gradient: Select the default color for bullish and bearish returns and enable/disable the gradient feature
Returns Model by TenozenHey there! I've been diving into the book "Paul Wilmott on Quantitative Finance," and I stumbled upon this cool model for calculating and modeling returns. Basically, it helps us figure out how much a price has changed over a set number of periods—I like to use 20 periods as a default. Once we get that rate of change value, we crunch some numbers to find the standard deviation and mean using all the historical data we have. That's the foundation of this model.
Now, let's talk about how to use it. This model shows us how returns and price behavior are connected. When returns hang out in the +1 to +2 standard deviation range, it usually means returns are about to drop, and vice versa. Often, this leads to corresponding price moves. But here's the thing: sometimes prices don't do what we expect. Why? It's because there's another hidden factor at play—I like to call it "power."
This "power" isn't something we can see directly, but it's there. Basically, when returns are within that standard deviation range, the market faces resistance when trying to move in its preferred direction, whether bullish or bearish. The strength of this "power" determines if the market will snap back to the average or go for a wild ride. It can show up as small price wiggles, big price jumps, or lightning-fast moves. By understanding this "power," we can get a better handle on what the market might do next and avoid getting blindsided. In the meantime, I couldn't explain "power" yet, but In the future, when I've learned enough, I'd love to share the model with you guys!
So... I'm planning to explore and share more models from this book as I learn, even if those pesky math formulas can be tough to crack. I hope you find this indicator as helpful as I do, and if you've got any suggestions or feedback, please feel free to share! Ciao!
YoY or MoM ReturnsThis script is a technical indicator that calculates the year-over-year (YoY) or month-over-month (MoM) returns of a security.
The returns are then plotted on a chart, with positive returns colored in green and negative returns colored in red.
Monthly ReturnsDisplays monthly and yearly returns in tabular format along with maximum, minimum, average returns and standard deviations.
This uses boxes to build the table and as maximum boxes that could be used is 500, it displays up to 32 years of returns. However, for maximum, minimum, average and standard deviation calculations, it uses data from all months since inception.
This requires timeframe to be set to one month (1M). Cell widths correspond to years. For the first year, cell widths may be shorter and there could be overlap of numbers as nothing could be drawn before the first bar.
Provide sufficient space for the table to render properly. Zooming out or less space may lead to overlapping of numbers.
Performance Tablethis scrip is modified of Performance Table () of TradingView user @BeeHolder = Thank u very much.
-
@BeeHolder formula is based on daily basis,
but my calculation is based on respective day, week and month.
-
The formula of the calculation is (Current Close - Previous Close) * 100 / Previous Close, where Past value is:
1D = close 1 day before
5D = close 5 day before
1W - close 1 week before
4W = close 4 week before
1M - close 1 month before
3M - close 3 month before
6M - close 6 month before
12M - close 12 month before
52W - close 52 week before
Also table position cane be set.
thank you all
-
Annual Returns % Comparison [By MUQWISHI]Overview
The Annual Returns % Comparison indicator aimed to compare the historical annual percentage change of any two symbols. The indicator output shows a column-plot that was developed by two using a pine script table, so each period has pair columns showing the yearly percentage change for entered symbols.
Features
- Enter date range.
- Fill up with any two symbols.
- Choose the output data whether adjusted or not.
- Change the location of the table plot
- Color columns by a symbol.
- Size the height and width of columns.
- Color background, border, and text.
- The tooltip of the column value appears once the cursor sets above the specific column. As it seen below.
Let me know if you have any questions.
Thanks.
ln(close/20 sma) adjusted for time (BTC)(This indicator was designed for the BTC index chart)
Designed for Bitcoin. Plots the log of the close/20W SMA with a linear offset m*t, where m is the gradient I've chosen and t is the candle index. Anything above 1 is a mania phase/market cycle top. If it peaks around 0.92 and rolls over, it could be a local/market cycle top.
This will obviously not work at all in the long term as Bitcoin will not continue following the trend line on the log plot (you can even see it start to deviate in the Jan-Feb 2021 peaks where the indicator went to 1.15).
It identifies the 2011, 2013 (both of them), 2017 tops as being just above 1. It also identifies the 2019 local peak and 2021 market cycle top at ~0.94.
Feel free to change the gradient or even add a function to curve the straight line eventually. I made this for fun, feel free to use it as you wish.
Yearly Percentage ReturnsAn indicator that lets you visualize the historical Yearly Percentage returns of any symbol .
Key Features:
Displays the yearly returns from start to end of each year
Displays a table showing all yearly returns for current symbol
Displays start of each year as a vertical line
Displays up to 5 custom horizontal levels
Table Settings:
Enable table - Show/Hide the table
Size - Sets the size of the table
Position - Sets the position of the table on the screen
Direction - Sets the direction of the table to display the data (Vertically or Horizontally)
Weekly Returns with BenchmarkSome time ago I published Monthly returns table. Now It's time for weekly one.
To get it work you need a pretty big screen, but I hope it will be useful for some of you.
Features of this table includes:
Display weekly returns of your strategy, benchmark, and alpha over this benchmark.
Select benchmark to be another instrument
Select the date from which you want to compute monthly returns
Show/hide benchmark and alpha
Choose colors for gradient for gain/loss values
Use it with any type of strategy
Use it with replay
Thanks to @MUQWISHI to help me coding it.
It's not about the strategy itself but the way you display returns on your chart. So pls don't critique my choice of the strategy and its performance 🙂
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
One Year ReturnThis is a script meant for the weekly timeframe . It shows the change between the current close and the close 52 bars ago. I find that this data can be useful for deciding how long to stay in a trade, and for deciding how far a stock is likely to move in a year based on it's historical returns. The High average takes the sum of all positive returns and averages it using the number of bars where the data was positive, the low average does the same but with all the returns below zero. When both are turned on you will see a band between these values.
conditional_returnsThis script attempts to contextualize the instrument's latest return. It asks, "when a return of the same or greater magnitude occurred in the past, in the same direction, what was the following period's return?"
By default, the latest return is used. For example, on a daily chart, that would mean "today's" return. However, you can select any return you want using the "override" input.
The output table shows:
- The latest/override return, as a percentage. This is in the top left, fuchsia cell.
The first three, blue columns, show:
- The count of up and down (or positive and negative) next period returns. This shows you the sample size.
- The percentage of up/down next period returns.
- The average next-period return return, up and down, as percentages.
The next three, green columns show these same statistics, but for all returns--every period in the active date range is used. This data serves as a basis for comparison.
Note that you can select a custom date range with the "start" and "end" inputs. The corresponding area on the chart is shaded light grey, to show which data is used in the computations.
Simple/Compounded Returns & Drawdowns TableVery excited to bring this script to the public. This is a very useful table that displays the performance of any strategy you give it in a more detailed view. It runs on all timeframes and at any position on the chart with the replay function. It also updates on tick changes. The table consists of three modes: Simple Equity, Compound Equity and Drawdown.
Simple Equity – shows the change in equity for every month and year. It is calculated by finding the difference in initial equity at the beginning of the month/year and the end of the month/year. The table will thus display strategy performance in blocks of time that are not correlated. It is an excellent way to see individual month/year performance from start to finish but it may not represent true change in equity over time. For example, let's assume that 100% of equity is used on every trade for simplicity. If a loss of 50% is made in the first month and a profit of 100% is made in the next month, the strategy will show 50% profit for the year. This aggregate value might be helpful to know for testing purposes, but in reality, the account is actually at break-even for the year (Initial Equity * 0.5 * 2 = Initial Equity).
Compound Equity – shows compounded change in equity for every month and year. It is calculated by finding the difference in starting equity when the strategy is run and equity at the end of the month/year. The table will thus display the true strategy performance – compounded equity at the end of each month/year.
Drawdown – shows max drawdown for every month and year. It is calculated by finding the difference between the highest equity achieved for the month/year and the trough in equity for the same month/year. Notice: strategy tester might have a max drawdown value higher than any of the drawdown values in the table. This is because the strategy tester calculates the difference between the highest and lowest equity for the entire strategy, whereas the table displays drawdowns for months and years only. Sometimes, the max drawdown for the year will also be the max drawdown for the entire strategy; hence the two values will be the same.
To use this table with your own strategy, simply find " PLACE YOUR STRATEGY CODE HERE " at the bottom of the script and place your strategy code there. Special thanks to QuantNomad for the inspiration. As always, please let me know if there are any bugs or if you need some help. Leave a like if you wish!
Risk adjusted returns data (volatility optimised)RAR - risk adjusted returns. This methodology could be helpful in portfolio creation and position size risk management. We can set our own preference of risk tolerance via the X variable which is the exponent of volatility in our calculations. This gives an unlimited set of example portfolios on a given time-frame that can be sorted from return oriented to volatility reduction oriented as X increases. RARs are to be compared against eachother.
Monthly Returns in Strategies with Market BenchmarkThis is a modified version of this excellent script Monthly Returns in PineScript Strategues by QuantNomad
I liked and used the script but wanted to see how strategy performed vs market on each month/year. So I am sharing back.
The modification consists in adding Market or Buy & Hold performance between parenthesis inside each cell to better see how strategy performed vs market.
Also, 3 red levels and 3 green levels have been used :
For green :
1/ Light when strategy pnl > 0 but < market
2/ medium when strategy pnl > 0 and > market
3/ Dark when strategy pnl > 0 and market < 0 or pnl > market x 2
Same logic in the opposite direction for red.
The strategy provided here is just a showcase of how to use the table in pine script.
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
Monthly Returns in PineScript StrategiesI'm not 100% satisfied with the strategy performance output I receive from TradingView. Quite often I want to see something that is not available by default. I usually export raw trades/metrics from TradingView and then do additional analysis manually.
But with tables, you can build additional metrics and tools for your strategies quite easily.
This script will just show a table with monthly/yearly performance of your script. Quite a lot of traders/investors used to look at returns like that. Also, it might help you to identify periods of time when your strategy performed good/bad than expected and try to analyze that better.
The script is very simple and I believe you can easily apply it to your own strategies.
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
Rolling ReturnsWhat does this indicator show?
This indicator shows the rolling return of a set lookback period.
The default indicator value is 20 which will show the rolling 20-day return because 20 trading days is 1 month.
Seasonality of ReturnsHi!
I want to share a simple script I built to analize the seasonality of Bitcoin and other assets.
So far it just displays the average return of each month, but I might add some more things later on.
The best timeframe to use it is the monthly timeframe it works on all timeframes but you need the full history for the average, and on weekly you will see issues cause weeks dont match months
On the dataview you can see the variance of each month, feel free to edit it at your own like
Mikel
[BCT] Can BTC be predicted or is it purely random?Variance Ratio**This indicator can be applied to the ticker of your choice (not just BTC)**
Markets are said to be "efficient". An efficient market is by definition unpredictable - no matter the amount of ML, computation, or indicators thrown at it. In particular, in an efficient market, TA will not be of help.
An illustration of efficient markets is the WSJ's longstanding monkey vs. human contest:Blindfolded Monkey Beats Humans With Stock Picks, granted there are several flaws to it.
BTC is a relatively new market. New markets are typically highly inefficient (easier to make money) and become more and more efficient over time (harder to make money). How much more efficient is BTC becoming?
We apply the Variance Ratio method and apply it to BTC.
BACKGROUND ON THE VARIANCE RATIO METHOD
Based on 1988 MacKinlay's seminal paper "Stock Market Prices do not Follow a Random Walk", the idea is to exploit a phenomenon called "variance scaling".
For those keen on looking into the math, the short version of it is under the assumption of iid (random walk) we have the following:
H0: Var(Sum(returns over K bars))=Sum(Var(returns over 1 bar))=k*Var(return over 1 bar)
We look to reject or not H0 depending on the observations.
In this script, we compare the variance of the (log) returns for the chart selected between:
(1) The (average) variance over k bars (call this Vk)
(2) The (average) variance over 1 bar (call this V1)
H0 simply says that Vk=k*V1 if the stock follows a random walk.
We compute the Variance Ratio VR(k)=Variance(returns over k bar)/(Sum(Var(returns over 1 bar)))-1
We then compute the associated Z-score which we chart out for a configurable k number of bars.
HOW TO INTERPRET THE CHART
The line drawn is the Z-Score for VR(k). It represents the number of standard deviations of VR(k) from 0 - the further out, the less random.
- If the line is close / hovers around 0, the ticker appears to follow a random walk (i.e. may not be predictable)
- If the line is consistently > 2 or <-2, the ticker likely does not follow a random walk (i.e. may have predictable features)
- If the line is positive, it means that the Variance on the k bars is larger than the variance on 1 bar (more variance on longer timeframes)
- If the line is negative, it means that the Variance on the k bars is smaller than the variance on 1 bar (more variance on smaller timeframes)
USE CASES
- Identify timeframes where you won't be able to make money
- Identify whether a stock cannot be predicted (forget about TA, indicators etc. -- a random walk is not predictable)
- Identify whether a stock is becoming less and less predictable (Z-score amplitude will decrease over time)
FEATURES
- select the number of K bar to compare vs. 1 bar (default = 16) - ideally a power of 2 but any other number will work. The chart is based off this selection
- select the lookback period for the analysis (500 bars by default)
- select the source to analyze (default = close, but you may select other inputs to calculate the returns from)
- results form the statistical tests on different K's in the table on the right/bottom side of the chart (H0 rejected = not random walk; H0 not rejected = it essentially looks rather random and we can't conclude that it's not a random walk)
COMMENTARY ON BTC
- It appears BTC's absolute value of the ZScore on the Variance Ratio is declining year after year - corroborating an increasingly efficient market as new participants join.
- However, we can still detect a fair amount of potential inefficiency using this simple test.
As usual, this is not investment advice. DYOR.
With love,
🐵BCT🐵
Return by day of the weekBuy on Mondays sell on Tuesdays.
Just a simple tracking of returns.
It works only on the weekly charts
Return (Percent Change)This Script displays Regular or Log Returns as either a line or histogram and labels the current bar.
If something other than price is selected as the source, the result is percent change with a positive or negative slope.
If a moving average of price is used as the source, the result is analogous to a strength index
Other options include a look-back period adjustment (the default is 1),
smoothing results by converting to an EMA, and
Bollinger Bands with Length and Standard Deviation inputs.
Kolmogorov-Smirnov TestThe Kolmogorov–Smirnov test aims to tell you if the distribution of prices (or log returns) tends to follow a normal distribution or not. You can read about this test on Wikipedia . It seems to be a basic but trusted measure in the quantitative trading world.
When KS-t columns are blue, then it's safe to assume normal distribution. When they are red, the normal distribution assumption is proven wrong by the magnitude of the KS-t value.
In the plotting tab of the script, you can activate another option that displays the probability of the distribution being actually normal. It's values are bounded between 0 and 1, like all probabilities.
This test can be useful when using statistical concepts for trading markets, like standard deviations, z-scores, etc because they all depend on the assumption of prices (or log returns) being normaly distributed.
If you see something wrong, don't hesitate to message me.
Happy trading to all.