4 people like it.

Historical Volatility

The code snippet is capable of calculating historical volatility using Close Price, High Low Price and Close High Low Price methods. Simply provide symbol, start date and end date of the specific volatility method and it extracts the market data from the yahoo service and calculated the volatility.

  1: 
  2: 
  3: 
  4: 
  5: 
  6: 
  7: 
  8: 
  9: 
 10: 
 11: 
 12: 
 13: 
 14: 
 15: 
 16: 
 17: 
 18: 
 19: 
 20: 
 21: 
 22: 
 23: 
 24: 
 25: 
 26: 
 27: 
 28: 
 29: 
 30: 
 31: 
 32: 
 33: 
 34: 
 35: 
 36: 
 37: 
 38: 
 39: 
 40: 
 41: 
 42: 
 43: 
 44: 
 45: 
 46: 
 47: 
 48: 
 49: 
 50: 
 51: 
 52: 
 53: 
 54: 
 55: 
 56: 
 57: 
 58: 
 59: 
 60: 
 61: 
 62: 
 63: 
 64: 
 65: 
 66: 
 67: 
 68: 
 69: 
 70: 
 71: 
 72: 
 73: 
 74: 
 75: 
 76: 
 77: 
 78: 
 79: 
 80: 
 81: 
 82: 
 83: 
 84: 
 85: 
 86: 
 87: 
 88: 
 89: 
 90: 
 91: 
 92: 
 93: 
 94: 
 95: 
 96: 
 97: 
 98: 
 99: 
100: 
101: 
102: 
103: 
open System
open System.IO
open System.Xml
open System.Text
open System.Net
open System.Globalization

let makeUrl symbol (dfrom:DateTime) (dto:DateTime) = 
    //Uses the not-so-known chart-data:
    new Uri("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + 
       "&e=" + dto.Day.ToString() + "&d=" + dto.Month.ToString() + "&f=" + dto.Year.ToString() +
       "&g=d&b=" + dfrom.Day.ToString() + "&a=" + dfrom.Month.ToString() + "&c=" + dfrom.Year.ToString() + 
       "&ignore=.csv")

let fetch (url : Uri) = 
    let req = WebRequest.Create (url) :?> HttpWebRequest
    use stream = req.GetResponse().GetResponseStream()
    use reader = new StreamReader(stream)
    reader.ReadToEnd()

let reformat (response:string) = 
    let split (mark:char) (data:string) = 
        data.Split(mark) |> Array.toList
    response |> split '\n' 
    |> List.filter (fun f -> f<>"") 
    |> List.map (split ',') 
    
let getRequest uri = (fetch >> reformat) uri

type MarketData =
    {Date: DateTime;
     Open: double;
     High: double;
     Low: double;
     Close: double;
     Volume: int;
     AdjClose: double;}

let converter (data:List<List<string>>) =
    [for dataArray in data.Tail do
        yield {Date = DateTime.ParseExact(dataArray.[0],"yyyy-MM-dd",CultureInfo.InvariantCulture);
          Open = System.Convert.ToDouble(dataArray.[1]);
          High = System.Convert.ToDouble(dataArray.[2]);
          Low = System.Convert.ToDouble(dataArray.[3]);
          Close = System.Convert.ToDouble(dataArray.[4]);
          Volume = System.Convert.ToInt32(dataArray.[5]);
          AdjClose = System.Convert.ToDouble(dataArray.[6])}]

//Example: Microsoft, from 2010-03-20 to 2010-04-21
//getMarketData "MSFT" (new DateTime(2010,1,1)) (new DateTime(2010,1,30));;
let getMarketData symbol fromDate toDate = makeUrl symbol fromDate toDate  |> getRequest |> converter

//highLowVolatility "MSFT" (new DateTime(2010,1,1)) (new DateTime(2010,1,30));;
let highLowVolatility symbol (fromDate:DateTime) (toDate:DateTime) =
    let data = getMarketData symbol fromDate toDate
    data
    |> List.fold (fun acc mktdata -> acc + Math.Log(mktdata.High / mktdata.Low) )  0.0
    |> (*) ( 1.0 / ( ( 2.0 * System.Convert.ToDouble(data.Length)) * System.Math.Sqrt(System.Math.Log(2.0)) ) )
    |> (*) (System.Math.Sqrt 252.0)

