Created
February 3, 2015 21:56
-
-
Save DexterHaslem/2b322550d974571b54fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module yahoo_iv | |
open System | |
open System.Net | |
let stddev(values:seq<float>) = | |
values | |
|> Seq.fold (fun acc x -> acc + (1.0 / float (Seq.length values)) * (x - (Seq.average values)) ** 2.0) 0.0 | |
|> sqrt | |
let calcDailyReturns(prices:seq<float>) = | |
prices | |
|> Seq.pairwise | |
|> Seq.map (fun (x, y) -> log (x / y)) | |
let annualVolatility(returns:seq<float>) = | |
let sd = stddev(calcDailyReturns(returns)) | |
let days = Seq.length(returns) | |
sd * sqrt(float days) | |
let formatLeadingZero(number:int):String = | |
String.Format("{0:00}", number) | |
let constructURL(symbol, fromDate:DateTime, toDate:DateTime) = | |
"http://ichart.finance.yahoo.com/table.csv?s=" + symbol + | |
"&d=" + formatLeadingZero(toDate.Month-1) | |
+ "&e=" + formatLeadingZero(toDate.Day) | |
+ "&f=" + formatLeadingZero(toDate.Year) | |
+ "&g=d&a=" + formatLeadingZero(fromDate.Month-1) | |
+ "&b=" + formatLeadingZero(fromDate.Day) | |
+ "&c=" + formatLeadingZero(fromDate.Year) | |
+ "&ignore=.csv" | |
let fetchOne symbol fromDate toDate = | |
use client = new WebClient() | |
client.DownloadString(constructURL(symbol, fromDate, toDate)) | |
let getPrices stock fromDate toDate = | |
let data = fetchOne stock fromDate toDate | |
data.Trim().Split('\n') | |
|> Seq.skip 1 | |
|> Seq.map (fun s -> s.Split(',')) | |
|> Seq.map (fun s -> float s.[4]) | |
|> Seq.takeWhile (fun s -> s >= 0.0) | |
let getAnnualizedVol stock fromStr toStr = | |
let prices = getPrices stock (System.DateTime.Parse fromStr) (System.DateTime.Parse toStr) | |
let vol = Math.Round(annualVolatility(prices) * 100.0, 2) | |
sprintf "Volatility for %s is %.2f %%" stock vol |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment