Library · Pine Script v5 · Library

MathFinancialAbsoluteRiskMeasures

by ricardosantos79· code credited to RicardoSantos

This Pine Script v5 library exports absolute risk statistics for a float sample.

View on GitHub

GitHub stars261on the repository
Pine versionv5runs as is
Lines of code151
Settings0inputs
LicenceNone statedfile: MPL-2.0
Last update4 years ago13 Nov 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

151 lines of Pine Script v5 from beta/libs/Math/MathFinancialAbsoluteRiskMeasures.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

MathFinancialAbsoluteRiskMeasures.pinescript
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RicardoSantos

//@version=5

// @description Financial Absolute Risk Measures.
library(title='MathFinancialAbsoluteRiskMeasures')

// reference:
//      https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Financial/AbsoluteRiskMeasures.cs

// Note: The following statistics would be considered an absolute risk statistic in the finance realm as well.
//      Standard Deviation
//      Annualized Standard Deviation = Math.Sqrt(Monthly Standard Deviation x ( 12 ))
//      Skewness
//      Kurtosis

// @function Standard deviation of gains in a data sample.
// @param sample float array, data sample.
// @returns float.
export gain_stdev (float[] sample) => //{
    int _size = array.size(sample)
    if _size > 0
        float[] _G = array.new_float()
        for _i = 0 to _size-1
            float _xi = array.get(sample, _i)
            if _xi >= 0.0
                array.push(_G, _xi)
        array.stdev(_G)
//{ usage:
// plot(gain_stdev(array.from(250.0, -35, 100, 50, -120, 200)))
//{ notes:
// Calculation is similar to Standard Deviation , except it calculates an average (mean) return only for periods with a gain
// and measures the variation of only the gain periods around the gain mean. Measures the volatility of upside performance.
// © Copyright 1996, 1999 Gary L.Gastineau. First Edition. © 1992 Swiss Bank Corporation.
//}}}

// @function Standard deviation of losses in a data sample.
// @param sample float array, data sample.
// @returns float.
export loss_stdev(float[] sample) => //{
    int _size = array.size(sample)
    if _size > 0
        float[] _L = array.new_float()
        for _i = 0 to _size-1
            float _xi = array.get(sample, _i)
            if _xi < 0.0
                array.push(_L, _xi)
        array.stdev(_L)
//{ usage:
// plot(loss_stdev(array.from(250.0, -35, 100, 50, -120, 200)))
//{ notes:
// Similar to standard deviation, except this statistic calculates an average (mean) return for only the periods with a loss and then
// measures the variation of only the losing periods around this loss mean. This statistic measures the volatility of downside performance.
// http://www.offshore-library.com/kb/statistics.php
//}}}

// @function Downside standard deviation in a data sample.
// @param sample float array, data sample.
// @param minimal_acceptable_return float, minimum gain value.
// @returns float.
export downside_stdev (float[] sample, float minimal_acceptable_return=0.0) => //{
    int _size = array.size(sample)
    if _size > 0
        float[] _D = array.new_float()
        for _i = 0 to _size-1
            float _xi = array.get(sample, _i)
            if _xi < minimal_acceptable_return
                array.push(_D, _xi)
        array.stdev(_D)
//{ usage:
// plot(downside_stdev(array.from(250.0, -35, 100, 50, -120, 200), 100.0))
//{ notes:
// This measure is similar to the loss standard deviation except the downside deviation
// considers only returns that fall below a defined minimum acceptable return (MAR) rather than the arithmetic mean.
// For example, if the MAR is 7%, the downside deviation would measure the variation of each period that falls below
// 7%. (The loss standard deviation, on the other hand, would take only losing periods, calculate an average return for
// the losing periods, and then measure the variation between each losing return and the losing return average).
//}}}

// @function Standard deviation of less than average returns in a data sample.
// @param sample float array, data sample.
// @returns float.
export semi_stdev (float[] sample) => //{
    int _size = array.size(sample)
    if _size > 0
        float[] _S = array.new_float()
        float _mean = array.avg(sample)
        for _i = 0 to _size-1
            float _xi = array.get(sample, _i)
            if _xi < _mean
                array.push(_S, _xi)
        array.stdev(_S)
//{ usage:
// plot(semi_stdev(array.from(250.0, -35, 100, 50, -120, 200)))
//{ notes:
// A measure of volatility in returns below the mean. It's similar to standard deviation, but it only
// looks at periods where the investment return was less than average return.
//}}}

