Bitcoin Logarithmic MACD Risk Metric (W, M)Description
The Bitcoin Logarithmic MACD Risk Metric (W, M) is a long-term macro analysis tool designed to identify generational buying and selling opportunities for Bitcoin. By applying logarithmic and linear regression models to the Logarithmic MACD (LMACD), this indicator normalizes price momentum relative to historical market cycle extremes.
Unlike standard MACD, the logarithmic version used here accounts for Bitcoin's exponential growth over time, allowing for a consistent comparison of momentum across different cycles.
IMPORTANT: Timeframe Compatibility
Note: This indicator is strictly designed for Weekly (W) and Monthly (M) timeframes. The regression lines won't show on other timeframes.
The regression lines (Log and Linear fits) were calculated using data points from these high-level timeframes because they contain less "noise" and are far more reliable for predicting global cyclical tops and bottoms.
It is highly recommended to wait for the candle close on the respective timeframe to confirm any signal, as mid-candle fluctuations can significantly alter the Risk Metric value.
How to Use It
The metric provides a "Risk" score between 0 and 1, visualizing where Bitcoin sits within its historical growth channel.
Sell Zone (Red): When the LMACD line enters the red zone, it indicates that Bitcoin is overbought and potentially nearing a cyclical peak.
Buy Zone (Green): When the LMACD drops into the green zone, it suggests the asset is oversold and approaching a cyclical bottom.
Confluence: While these zones have historically marked major reversals, this indicator should not be used in isolation. Always seek confluence with other technical or fundamental indicators.
Customizable Settings
Line Fits: You can choose between "Log Fit" and "Linear Fit" for both Top and Bottom lines to see which model best aligns with your current analysis.
View Mode: Switch between Fit Lines (seeing the MACD inside the channel) or Normalized (viewing the risk as a 0-1 oscillator).
Risk Levels: Adjust the thresholds for the Buy and Sell zones to fit your risk tolerance.
Price Overlay: Toggle the candle coloring on the main chart to see risk levels directly on the price action.
VIsualization Tip
If the price overlay makes the chart look too cluttered, you can hide the Bitcoin price bars in the main chart settings to focus purely on the colored risk overlay. Alternatively, you can disable the "Plot on Main Pane" option in the indicator settings if you only want to see the metric in its own separate pane below.
Limitations
Asset Focus: This indicator is specifically calibrated for Bitcoin. While you can apply it to other charts, the indicator pane will always display Bitcoin's MACD risk, whereas the price overlay will color the candles of the currently selected instrument.
Fixed Parameters: The LMACD settings (12, 26, Close) are hardcoded. This is intentional, as the regression fitting was performed specifically using these values; changing them would make the historical bands irrelevant.
Hardcoded Coefficients: The regression lines are based on historical tops and bottoms up to 2023. Future market cycles may require new approximations if Bitcoin's volatility profile shifts significantly.
Regression Specifics: The Linear Fit model treats the early 2011 peaks/bottoms as outliers. On the Monthly timeframe, the bottom line is available only as a linear fit due to the limited number of historical macro data points. The upper linear boundary is guaranteed to be broken by future price action, but it can serve as a "conservative" macro target in the meantime.
No Guarantees: Past performance does not guarantee future results. There is no certainty that the metric will reach the boundaries in every cycle or remain within them indefinitely.
Indicator

Bitcoin RSI Channel (2W, M)Bitcoin RSI Channel (2W, M)
The Bitcoin RSI Channel is a macro-analytical tool designed to identify long-term cyclical tops and bottoms of Bitcoin by applying linear regression modeling to the Relative Strength Index (RSI).
Traditionally, RSI levels like 70 and 30 are used as static markers for overbought and oversold conditions. However, as Bitcoin matures and its volatility dampens, its cyclical RSI peaks and troughs have historically followed a descending trajectory. This script accounts for that "fading" volatility by using mathematically fitted trendlines that track the actual historical extremes of Bitcoin’s momentum.
Main Objectives
Curve Fitting: Plots mathematically modeled linear regression lines through historical RSI peaks and bottoms, ensuring the channel remains as close as possible to the actual turning points of previous cycles.
Normalized View: Provides an optional "Normalized" mode where the dynamic channel is flattened into a 0-1 "Risk Metric" for easier comparison between cycles.
Main Chart Visualization: Directly projects overbought and oversold zones onto the price chart via plot coloring, allowing for a seamless confluence of price action and momentum analysis.
Cycle Forecasting: Designed as a high-timeframe tool to assist in predicting global market tops and generational buying opportunities.
IMPORTANT: Timeframe & Methodology
Please note that the regression lines in this script are specifically modeled for the 2-Week (2W) and Monthly (1M) timeframes.
These high timeframes were chosen because they significantly reduce market noise, making them superior for identifying global cycle shifts. The coefficients used in the code were derived from an approximation (fitting) of data points from 2011 through 2023.
Recommendation: Always wait for the candle to close on the 2W or Monthly timeframe to confirm a signal. Intra-candle fluctuations can be volatile and may provide premature signals before the period is finalized.
How to Use
Identifying Extremes: When the RSI enters the green "Buy Zone" or the red "Sell Zone," it historically indicates that Bitcoin has reached extreme oversold or overbought levels. These periods suggest the proximity of a potential cyclical bottom or top.
Visualizing on Price: These macro shifts are intuitively reflected through the price overlay on the main chart, providing immediate visual feedback on the current stage of the market cycle.
Strategic Caution: These zones have not been infallible in the past, and this indicator should not be used in isolation. Always seek confluence with other technical or fundamental analysis before making trading decisions.
User Tips
Clean View: You can hide the Bitcoin price bars on your main chart (via the Chart Settings) to focus entirely on the risk-based coloring provided by the indicator overlay.
Overlay Toggle: If you prefer to keep the indicator purely in its own pane, you can disable the "Plot on Main Pane" option in the script settings.
Settings & Parameters
View Mode: Switch between "Fit Lines" (standard RSI inside a diagonal channel) and "Normalized" (RSI converted into a Risk Metric).
Sell/Buy Zone Levels: Adjustable thresholds (default 0.90 and 0.10) to define your personal risk appetite for overbought and oversold conditions.
Plot on Main Pane: Toggle to enable/disable price bar colorization based on the current Risk Metric.
Limitations & Disclaimer
BTC Specificity: This indicator is purpose-built for Bitcoin. While you can load it on other symbols, the indicator pane will always calculate based on INDEX:BTCUSD data to maintain its cyclical logic. The main chart overlay, however, will color the plot of whatever instrument you are currently viewing.
Fixed RSI Optimization: The regression model is strictly optimized using the default RSI settings (14-period, Source: Close). The linear regression lines were fitted specifically to these values; therefore, the ability to modify the RSI length or source has been intentionally omitted from the settings. Changing these parameters would render the channel irrelevant, as the trendlines would no longer align with historical market extremes.
Static Modeling: The regression coefficients are "hardcoded" based on historical peaks and troughs up to 2023. As the market evolves, future cycles may require new approximations to account for shifting volatility.
No Guarantees: Mathematical models describe the past but do not guarantee the future. There is no guarantee that Bitcoin will reach the upper or lower boundaries in any given cycle, or that it will stay within them. Use this tool as one part of a comprehensive trading strategy.
Indicator

Bitcoin 1-Year Running ROI Risk MetricOverview
The Bitcoin 1-Year Running ROI Risk Metric is a macro-analysis oscillator designed to evaluate the current stage of Bitcoin's market cycle. By analyzing the 1-year rolling Return on Investment (ROI) and applying regression models to historical peaks and troughs, it translates raw market data into a normalized Risk score ranging from 0 to 1.
How it Works
Historically, due to the law of diminishing returns, Bitcoin's cycle peaks yield a progressively lower ROI each macro cycle. This indicator accounts for this phenomenon by fitting bounding regression curves to historical cycle extremes.
The script calculates the natural logarithm of the 1-year ROI. It then normalizes this value between a fitted bottom line (representing historical bear market bottoms) and a fitted top line (representing historical bull market peaks).
A Risk value near 0 (or inside the Buy Zone) indicates historical bear market lows, representing minimal macro risk and potential accumulation zones.
A Risk value near 1 (or inside the Sell Zone) suggests the market is approaching the historical limits of diminishing returns, indicating maximum macro risk and potential cycle tops.
Settings & Customization
Users can customize the indicator's behavior and visuals through the settings menu:
Top Line: Select the mathematical model used for the upper boundary of the market cycle. Choose between a Log Fit (logarithmic regression, which best captures all historical tops) or a Linear Fit (a more conservative straight line that excludes the 2011 peak).
View: Switch between the Normalized mode (displays the Risk metric as a clean 0 to 1 oscillator) and the Fit Lines mode (displays the raw logarithmic ROI values along with the upper, middle, and lower regression bands).
Sell / Buy Zone Levels: Adjust the thresholds that define the extreme risk areas. By default, the Sell Zone starts at 0.90 and the Buy Zone at 0.10. These values dictate when the oscillator and the main chart price line change colors.
Plot on the Main Pane: A simple toggle to turn the colored price line overlay on your main chart on or off.
💡 Visualization Tip
The script projects a colored price line directly onto your main chart (Green for Buy Zone, Red for Sell Zone).
To see this colored indicator line clearly without visual clutter, you can hide the standard Bitcoin price candles using the chart's object tree or settings.
Conversely, if you prefer a clean main chart and only want to view the risk oscillator in the lower pane, simply uncheck the "Plot on the Main Pane" option in the indicator's settings.
Limitations & Disclaimers
Please keep the following points in mind when using this tool:
Asset Specific: This indicator is strictly designed for Bitcoin. It internally fetches data using the INDEX:BTCUSD ticker. While you can load it on any other asset's chart, the oscillator in the lower pane will always display Bitcoin's data.
Timeframe Dependency: Although the indicator will calculate on any timeframe, it is highly recommended to use the Weekly (1W) chart. The regression curve fitting was performed using weekly closes. On other timeframes, the regression boundaries may not align perfectly with the exact global tops and bottoms.
Hardcoded Coefficients: The curve fitting was calculated based on Bitcoin's global tops and bottoms up to the year 2023. The resulting mathematical coefficients are hardcoded into the script. Future macro cycles may require a new approximation and an update to these coefficients.
Linear Fit Outlier: If you select the "Linear Fit" option for the Top Line in the settings, note that this model intentionally ignores the 2011 global top, treating it as a statistical outlier. This linear boundary is guaranteed to be broken by future price action, but it can serve as a "conservative" macro target in the meantime.
No Guarantees: There is no guarantee that Bitcoin's price or ROI will reach the upper or lower boundaries in the future, nor is it guaranteed to remain within them. This indicator is for educational and macro-analysis purposes only and does not constitute financial advice.
Indicator

Pi Cycle Top OscillatorOverview
The Pi Cycle Top Oscillator is an advanced, adaptive iteration of the classic Pi Cycle Top indicator, reimagined as a continuous risk metric. While the original indicator famously predicted Bitcoin’s macro peaks by waiting for a binary crossover of the 111-day SMA and the 2x 350-day SMA, this script translates the relationship between these two moving averages into a normalized 0 to 1 oscillator, providing both buy and sell signals.
As an asset matures, its volatility historically compresses. In the 2021 cycle, the classic moving averages barely touched, meaning future cycles might never see a pure crossover due to the law of diminishing returns. This oscillator solves that problem by replacing the rigid crossover requirement with dynamic, regression-based boundaries.
Tip
Hide the Bitcoin price chart to clearly view the metric in the main chart pane:
How it Works
Instead of waiting for a binary signal, this indicator calculates the exact mathematical ratio between the two moving averages:
ratio = ta.sma(close, 111) / (ta.sma(close, 350) * 2)
Using historical extremes of this ratio, the script projects two dynamic boundaries:
Top Boundary: A logarithmic regression curve that accounts for historical volatility decay, descending over time.
Bottom Boundary: A linear regression line representing macro bottoms.
The current ratio is then normalized between these two converging lines, producing a continuous Risk metric.
Key Features
Continuous Risk Scale: Unlike the classic indicator which is either "on" or "off", this oscillator provides a constant reading from 0 (historical bottom) to 1 (probable macro top).
Volatility Adjusted: The logarithmic top line factors in macro volatility decay, ensuring the indicator remains relevant in future cycles even if a classic crossover never occurs.
Visual Chart Feedback: The main chart automatically highlights price bars in Green when Risk falls below your custom Buy Zone Level, and Red when Risk exceeds your Sell Zone Level.
Dual Display Modes: Use the indicator settings to toggle between the normalized 0-1 "Oscillator" view and the raw "Fit Lines" view to see the actual ratio and regression curves.
How to Use
This tool is designed for macro-level portfolio risk management rather than short-term trading.
Accumulation: Readings near or below 0.1 historically correlate with macro bottoms, presenting potential long-term accumulation zones.
Distribution: Readings near or above 0.9 indicate severe market overheating, signaling potential distribution zones.
You can adjust the Buy and Sell zone thresholds in the indicator settings to fit your personal risk tolerance.
Limitations
Bitcoin Exclusive: This indicator is designed strictly for analyzing Bitcoin. Its mathematical model is based entirely on Bitcoin's historical macro cycles and is not applicable to other cryptocurrencies or traditional assets.
No Guaranteed Extremes: There are no guarantees that the oscillator will reach the upper or lower boundaries in future cycles, nor that it will remain strictly within the 0 to 1 range. For example, during the 2025 cycle, the oscillator never reached the theoretical sell zone, demonstrating that market dynamics can and do shift.
Static Curve Fitting: The regression curves for the upper and lower boundaries were fitted using the global tops and bottoms of the 111-day and 2x 350-day SMA ratio prior to 2023. The resulting equation coefficients are hardcoded directly into the script. As new macro extremes form in the future, these boundary models may eventually require a new approximation to maintain their accuracy.
Indicator

Relative Risk MetricOVERVIEW
The Relative Risk Metric is designed to provide a relative measure of an asset's price, within a specified range, over a log scale.
PURPOSE
Relative Position Assessment: Visualizes where the current price stands within a user-defined range, adjusted for log scale.
Logarithmic Transformation: Utilizes the natural log to account for a log scale of prices, offering a more accurate representation of relative positions.
Calculation: The indicator calculates a normalized value via the function Relative Price = / log(UpperBound) − log(LowerBound) . The result is a value between 0 and 1, where 0 corresponds to the lower bound and 1 corresponds to the upper bound on a log scale.
VISUALIZATION
The indicator plots three series:
Risk Metric - a plot of the risk metric value that’s computed from an asset's relative price so that it lies within a logarithmic range between 0.0 & 1.0.
Smoothed Risk Metric - a plot of the risk metric that’s been smoothed.
Entry/Exit - a scatter plot for identified entry and exit. Values are expressed as percent and are coded as red being exit and green being entity. E.g., a red dot at 0.02 implies exit 2% of the held asset. A green dot at 0.01 implies use 1% of a designated capital reserve.
USAGE
Risk Metric
The risk metric transformation function has several parameters. These control aspects such as decay, sensitivity, bounds and time offset.
Decay - Acts as an exponent multiplier and controls how quickly dynamic bounds change as a function of the bar_index.
Time Offset - provides a centering effect of the exponential transformation relative to the current bar_index.
Sensitivity - controls how sensitive to time the dynamic bound adjustments should be.
Baseline control - Serves as an additive offset for dynamic bounds computation which ensures that bounds never become too small or negative.
UpperBound - provides headroom to accomodate growth an assets price from the baseline. For example, an upperbound of 3.5 accommodates a 3.5x growth from the baseline value (e.g., $100 -> $350).
LowerBound - provides log scale compression such that the overall metric provides meaningful insights for prices well below the average whilst avoiding extreme scaling. A lowerbound of 0.25 corresponds to a price that is approx one quarter of a normalised baseline in a log context.
Weighted Entry/Exit
This feature provides a weighted system for identifying DCA entry and exit. This weighting mechanism adjusts the metric's interpretation to highlight conditions based on dynamic thresholds and user-defined parameters to identify high-probability zones for entry/exit actions and provide risk-adjusted insights.
Weighting Parameters
The weighting function supports fine-tuning of the computed weighted entry/exit values
Base: determines the foundational multiplier for weighting the entry/exit value. A higher base amplifies the weighting effect, making the weighted values more pronounced. It acts as a scaling factor to control the overall magnitude of the weighting.
Exponent: adjusts the curve of the weighting function. Higher exponent values increase sensitivity, emphasizing differences between risk metric values near the entry or exit thresholds. This creates a steeper gradient for the computed entry/exit value making it more responsive to subtle shifts in risk levels.
Cut Off: specifies the maximum percentage (expressed as a fraction of 1.0) that the weighted entry/exit value can reach. This cap ensures the metric remains within a meaningful range and avoids skewing
Exit condition: Defines a threshold for exit. When the risk metric is below the exit threshold (but above the entry threshold) then entry/exit is neutral.
Entry condition: Defines a threshold for entry. When the risk metric is above the entry threshold (but below the exit threshold) then entry/exit is neutral.
Weighting Behaviour
For entry conditions - value is more heavily weighted as the metric approaches the entry threshold, emphasizing lower risk levels.
For exit conditions - value is more heavily weighted as the metric nears the exit threshold, emphasizing increased risk levels.
USE-CASES
Identifying potential overbought or oversold conditions within the specified logarithmic range.
Assisting in assessing how the current price compares to historical price levels on a logarithmic scale.
Guiding decision-making processes by providing insights into the relative positioning of prices within a log context
CONSIDERATIONS
Validation: It's recommended that backtesting over historical data be done before acting on any identified entry/exit values.
User Discretion: This indicator focus on price risk. Consider other risk factors and general market conditions as well.
Indicator

Sharpe and Sortino Ratios█ OVERVIEW
This indicator calculates the Sharpe and Sortino ratios using a chart symbol's periodic price returns, offering insights into the symbol's risk-adjusted performance. It features the option to calculate these ratios by comparing the periodic returns to a fixed annual rate of return or the returns from another selected symbol's context.
█ CONCEPTS
Returns, risk, and volatility
The return on an investment is the relative gain or loss over a period, often expressed as a percentage. Investment returns can originate from several sources, including capital gains, dividends, and interest income. Many investors seek the highest returns possible in the quest for profit. However, prudent investing and trading entails evaluating such returns against the associated risks (i.e., the uncertainty of returns and the potential for financial losses) for a clearer perspective on overall performance and sustainability.
The profitability of an investment typically comes at the cost of enduring market swings, noise, and general uncertainty. To navigate these turbulent waters, investors and portfolio managers often utilize volatility , a measure of the statistical dispersion of historical returns, as a foundational element in their risk assessments because it provides a tangible way to gauge the uncertainty in returns. High volatility suggests increased uncertainty and, consequently, higher risk, whereas low volatility suggests more stable returns with minimal fluctuations, implying lower risk. These concepts are integral components in several risk-adjusted performance metrics, including the Sharpe and Sortino ratios calculated by this indicator.
Risk-free rate
The risk-free rate represents the rate of return on a hypothetical investment carrying no risk of financial loss. This theoretical rate provides a benchmark for comparing the returns on a risky investment and evaluating whether its excess returns justify the risks. If an investment's returns are at or below the theoretical risk-free rate or the risk premium is below a desired amount, it may suggest that the returns do not compensate for the extra risk, which might be a call to reassess the investment.
Since the risk-free rate is a theoretical concept, investors often utilize proxies for the rate in practice, such as Treasury bills and other government bonds. Conventionally, analysts consider such instruments "risk-free" for a domestic holder, as they are a form of government obligation with a low perceived likelihood of default.
The average yield on short-term Treasury bills, influenced by economic conditions, monetary policies, and inflation expectations, has historically hovered around 2-3% over the long term. This range also aligns with central banks' inflation targets. As such, one may interpret a value within this range as a minimum proxy for the risk-free rate, as it may correspond to the minimum rate required to maintain purchasing power over time. This indicator uses a default value of 2% as the risk-free rate in its Sharpe and Sortino ratio calculations. Users can adjust this value from the "Risk-free rate of return" input in the "Settings/Inputs" tab.
Sharpe and Sortino ratios
The Sharpe and Sortino ratios are two of the most widely used metrics that offer insight into an investment's risk-adjusted performance . They provide a standardized framework to compare the effectiveness of investments relative to their perceived risks. These metrics can help investors determine whether the returns justify the risks taken to achieve them, promoting more informed investment decisions.
Both metrics measure risk-adjusted performance similarly. However, they have some differences in their formulas and their interpretation:
1. Sharpe ratio
The Sharpe ratio , developed by Nobel laureate William F. Sharpe, measures the performance of an investment compared to a theoretically risk-free asset, adjusted for the investment risk. The ratio uses the following formula:
Sharpe Ratio = (𝑅𝑎 − 𝑅𝑓) / 𝜎𝑎
Where:
• 𝑅𝑎 = Average return of the investment
• 𝑅𝑓 = Theoretical risk-free rate of return
• 𝜎𝑎 = Standard deviation of the investment's returns (volatility)
A higher Sharpe ratio indicates a more favorable risk-adjusted return, as it signifies that the investment produced higher excess returns per unit of increase in total perceived risk.
2. Sortino ratio
The Sortino ratio is a modified form of the Sharpe ratio that only considers downside volatility , i.e., the volatility of returns below the theoretical risk-free benchmark. Although it shares close similarities with the Sharpe ratio, it can produce very different values, especially when the returns do not have a symmetrical distribution, since it does not penalize upside and downside volatility equally. The ratio uses the following formula:
Sortino Ratio = (𝑅𝑎 − 𝑅𝑓) / 𝜎𝑑
Where:
• 𝑅𝑎 = Average return of the investment
• 𝑅𝑓 = Theoretical risk-free rate of return
• 𝜎𝑑 = Downside deviation (standard deviation of negative excess returns, or downside volatility)
The Sortino ratio offers an alternative perspective on an investment's return-generating efficiency since it does not consider upside volatility in its calculation. A higher Sortino ratio signifies that the investment produced higher excess returns per unit of increase in perceived downside risk.
The risk-free rate (𝑅𝑓) in the numerator of both ratio formulas acts as a baseline for comparing an investment's performance to a theoretical risk-free alternative. By subtracting the risk-free rate from the expected return (𝑅𝑎−𝑅𝑓), the numerator essentially represents the risk premium of the investment.
Comparison with another symbol
In addition to the conventional Sharpe and Sortino ratios, which compare an instrument's returns to a risk-free rate, this indicator can also compare returns to a user-specified benchmark symbol , allowing the calculation of Information ratios .
An Information ratio is a generalized form of the Sharpe ratio that compares an investment's returns to a risky benchmark , such as SPY, rather than a risk-free rate. It measures the investment's active return (the difference between its returns and the benchmark returns) relative to its tracking error (i.e., the volatility of the active return) using the following formula:
𝐼𝑅 = (𝑅𝑝 − 𝑅𝑏) / 𝑇𝐸
Where:
• 𝑅𝑝 = Average return on the portfolio or investment
• 𝑅𝑏 = Average return from the benchmark instrument
• 𝑇𝐸 = Tracking error (volatility of 𝑅𝑝 − 𝑅𝑏)
Comparing returns to a benchmark instrument rather than a theoretical risk-free rate offers unique insights into risk-adjusted performance. Higher Information ratios signify that the investment produced higher active returns per unit of increase in risk relative to the benchmark. Conventional choices for non-risk-free benchmarks include major composite indices like the S&P 500 and DJIA, as the resulting ratios can provide insight into the effectiveness of an investment relative to the broader market.
Users can enable this generalized calculation for both the Sharpe and Sortino ratios by selecting the "Benchmark symbol returns" option from the "Benchmark type" dropdown in the "Settings/Inputs" tab.
It's crucial to note that this indicator compares the charts symbol's rate of change (return) to the rate of change in the benchmark symbol. Consequently, not all symbols available on PulseWire are suitable for use with these ratios due to the nature of what their values represent. For instance, using a bond as a benchmark will produce distorted results since each bar's values represent yields rather than prices, meaning it compares the rate of change in the yield. To maintain consistency and relevance in the calculated ratios, ensure the values from the compared symbols strictly represent price information.
█ FEATURES
This indicator provides traders with two widely used metrics for assessing risk-adjusted performance, generalized to allow users to compare the chart symbol's price returns to a fixed risk-free rate or the returns from another risky symbol. Below are the key features of this indicator:
Timeframe selection
The "Returns timeframe" input determines the timeframe of the calculated price returns. Users can select any value greater than or equal to the chart's timeframe. The default timeframe is "1M".
Periodic returns tracking
This indicator compounds and collects requested price returns from the selected timeframe over monthly or daily periods, similar to how the Broker Emulator works when calculating strategy performance metrics on trade data. It employs the following logic:
• Track returns over monthly periods if the chart's data spans at least two months.
• Track returns over daily periods if the chart's data spans at least two days but not two months.
• Do not track or collect returns if the data spans less than two days, as the amount of data is insufficient for meaningful ratio calculations.
The indicator uses the returns collected from up to a specified number of periods to calculate the Sharpe and Sortino ratios, depending on the available historical data. It also uses these periodic returns to calculate the average returns it displays in the Data Window.
Users can control the maximum number of periods the indicator analyzes with the "Max no. of periods used" input in the "Settings/Inputs" tab. The default value is 60 periods.
Benchmark specification
The "Benchmark return type" input specifies the benchmark type the indicator compares to the chart symbol's returns in the ratio calculations. It features the following two options:
• "Risk-free rate of return (%)": Compares the price returns to a user-specified annual rate of return representing a theoretical risk-free rate (e.g., 2%).
• "Benchmark symbol return": Compares the price returns to a selected benchmark symbol (e.g., "AMEX:SPY) to calculate Information ratios.
When comparing a chart symbol's returns to a specified benchmark symbol, this indicator aligns the times of data points from the benchmark with the times of data points from the chart's symbol to facilitate a fair comparison between symbols with different active sessions.
Visualization and display
• The indicator displays the periodic returns requested from the specified "Returns timeframe" in a separate pane. The plot includes dynamic colors to signify positive and negative returns.
• When the "Returns timeframe" value represents a higher timeframe, the indicator displays background highlights on the main chart pane to signify when a new value is available and whether the return is positive or negative.
• When the specified benchmark return type is a benchmark symbol, the indicator displays the requested symbol's returns in the separate pane as a gray line for visual comparison.
• Within the separate pane, the indicator displays a single-cell table that shows the base period it uses for periodic returns, the number of periods it uses in the calculation, the timeframe of the requested data, and the calculated Sharpe and Sortino ratios.
• The Data Window displays the chart symbol and benchmark returns, their periodic averages, and the Sharpe and Sortino ratios.
█ FOR Pine Script™ CODERS
• This script utilizes the functions from our RiskMetrics library to determine the size of the periods, calculate and collect periodic returns, and compute the Sharpe and Sortino ratios.
• The `getAlignedPrices()` function in this script requests price data for the chart's symbol and a benchmark symbol with consistent time alignment by utilizing spread symbols , which helps facilitate a fair comparison between different symbol types. Retrieving prices from spreads avoids potential information loss and data misalignment that can otherwise occur when using separate requests from each symbol's context when those symbols have different sessions or data times.
• For consistency, the `getAlignedPrices()` function includes extended hours and dividend adjustment modifiers in its data requests. Additionally, it includes other settings inherited from the chart's context, such as "settlement-as-close" preferences for fair comparison between futures instruments.
• This script uses the `changePercent()` function from our ta library to calculate the percentage changes of the requested data.
• The newly released `force_overlay` parameter in display-related functions allows indicators to display visuals on the main chart and a separate pane simultaneously. We use the parameter in this script's bgcolor() call to display background highlights on the main chart.
Look first. Then leap.
Indicator

RiskMetrics█ OVERVIEW
This library is a tool for Pine programmers that provides functions for calculating risk-adjusted performance metrics on periodic price returns. The calculations used by this library's functions closely mirror those the Broker Emulator uses to calculate strategy performance metrics (e.g., Sharpe and Sortino ratios) without depending on strategy-specific functionality.
█ CONCEPTS
Returns, risk, and volatility
The return on an investment is the relative gain or loss over a period, often expressed as a percentage. Investment returns can originate from several sources, including capital gains, dividends, and interest income. Many investors seek the highest returns possible in the quest for profit. However, prudent investing and trading entails evaluating such returns against the associated risks (i.e., the uncertainty of returns and the potential for financial losses) for a clearer perspective on overall performance and sustainability.
One way investors and analysts assess the risk of an investment is by analyzing its volatility , i.e., the statistical dispersion of historical returns. Investors often use volatility in risk estimation because it provides a quantifiable way to gauge the expected extent of fluctuation in returns. Elevated volatility implies heightened uncertainty in the market, which suggests higher expected risk. Conversely, low volatility implies relatively stable returns with relatively minimal fluctuations, thus suggesting lower expected risk. Several risk-adjusted performance metrics utilize volatility in their calculations for this reason.
Risk-free rate
The risk-free rate represents the rate of return on a hypothetical investment carrying no risk of financial loss. This theoretical rate provides a benchmark for comparing the returns on a risky investment and evaluating whether its excess returns justify the risks. If an investment's returns are at or below the theoretical risk-free rate or the risk premium is below a desired amount, it may suggest that the returns do not compensate for the extra risk, which might be a call to reassess the investment.
Since the risk-free rate is a theoretical concept, investors often utilize proxies for the rate in practice, such as Treasury bills and other government bonds. Conventionally, analysts consider such instruments "risk-free" for a domestic holder, as they are a form of government obligation with a low perceived likelihood of default.
The average yield on short-term Treasury bills, influenced by economic conditions, monetary policies, and inflation expectations, has historically hovered around 2-3% over the long term. This range also aligns with central banks' inflation targets. As such, one may interpret a value within this range as a minimum proxy for the risk-free rate, as it may correspond to the minimum rate required to maintain purchasing power over time.
The built-in Sharpe and Sortino ratios that strategies calculate and display in the Performance Summary tab use a default risk-free rate of 2%, and the metrics in this library's example code use the same default rate. Users can adjust this value to fit their analysis needs.
Risk-adjusted performance
Risk-adjusted performance metrics gauge the effectiveness of an investment by considering its returns relative to the perceived risk. They aim to provide a more well-rounded picture of performance by factoring in the level of risk taken to achieve returns. Investors can utilize such metrics to help determine whether the returns from an investment justify the risks and make informed decisions.
The two most commonly used risk-adjusted performance metrics are the Sharpe ratio and the Sortino ratio.
1. Sharpe ratio
The Sharpe ratio , developed by Nobel laureate William F. Sharpe, measures the performance of an investment compared to a theoretically risk-free asset, adjusted for the investment risk. The ratio uses the following formula:
Sharpe Ratio = (𝑅𝑎 − 𝑅𝑓) / 𝜎𝑎
Where:
• 𝑅𝑎 = Average return of the investment
• 𝑅𝑓 = Theoretical risk-free rate of return
• 𝜎𝑎 = Standard deviation of the investment's returns (volatility)
A higher Sharpe ratio indicates a more favorable risk-adjusted return, as it signifies that the investment produced higher excess returns per unit of increase in total perceived risk.
2. Sortino ratio
The Sortino ratio is a modified form of the Sharpe ratio that only considers downside volatility , i.e., the volatility of returns below the theoretical risk-free benchmark. Although it shares close similarities with the Sharpe ratio, it can produce very different values, especially when the returns do not have a symmetrical distribution, since it does not penalize upside and downside volatility equally. The ratio uses the following formula:
Sortino Ratio = (𝑅𝑎 − 𝑅𝑓) / 𝜎𝑑
Where:
• 𝑅𝑎 = Average return of the investment
• 𝑅𝑓 = Theoretical risk-free rate of return
• 𝜎𝑑 = Downside deviation (standard deviation of negative excess returns, or downside volatility)
The Sortino ratio offers an alternative perspective on an investment's return-generating efficiency since it does not consider upside volatility in its calculation. A higher Sortino ratio signifies that the investment produced higher excess returns per unit of increase in perceived downside risk.
█ CALCULATIONS
Return period detection
Calculating risk-adjusted performance metrics requires collecting returns across several periods of a given size. Analysts may use different period sizes based on the context and their preferences. However, two widely used standards are monthly or daily periods, depending on the available data and the investment's duration. The built-in ratios displayed in the Strategy Tester utilize returns from either monthly or daily periods in their calculations based on the following logic:
• Use monthly returns if the history of closed trades spans at least two months.
• Use daily returns if the trades span at least two days but less than two months.
• Do not calculate the ratios if the trade data spans fewer than two days.
This library's `detectPeriod()` function applies related logic to available chart data rather than trade data to determine which period is appropriate:
• It returns true if the chart's data spans at least two months, indicating that it's sufficient to use monthly periods.
• It returns false if the chart's data spans at least two days but not two months, suggesting the use of daily periods.
• It returns na if the length of the chart's data covers less than two days, signifying that the data is insufficient for meaningful ratio calculations.
It's important to note that programmers should only call `detectPeriod()` from a script's global scope or within the outermost scope of a function called from the global scope, as it requires the time value from the first bar to accurately measure the amount of time covered by the chart's data.
Collecting periodic returns
This library's `getPeriodicReturns()` function tracks price return data within monthly or daily periods and stores the periodic values in an array . It uses a `detectPeriod()` call as the condition to determine whether each element in the array represents the return over a monthly or daily period.
The `getPeriodicReturns()` function has two overloads. The first overload requires two arguments and outputs an array of monthly or daily returns for use in the `sharpe()` and `sortino()` methods. To calculate these returns:
1. The `percentChange` argument should be a series that represents percentage gains or losses. The values can be bar-to-bar return percentages on the chart timeframe or percentages requested from a higher timeframe.
2. The function compounds all non-na `percentChange` values within each monthly or daily period to calculate the period's total return percentage. When the `percentChange` represents returns from a higher timeframe, ensure the requested data includes gaps to avoid compounding redundant values.
3. After a period ends, the function queues the compounded return into the array , removing the oldest element from the array when its size exceeds the `maxPeriods` argument.
The resulting array represents the sequence of closed returns over up to `maxPeriods` months or days, depending on the available data.
The second overload of the function includes an additional `benchmark` parameter. Unlike the first overload, this version tracks and collects differences between the `percentChange` and the specified `benchmark` values. The resulting array represents the sequence of excess returns over up to `maxPeriods` months or days. Passing this array to the `sharpe()` and `sortino()` methods calculates generalized Information ratios , which represent the risk-adjustment performance of a sequence of returns compared to a risky benchmark instead of a risk-free rate. For consistency, ensure the non-na times of the `benchmark` values align with the times of the `percentChange` values.
Ratio methods
This library's `sharpe()` and `sortino()` methods respectively calculate the Sharpe and Sortino ratios based on an array of returns compared to a specified annual benchmark. Both methods adjust the annual benchmark based on the number of periods per year to suit the frequency of the returns:
• If the method call does not include a `periodsPerYear` argument, it uses `detectPeriod()` to determine whether the returns represent monthly or daily values based on the chart's history. If monthly, the method divides the `annualBenchmark` value by 12. If daily, it divides the value by 365.
• If the method call does specify a `periodsPerYear` argument, the argument's value supersedes the automatic calculation, facilitating custom benchmark adjustments, such as dividing by 252 when analyzing collected daily stock returns.
When the array passed to these methods represents a sequence of excess returns , such as the result from the second overload of `getPeriodicReturns()`, use an `annualBenchmark` value of 0 to avoid comparing those excess returns to a separate rate.
By default, these methods only calculate the ratios on the last available bar to minimize their resource usage. Users can override this behavior with the `forceCalc` parameter. When the value is true , the method calculates the ratio on each call if sufficient data is available, regardless of the bar index.
Look first. Then leap.
█ FUNCTIONS & METHODS
This library contains the following functions:
detectPeriod()
Determines whether the chart data has sufficient coverage to use monthly or daily returns
for risk metric calculations.
Returns: (bool) `true` if the period spans more than two months, `false` if it otherwise spans more
than two days, and `na` if the data is insufficient.
getPeriodicReturns(percentChange, maxPeriods)
(Overload 1 of 2) Tracks periodic return percentages and queues them into an array for ratio
calculations. The span of the chart's historical data determines whether the function uses
daily or monthly periods in its calculations. If the chart spans more than two months,
it uses "1M" periods. Otherwise, if the chart spans more than two days, it uses "1D"
periods. If the chart covers less than two days, it does not store changes.
Parameters:
percentChange (float) : (series float) The change percentage. The function compounds non-na values from each
chart bar within monthly or daily periods to calculate the periodic changes.
maxPeriods (simple int) : (simple int) The maximum number of periodic returns to store in the returned array.
Returns: (array) An array containing the overall percentage changes for each period, limited
to the maximum specified by `maxPeriods`.
getPeriodicReturns(percentChange, benchmark, maxPeriods)
(Overload 2 of 2) Tracks periodic excess return percentages and queues the values into an
array. The span of the chart's historical data determines whether the function uses
daily or monthly periods in its calculations. If the chart spans more than two months,
it uses "1M" periods. Otherwise, if the chart spans more than two days, it uses "1D"
periods. If the chart covers less than two days, it does not store changes.
Parameters:
percentChange (float) : (series float) The change percentage. The function compounds non-na values from each
chart bar within monthly or daily periods to calculate the periodic changes.
benchmark (float) : (series float) The benchmark percentage to compare against `percentChange` values.
The function compounds non-na values from each bar within monthly or
daily periods and subtracts the results from the compounded `percentChange` values to
calculate the excess returns. For consistency, ensure this series has a similar history
length to the `percentChange` with aligned non-na value times.
maxPeriods (simple int) : (simple int) The maximum number of periodic excess returns to store in the returned array.
Returns: (array) An array containing monthly or daily excess returns, limited
to the maximum specified by `maxPeriods`.
method sharpeRatio(returnsArray, annualBenchmark, forceCalc, periodsPerYear)
Calculates the Sharpe ratio for an array of periodic returns.
Callable as a method or a function.
Namespace types: array
Parameters:
returnsArray (array) : (array) An array of periodic return percentages, e.g., returns over monthly or
daily periods.
annualBenchmark (float) : (series float) The annual rate of return to compare against `returnsArray` values. When
`periodsPerYear` is `na`, the function divides this value by 12 to calculate a
monthly benchmark if the chart's data spans at least two months or 365 for a daily
benchmark if the data otherwise spans at least two days. If `periodsPerYear`
has a specified value, the function divides the rate by that value instead.
forceCalc (bool) : (series bool) If `true`, calculates the ratio on every call. Otherwise, ratio calculation
only occurs on the last available bar. Optional. The default is `false`.
periodsPerYear (simple int) : (simple int) If specified, divides the annual rate by this value instead of the value
determined by the time span of the chart's data.
Returns: (float) The Sharpe ratio, which estimates the excess return per unit of total volatility.
method sortinoRatio(returnsArray, annualBenchmark, forceCalc, periodsPerYear)
Calculates the Sortino ratio for an array of periodic returns.
Callable as a method or a function.
Namespace types: array
Parameters:
returnsArray (array) : (array) An array of periodic return percentages, e.g., returns over monthly or
daily periods.
annualBenchmark (float) : (series float) The annual rate of return to compare against `returnsArray` values. When
`periodsPerYear` is `na`, the function divides this value by 12 to calculate a
monthly benchmark if the chart's data spans at least two months or 365 for a daily
benchmark if the data otherwise spans at least two days. If `periodsPerYear`
has a specified value, the function divides the rate by that value instead.
forceCalc (bool) : (series bool) If `true`, calculates the ratio on every call. Otherwise, ratio calculation
only occurs on the last available bar. Optional. The default is `false`.
periodsPerYear (simple int) : (simple int) If specified, divides the annual rate by this value instead of the value
determined by the time span of the chart's data.
Returns: (float) The Sortino ratio, which estimates the excess return per unit of downside
volatility. Library
