HistoricalVolatility.efs

ICE Data Services -

HistoricalVolatility.efs                                                                                                      EFSLibrary - Discussion Board

File Name: HistoricalVolatility.efs


Description:
Calculates the historical volatility for the Daily, Weekly or Monthly intervals. 

 

Formula Parameters:
Number of Periods: 20

 

Notes:
Study requires a Daily, Weekly or Monthly interval.

 

Download File:
HistoricalVolatility.efs




EFS Code:

/*********************************
Provided By:  
    eSignal (Copyright © eSignal), a division of Interactive Data 
    Corporation. 2007. All rights reserved. This sample eSignal 
    Formula Script (EFS) is for educational purposes only and may be 
    modified and saved under a new file name.  eSignal is not responsible
    for the functionality once modified.  eSignal reserves the right 
    to modify and overwrite this EFS file with each new release.
    
Description:  Historical Volatility

Version:  1.0   7/2/2007

Notes:
    * Study requires a Daily, Weekly or Monthly interval.

Parameters:                             Default:
Number of Periods                       20
**********************************/


function preMain() {
    setStudyTitle("Historical Volatility");
    setCursorLabelName("HV ", 0);
    
    var fp1 = new FunctionParameter("nPeriods", FunctionParameter.NUMBER);
        fp1.setName("Number of Periods");
        fp1.setLowerLimit(1);
        fp1.setDefault(20);
}


var bInit = false;
var nTP = null;     // Trading Periods per year
var xHV = null;     // Historical Volatility Series object

function main(nPeriods) {
    // interval check
    if (isDWM() == false) {
        drawTextRelative(20, 20, "This study requires a D, W or M interval.", 
            Color.red, Color.black, Text.RELATIVETOLEFT|Text.RELATIVETOBOTTOM|Text.BOLD,
            null, 14, "inv_error");
        return;
    }
    
    if (bInit == false) {
        var nInv = getInterval();
        if (nInv == "D") nTP = 262;
        if (nInv == "W") nTP = 52;
        if (nInv == "M") nTP = 12;
        xHV = efsInternal("calcHV", nPeriods, nTP);
        bInit = true;
    }
    
    var nHV = xHV.getValue(0);
    if (nHV == null) return;
    
    return nHV;
}


function calcHV(_nPeriods, _nTP) {
    if (close(-(_nPeriods+1)) == null) return;
    
    var HV = null;
    var nSSD = 0;
    var nSum = 0;
    var nAvg = 0;
    
    for (var i = 0; i < _nPeriods; i++) {
        nSum += Math.log(close(-i) / close(-(i+1)));
    }
    nAvg = nSum / _nPeriods;
    
    for (var j = 0; j < _nPeriods; j++) {
        nSSD += Math.pow( (Math.log(close(-j) / close(-(j+1))) - nAvg) , 2);
    }
    
    HV = Math.sqrt( (nSSD / (_nPeriods-1) ) ) * Math.sqrt(_nTP);
    
    return (HV*100);
}