//closeVolatility "MSFT" (new DateTime(2010,1,1)) (new DateTime(2010,1,30));;
let closeVolatility symbol (fromDate:DateTime) (toDate:DateTime) =
        let data = getMarketData symbol fromDate toDate
        let rec close (dt: MarketData list)  =
            match dt with
            | x::y::[] -> System.Math.Pow(System.Math.Log((y.Close / x.Close)),2.0) 
            | x::y::tail -> System.Math.Pow(System.Math.Log((y.Close / x.Close)),2.0)  + (close (List.append [y] tail))
            | [] -> 0.0
  
        let rec close1 (dt: MarketData list)  =
            match dt with
            | x::y::[] -> System.Math.Log(y.Close / x.Close)
            | x::y::tail -> System.Math.Log(y.Close / x.Close)  + (close1 (List.append [y] tail))
            | [] -> 0.0
        
        let firstValue = data
                            |> close
                            |> (*) (1.0 / (System.Convert.ToDouble(data.Length - 1) - 1.0))
                           
        let secondValue = (System.Math.Pow((close1 data), 2.0)) * ( 1.0 / (System.Convert.ToDouble(data.Length - 1) *(System.Convert.ToDouble(data.Length - 1) - 1.0 )))
       
        System.Math.Sqrt (firstValue - secondValue) * System.Math.Sqrt(252.0)     

//highLowCloseVolatility "MSFT" (new DateTime(2010,1,1)) (new DateTime(2010,1,30));;
let highLowCloseVolatility symbol (fromDate:DateTime) (toDate:DateTime) =
        let data = getMarketData symbol fromDate toDate
        let highLow (dt: MarketData list) = 
                    dt
                    |> List.fold (fun acc x -> acc + (0.5) * System.Math.Pow(System.Math.Log(x.High / x.Low),2.0))  0.0
                    |> (*) ( 1.0 / System.Convert.ToDouble(data.Length - 1))

        let rec closeCalc (dt: MarketData list)  =
                    match dt with
                    | x::y::[] -> ((2.0 * System.Math.Log(2.0)) - 1.0) * System.Math.Pow(System.Math.Log((y.Close / x.Close)),2.0) 
                    | x::y::tail -> ((2.0 * System.Math.Log(2.0)) - 1.0) * System.Math.Pow(System.Math.Log((y.Close / x.Close)),2.0)  + (closeCalc (List.append [y] tail))
                    | [] -> 0.0

        let close (dt: MarketData list) =
                dt
                |> closeCalc
                |> (*) ( 1.0 / System.Convert.ToDouble(data.Length - 1))

        System.Math.Sqrt(252.0) * System.Math.Sqrt((highLow data.Tail) - (close data))
namespace System
namespace System.IO
namespace System.Xml
namespace System.Text
namespace System.Net
namespace System.Globalization
val makeUrl : symbol:string -> dfrom:DateTime -> dto:DateTime -> Uri

Full name: Script.makeUrl
val symbol : string
val dfrom : DateTime
Multiple items
type DateTime =
  struct
    new : ticks:int64 -> DateTime + 10 overloads
    member Add : value:TimeSpan -> DateTime
    member AddDays : value:float -> DateTime
    member AddHours : value:float -> DateTime
    member AddMilliseconds : value:float -> DateTime
    member AddMinutes : value:float -> DateTime
    member AddMonths : months:int -> DateTime
    member AddSeconds : value:float -> DateTime
    member AddTicks : value:int64 -> DateTime
    member AddYears : value:int -> DateTime
    ...
  end

Full name: System.DateTime

--------------------
DateTime()
   (+0 other overloads)
DateTime(ticks: int64) : unit
   (+0 other overloads)
DateTime(ticks: int64, kind: DateTimeKind) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, calendar: Calendar) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: DateTimeKind) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: Calendar) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, kind: DateTimeKind) : unit
   (+0 other overloads)
val dto : DateTime
Multiple items
type Uri =
  new : uriString:string -> Uri + 5 overloads
  member AbsolutePath : string
  member AbsoluteUri : string
  member Authority : string
  member DnsSafeHost : string
  member Equals : comparand:obj -> bool
  member Fragment : string
  member GetComponents : components:UriComponents * format:UriFormat -> string
  member GetHashCode : unit -> int
  member GetLeftPart : part:UriPartial -> string
  ...

Full name: System.Uri

--------------------
Uri(uriString: string) : unit
Uri(uriString: string, uriKind: UriKind) : unit
Uri(baseUri: Uri, relativeUri: string) : unit
Uri(baseUri: Uri, relativeUri: Uri) : unit
property DateTime.Day: int
Int32.ToString() : string
Int32.ToString(provider: IFormatProvider) : string
Int32.ToString(format: string) : string
Int32.ToString(format: string, provider: IFormatProvider) : string
property DateTime.Month: int
property DateTime.Year: int
val fetch : url:Uri -> string

Full name: Script.fetch
val url : Uri
val req : HttpWebRequest
type WebRequest =
  inherit MarshalByRefObject
  member Abort : unit -> unit
  member AuthenticationLevel : AuthenticationLevel with get, set
  member BeginGetRequestStream : callback:AsyncCallback * state:obj -> IAsyncResult
  member BeginGetResponse : callback:AsyncCallback * state:obj -> IAsyncResult
  member CachePolicy : RequestCachePolicy with get, set
  member ConnectionGroupName : string with get, set
  member ContentLength : int64 with get, set
  member ContentType : string with get, set
  member Credentials : ICredentials with get, set
  member EndGetRequestStream : asyncResult:IAsyncResult -> Stream
  ...

Full name: System.Net.WebRequest
WebRequest.Create(requestUri: Uri) : WebRequest
WebRequest.Create(requestUriString: string) : WebRequest
type HttpWebRequest =
  inherit WebRequest
  member Abort : unit -> unit
  member Accept : string with get, set
  member AddRange : range:int -> unit + 7 overloads
  member Address : Uri
  member AllowAutoRedirect : bool with get, set
  member AllowWriteStreamBuffering : bool with get, set
  member AutomaticDecompression : DecompressionMethods with get, set
  member BeginGetRequestStream : callback:AsyncCallback * state:obj -> IAsyncResult
  member BeginGetResponse : callback:AsyncCallback * state:obj -> IAsyncResult
  member ClientCertificates : X509CertificateCollection with get, set
  ...

Full name: System.Net.HttpWebRequest
val stream : Stream
HttpWebRequest.GetResponse() : WebResponse
val reader : StreamReader
Multiple items
type StreamReader =
  inherit TextReader
  new : stream:Stream -> StreamReader + 9 overloads
  member BaseStream : Stream
  member Close : unit -> unit
  member CurrentEncoding : Encoding
  member DiscardBufferedData : unit -> unit
  member EndOfStream : bool
  member Peek : unit -> int
  member Read : unit -> int + 1 overload
  member ReadLine : unit -> string
  member ReadToEnd : unit -> string
  ...

Full name: System.IO.StreamReader

--------------------
StreamReader(stream: Stream) : unit
StreamReader(path: string) : unit
StreamReader(stream: Stream, detectEncodingFromByteOrderMarks: bool) : unit
StreamReader(stream: Stream, encoding: Encoding) : unit
StreamReader(path: string, detectEncodingFromByteOrderMarks: bool) : unit
StreamReader(path: string, encoding: Encoding) : unit
StreamReader(stream: Stream, encoding: Encoding, detectEncodingFromByteOrderMarks: bool) : unit
StreamReader(path: string, encoding: Encoding, detectEncodingFromByteOrderMarks: bool) : unit
StreamReader(stream: Stream, encoding: Encoding, detectEncodingFromByteOrderMarks: bool, bufferSize: int) : unit
StreamReader(path: string, encoding: Encoding, detectEncodingFromByteOrderMarks: bool, bufferSize: int) : unit
StreamReader.ReadToEnd() : string
val reformat : response:string -> string list list

