Historical Volatility Indicator

Hello
I would like to create a historical volatility indicator based on daily close prices. The indicator would have as an input the number of days used: 10, 20, 30, 60…etc.
I want to calculated the standard deviation of log returns, then annualize the StdDev using either 252 or 365 trading days. Thank you.

period = x
logReturn = Math.Log(Input[0] / Input[1])
annualizedHV = dailyStdDev * sqrtTradingDaysPerYear

1 Like

Hey there,

As requested, here’s the Historical Volatility Indicator you asked about. This version calculates historical volatility using the standard deviation of log returns, and then annualizes it based on your choice of trading days (252 or 365).

Just a quick note:

:backhand_index_pointing_right: Be sure to apply this indicator on a Daily chart.

It was specifically designed to track daily changes in volatility. If you load it on an intraday chart, you won’t get true daily-based historical volatility since the math depends on daily closes.

The description inside the code was written by us, so we’d appreciate it if that part stays intact.

Other than that, enjoy it…hope it helps with whatever project you’re working on.
Happy holidays, and have a great Thanksgiving ahead!

#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion

namespace NinjaTrader.NinjaScript.Indicators
{
public class HistoricalVolatilityIndicator : Indicator
{
private Series logReturns;

    #region OnStateChange
    protected override void OnStateChange()
    {
        if (State == State.SetDefaults)
        {
            Description                     = "Historical volatility based on standard deviation of log returns, annualized. Created by: The Algo Trader, LLC. All Rights Reserved.";
            Name                            = "HistoricalVolatilityIndicator";
            Calculate                       = Calculate.OnBarClose;
            IsOverlay                       = false;
            DisplayInDataBox                = true;
            DrawOnPricePanel                = false;
            PaintPriceMarkers               = true;
            IsSuspendedWhileInactive        = true;

            Period                          = 20;
            TradingDaysPerYear              = 252;

            AddPlot(Brushes.DodgerBlue, "HistoricalVolatility");
        }
        else if (State == State.DataLoaded)
        {
            logReturns = new Series<double>(this);
        }
    }
    #endregion

    #region OnBarUpdate
    protected override void OnBarUpdate()
    {
        if (CurrentBar < 1)
        {
            Value[0] = double.NaN;
            return;
        }

        if (Input[1] == 0)
        {
            Value[0] = double.NaN;
            return;
        }

        double lr = Math.Log(Input[0] / Input[1]);
        logReturns[0] = lr;

        if (CurrentBar < Period)
        {
            Value[0] = double.NaN;
            return;
        }

        double dailyStdDev = StdDev(logReturns, Period)[0];

        double annualizedHV = dailyStdDev * Math.Sqrt(TradingDaysPerYear);

        Value[0] = annualizedHV;
    }
    #endregion

    #region Properties
    [Range(2, int.MaxValue)]
    [NinjaScriptProperty]
    [Display(Name = "Period (days)", Order = 1, GroupName = "Parameters")]
    public int Period
    {
        get; set;
    }

    [Range(1, 365)]
    [NinjaScriptProperty]
    [Display(Name = "Trading Days Per Year", Order = 2, GroupName = "Parameters")]
    public int TradingDaysPerYear
    {
        get; set;
    }
    #endregion
}

}