Volatility

MarioMohr · library · 125 行 · 点赞 0 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MarioMohr
 
//@version=6
// @description Some practical measures of volatility that can be easily used to satisfy the need to show expanding and contracting volatility but are not tied to an underlying price level. The code I translated of the book "Trading Systems and Methods."
library('Volatility')
 
// @function This function calculates the difference between price now and close price of the candle 'n' bars before that. If prices are very volatile but closed where they began, then this method would show zero volatility. Over many calculations, this method returns a reasonable measure of volatility, but will always be lower than those using the highs and lows.
// @param length The length is needed to determine how many candles/bars back should take into account.
// @returns float
export change_in_price(int length = 14) =>
    close - close[length]
 
// @function This function measures volatility over most recent candles, which could be used as an estimate of risk. It may also be effective as the basis for a stop-loss or take-profit, like the ATR but it ignores the frequency of directional changes within the time interval. In other words: The difference between the highest high and lowest low over 'n' bars.
// @param length The length is needed to determine how many candles/bars back should take into account.
// @returns float
export maximum_price_fluctuation(int length = 14) =>
    float highest_high = ta.highest(source = high, length = length)
    float lowest_low = ta.lowest(source = low, length = length)
    highest_high - lowest_low
 
// @function This function measures volatility over most recent close prices. This is excellent for comparing volatility. It includes both frequency and magnitude. In other words: Sum of differences between second to last close price and last close price as absolute value for 'n' bars.
// @param length The length is needed to determine how many candles/bars back should take into account.
// @returns float
export absolute_price_change(int length = 14) =>
    math.sum(math.abs(close[2] - close[1]), length - 1)
 
// @function This function measures volatility over most recent close prices. Its the standard deviation of close over the past 'n' periods, times the square root of the number of periods in a year.
// @param length The length is needed to determine how many candles/bars back should take into account. Optional. Default value is 14, and minimum value is 2.
// @returns float
export annualized(int length = 14) =>
    int trading_days = syminfo.type == 'crypto' or syminfo.type == 'futures' ? 365 : 252
    float resolution = 86400 * trading_days / timeframe.in_seconds()
    ta.stdev(math.log(close / close[1]), math.max(length, 2)) * math.sqrt(resolution) * 100
 
// @function This function measures volatility over most recent percentage values, and it is the same calculation as 'annualized()', except it uses an external source to get the same result. Its the standard deviation of rate of change (ROC) over the past 'n' periods, times the square root of the number of periods in a year.
// @param roc Rate of change ('ta.roc(close, 1)') to calculate annualized volatiltiy.
// @param length The length is needed to determine how many candles/bars back should take into account. Optional. Default value is 14, and minimum value is 2.
// @param syminfo_type The type of symbol. Optional. Default is 'syminfo.type'.
// @returns float
export annualized_returns(float roc, int length = 14, simple string syminfo_type = syminfo.type) =>
    int trading_days = syminfo_type == 'crypto' or syminfo_type == 'futures' ? 365 : 252
    float resolution = 86400 * trading_days / timeframe.in_seconds()
    ta.stdev(roc, math.max(length, 2)) * math.sqrt(resolution)
 
// @function Calculates the historical volatility and the current volatility, both as bars/volume. This funtion works for Intraday use only!
// @param look_days_back Number of days to include in the historical data.
// @param is_cumulative If 'true', the cumulative volatility is calculated (ascended wedge pattern).
// @returns tuple [float average, float current]
export bars(int look_days_back = 14, bool is_cumulative = true) =>
 
    if timeframe.in_seconds() >= 86400
        runtime.error("The time interval needs to be below one day.")
 
    var int bars_count = 0
    var int bars_max   = last_bar_index
    int bars_per_day   = math.ceil(86400 / timeframe.in_seconds())
    int columns_max    = math.floor(bars_max / bars_per_day)
    int days           = columns_max > look_days_back ? look_days_back : columns_max
    
    var matrix<float> matrix_bars = matrix.new<float>(bars_per_day, days)
    var float current_volatility  = 0.0
 
    if session.isfirstbar
        bars_count         := 0
        current_volatility := high - low
        matrix_bars.remove_col()
        matrix_bars.add_col(0)
    else
        if not is_cumulative
            current_volatility := 0.0
        current_volatility += ta.tr
        bars_count         += 1
 
    matrix_bars.set(bars_count, 0, current_volatility)
 
    [matrix_bars.row(bars_count).avg(), current_volatility]
 
// @function This function is the ATR on a fixed 10 days length. It could be used as TP, or a fraction of it for SL.
// @returns float
export absolute_daily_range() =>
    float atr2 = na
    if timeframe.in_seconds(timeframe.period) > 86400
        float[] atr_array = request.security_lower_tf(syminfo.tickerid, "1D", ta.atr(10))
        atr2 := atr_array.last()
    else
        atr2 := request.security(syminfo.tickerid, "1D", ta.atr(10)[1], lookahead = barmerge.lookahead_on)
    atr2
 
 
// =====
// INPUT
// =====
 
var int ann_length   = input.int(14, "Length", 1, group = "Annualized (Price)", display = display.none)
//var int anr_length   = input.int(14, "Length", 1, group = "Annualized (Returns)", display = display.none)
//var int roc_length   = input.int(1, "ROC Length", 1, tooltip = "ROC = Rate of Change (%)", group = "Annualized (Returns)", display = display.none)
//var float roc_source = input.source(close, "ROC Source", tooltip = "ROC = Rate of Change (%)", group = "Annualized (Returns)", display = display.none)
var int apc_length   = input.int(14, "Length", 1, group = "APC (Absolute Price Change)", display = display.none)
var int atr_length   = input.int(14, "Length", 1, group = "ADR (Absolute True Range)", display = display.none)
var int cip_length   = input.int(14, "Length", 1, group = "CIP (Change in Price)", display = display.none)
var int mpf_length   = input.int(14, "Length", 1, group = "MPF (Maximum Price Fluctuation)", display = display.none)
 
// ============
// CALCULATIONS
// ============
 
float adr = absolute_daily_range()
float ann = annualized(ann_length)
//float anr = annualized_returns(ta.roc(roc_source, roc_length))
float apc = absolute_price_change(apc_length)
float cip = change_in_price(cip_length)
float mpf = maximum_price_fluctuation(mpf_length)
 
// ======
// OUTPUT
// ======
 
plot(adr, "ADR", color.maroon)
plot(ann, "Ann.", color.olive)
//plot(anr, "Ann. Return")
plot(apc, "APC", #B71C1C)
plot(ta.atr(atr_length), "ATR", color.yellow)
plot(cip, "CIP", #F57F17)
plot(mpf, "MPF", #E65100)

← 返回列表