Full name: Script.reformat
val response : string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = String

Full name: Microsoft.FSharp.Core.string
val split : (char -> string -> string list)
val mark : char
Multiple items
val char : value:'T -> char (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.char

--------------------
type char = Char

Full name: Microsoft.FSharp.Core.char
val data : string
String.Split([<ParamArray>] separator: char []) : string []
String.Split(separator: string [], options: StringSplitOptions) : string []
String.Split(separator: char [], options: StringSplitOptions) : string []
String.Split(separator: char [], count: int) : string []
String.Split(separator: string [], count: int, options: StringSplitOptions) : string []
String.Split(separator: char [], count: int, options: StringSplitOptions) : string []
type Array =
  member Clone : unit -> obj
  member CopyTo : array:Array * index:int -> unit + 1 overload
  member GetEnumerator : unit -> IEnumerator
  member GetLength : dimension:int -> int
  member GetLongLength : dimension:int -> int64
  member GetLowerBound : dimension:int -> int
  member GetUpperBound : dimension:int -> int
  member GetValue : [<ParamArray>] indices:int[] -> obj + 7 overloads
  member Initialize : unit -> unit
  member IsFixedSize : bool
  ...

Full name: System.Array
val toList : array:'T [] -> 'T list

Full name: Microsoft.FSharp.Collections.Array.toList
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val filter : predicate:('T -> bool) -> list:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.filter
val f : string
val map : mapping:('T -> 'U) -> list:'T list -> 'U list

Full name: Microsoft.FSharp.Collections.List.map
val getRequest : uri:Uri -> string list list

Full name: Script.getRequest
val uri : Uri
type MarketData =
  {Date: DateTime;
   Open: double;
   High: double;
   Low: double;
   Close: double;
   Volume: int;
   AdjClose: double;}

Full name: Script.MarketData
MarketData.Date: DateTime
MarketData.Open: double
Multiple items
val double : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.double

--------------------
type double = Double

Full name: Microsoft.FSharp.Core.double
MarketData.High: double
MarketData.Low: double
MarketData.Close: double
MarketData.Volume: int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
MarketData.AdjClose: double
val converter : data:List<List<string>> -> MarketData list

Full name: Script.converter
val data : List<List<string>>
val dataArray : List<string>
property List.Tail: List<string> list
DateTime.ParseExact(s: string, format: string, provider: IFormatProvider) : DateTime
DateTime.ParseExact(s: string, formats: string [], provider: IFormatProvider, style: DateTimeStyles) : DateTime
DateTime.ParseExact(s: string, format: string, provider: IFormatProvider, style: DateTimeStyles) : DateTime
Multiple items
type CultureInfo =
  new : name:string -> CultureInfo + 3 overloads
  member Calendar : Calendar
  member ClearCachedData : unit -> unit
  member Clone : unit -> obj
  member CompareInfo : CompareInfo
  member CultureTypes : CultureTypes
  member DateTimeFormat : DateTimeFormatInfo with get, set
  member DisplayName : string
  member EnglishName : string
  member Equals : value:obj -> bool
  ...

Full name: System.Globalization.CultureInfo

--------------------
CultureInfo(name: string) : unit
CultureInfo(culture: int) : unit
CultureInfo(name: string, useUserOverride: bool) : unit
CultureInfo(culture: int, useUserOverride: bool) : unit
property CultureInfo.InvariantCulture: CultureInfo
type Convert =
  static val DBNull : obj
  static member ChangeType : value:obj * typeCode:TypeCode -> obj + 3 overloads
  static member FromBase64CharArray : inArray:char[] * offset:int * length:int -> byte[]
  static member FromBase64String : s:string -> byte[]
  static member GetTypeCode : value:obj -> TypeCode
  static member IsDBNull : value:obj -> bool
  static member ToBase64CharArray : inArray:byte[] * offsetIn:int * length:int * outArray:char[] * offsetOut:int -> int + 1 overload
  static member ToBase64String : inArray:byte[] -> string + 3 overloads
  static member ToBoolean : value:obj -> bool + 17 overloads
  static member ToByte : value:obj -> byte + 18 overloads
  ...

Full name: System.Convert
Convert.ToDouble(value: DateTime) : float
   (+0 other overloads)
Convert.ToDouble(value: bool) : float
   (+0 other overloads)
Convert.ToDouble(value: string) : float
   (+0 other overloads)
Convert.ToDouble(value: decimal) : float
   (+0 other overloads)
Convert.ToDouble(value: float) : float
   (+0 other overloads)
Convert.ToDouble(value: float32) : float
   (+0 other overloads)
Convert.ToDouble(value: uint64) : float
   (+0 other overloads)
Convert.ToDouble(value: int64) : float
   (+0 other overloads)
Convert.ToDouble(value: uint32) : float
   (+0 other overloads)
Convert.ToDouble(value: int) : float
   (+0 other overloads)
Convert.ToInt32(value: DateTime) : int
   (+0 other overloads)
Convert.ToInt32(value: string) : int
   (+0 other overloads)
Convert.ToInt32(value: decimal) : int
   (+0 other overloads)
Convert.ToInt32(value: float) : int
   (+0 other overloads)
Convert.ToInt32(value: float32) : int
   (+0 other overloads)
Convert.ToInt32(value: uint64) : int
   (+0 other overloads)
Convert.ToInt32(value: int64) : int
   (+0 other overloads)
Convert.ToInt32(value: int) : int
   (+0 other overloads)
Convert.ToInt32(value: uint32) : int
   (+0 other overloads)
Convert.ToInt32(value: uint16) : int
   (+0 other overloads)
val getMarketData : symbol:string -> fromDate:DateTime -> toDate:DateTime -> MarketData list

Full name: Script.getMarketData
val fromDate : DateTime
val toDate : DateTime
val highLowVolatility : symbol:string -> fromDate:DateTime -> toDate:DateTime -> float

Full name: Script.highLowVolatility
val data : MarketData list
val fold : folder:('State -> 'T -> 'State) -> state:'State -> list:'T list -> 'State

Full name: Microsoft.FSharp.Collections.List.fold
val acc : float
val mktdata : MarketData
type Math =
  static val PI : float
  static val E : float
  static member Abs : value:sbyte -> sbyte + 6 overloads
  static member Acos : d:float -> float
  static member Asin : d:float -> float
  static member Atan : d:float -> float
  static member Atan2 : y:float * x:float -> float
  static member BigMul : a:int * b:int -> int64
  static member Ceiling : d:decimal -> decimal + 1 overload
  static member Cos : d:float -> float
  ...

Full name: System.Math
Math.Log(d: float) : float
Math.Log(a: float, newBase: float) : float
property List.Length: int
Math.Sqrt(d: float) : float
val closeVolatility : symbol:string -> fromDate:DateTime -> toDate:DateTime -> float

Full name: Script.closeVolatility
val close : (MarketData list -> float)
val dt : MarketData list
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
val x : MarketData
val y : MarketData
Math.Pow(x: float, y: float) : float
val tail : MarketData list
val append : list1:'T list -> list2:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.append
val close1 : (MarketData list -> float)
val firstValue : float
val secondValue : float
val highLowCloseVolatility : symbol:string -> fromDate:DateTime -> toDate:DateTime -> float

Full name: Script.highLowCloseVolatility
val highLow : (MarketData list -> float)
val closeCalc : (MarketData list -> float)
property List.Tail: MarketData list
Raw view New version

More information

Link:http://fssnip.net/3J
Posted:5 years ago
Author:Kishor Aher
Tags: Finance , Historical Volatility , Volatility , High Low Volatility , Close Price Volatility