// @function ratio of average gains of average losses in a data sample.
// @param sample float array, data sample.
// @returns float.
export gain_loss_ratio (float[] sample) => //{
    int _size = array.size(sample)
    if _size > 0
        float[] _G = array.new_float()
        float[] _L = array.new_float()
        for _i = 0 to _size-1
            float _xi = array.get(sample, _i)
            if _xi >= 0
                array.push(_G, _xi)
            else
                array.push(_L, _xi)
        math.abs(array.stdev(_G) / array.stdev(_L))
//{ usage:
// plot(gain_loss_ratio(array.from(250.0, -35, 100, 50, -120, 200)))
//{ notes:
// Measures a fund’s average gain in a gain period divided by the fund’s average loss in a losing
// period. Periods can be monthly or quarterly depending on the data frequency.
//}}}

// @function Compound Risk Score
// @param source float, input data, default=close.
// @param length int, period of observation, default=12)
// @returns float.
export compound_risk_score (float source=close, int length=12) => //{
    float _total = 0.0
    float _absolute = 0.0
    if length < 1
        error('MathFinancialAbsoluteMeasures -> compound_risk_score(): "length" must be positive > 0.')
        float(na)
    else
        for _i = 1 to length
            float _diff = source[0] - source[_i]
            _total += _diff
            _absolute += math.abs(_diff)
        (_total / _absolute) * 100
//{ usage:
// int length = input.int(100), int avg_length = input.int(25)
// float cr = compound_risk_score(close, length)
// float ma = math.avg(ta.sma(cr, avg_length), 50.0)
// plot(series=cr, color=color.new(color.red, 0))
// plot(series=ma, color=color.new(color.teal, 0))
// hline(100), hline(50), hline(0), hline(-50), hline(-100)
//{ remarks:
//  if you took a trade for every bars close for the duration of the length
//  how would those trades fair atm?
//  values closer to (100 | -100) are better for its (bull | bear), closer to 0 will be closer to break eaven.
//  this indicator is optimal for trending markets.
//}}}

Overview

MathFinancialAbsoluteRiskMeasures calculates the standard deviation of positive observations, the standard deviation of negative observations, and downside deviation of values below a caller-supplied minimum acceptable return. Each function builds a filtered array and uses the built-in standard-deviation routine. The library plots nothing and has no inputs; callers supply the sample and, for downside deviation, the threshold. It does not generate trading signals or manage positions.

Details

Published by

ricardosantos79 on GitHub

Code credit

RicardoSantos, as written in the script's header

Type

Library, Pine Script v5

Draws

Library (no plots)

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

KernelFunctions

by artificial-intelligence-edge
75 stars

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation. It calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating be

Library v5
Updated 2 days ago · MIT GitHub repository of KernelFunctions

Ta

by nersent
29 stars

This Pine Script v5 library exports thin wrappers around built-in technical analysis functions. It covers moving averages, momentum measures such as RSI and CCI, volatility tools including ATR and standard deviation, range extremes, cross detection, and runnin

Library v5
Updated 11 months ago · Custom licence GitHub repository of Ta

Bands

by heyphat
26 stars

This library exports a Band type and functions that build a simple-moving-average basis with upper and lower envelopes from standard deviation. It classifies a source as above, below, or inside those envelopes, measures band width, and scales an imported z-sco

Library v6 Volatility & bandsMoving averages
Updated 2 months ago · AGPL-3.0 GitHub repository of Bands

Mylib

by ferranbt
21 stars

This script serves as a minimal utility library written in Pine Script v6. It provides an exported helper function that calculates the sum of two numeric arguments. As a reusable code library, it produces no visual plots, charts, or trading signals, and it con

Library v6
Updated 7 weeks ago · MPL-2.0 GitHub repository of Mylib

HLevel

by stupenkov
14 stars

HLevel is a Pine Script v5 utility library designed to manage horizontal price levels for cryptocurrency charts. It defines custom types for pivots and levels, along with methods to initialize, add, track, and expire price levels based on pivot high and pivot

Library v5
Updated 3 years ago · None stated GitHub repository of HLevel

Zignaly2Beta

by ruckard
13 stars

This library provides helper functions to format and build JSON webhook alert payloads for the Zignaly automated trading platform. It constructs formatted messages containing parameters such as trading pair, exchange, account type, leverage, margin mode, hedge

Library v5
Updated 1 year ago · None stated GitHub repository of Zignaly2Beta

More libraries

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers