16 people like it.

Yahoo Historical Quote Implementation

F# module to return historical EOD: open | high |low | close | volume quotes from Yahoo. Single day requests only. DataContract provided on the result record for easy serialization.

  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: 
104: 
105: 
106: 
107: 
108: 
module Yahoo
    open System
    open System.Net 
    open System.Text 
    open System.Web
    open System.IO
    open System.Security.Authentication 
    open System.Runtime.Serialization // needs system.runtime.serialization; system.xml


(*          
use datacontract defintiion of the record for serialization.
    [<DataContract>] 
    type YahooPrice = {
        [<field: DataMember(Name="yahooSymbol") >] 
        yahooSymbol : string ;

        [<field: DataMember(Name="day") >] 
        day: string ;

        [<field: DataMember(Name="openPrice") >] 
        openPrice: float ;

        [<field: DataMember(Name="closePrice") >] 
        closePrice: float ;

        [<field: DataMember(Name="highPrice") >] 
        highPrice: float ;

        [<field: DataMember(Name="lowPrice") >] 
        lowPrice: float ;

        [<field: DataMember(Name="adjustedClosePrice") >] 
        adjustedClosePrice: float;

        [<field: DataMember(Name="volume") >] 
        volume: float;

    }
*) 

    type YahooPrice = {
        yahooSymbol : string ;
        day: string ;
        openPrice: float ;
        closePrice: float ;
        highPrice: float ;
        lowPrice: float ;
        adjustedClosePrice: float;
        volume: float;
    }

    type YahooRequest = {
        day: string;
        ticker: string ;
    }

    exception BadResults of string * string

    let historicalQuote (r:YahooRequest) = 
        
        let date: string = r.day
        let symbol: string = r.ticker

        let oops() = 
            raise(BadResults(symbol, date))

        let pad (i:int) =  
            let s = i.ToString() ; 
            if s.Length < 2 then "0" + s else s

        let yr = date.Substring(0,4)
        let mth = Int32.Parse(date.Substring(5,2)) - 1
        let day = Int32.Parse(date.Substring(8,2))
        let u = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + pad(mth) + "&b=" + pad(day) + "&c=" + yr + "&d=" + pad(mth) + "&e=" + pad(day) + "&f=" + yr
        let request : HttpWebRequest = downcast WebRequest.Create(u) 
        request.Method <- "GET" 
        request.ContentType <- "application/x-www-form-urlencoded" 
                
        let resultsArr =
            try
                let response = request.GetResponse()        
                let result = 
                    try 
                        use reader = new StreamReader(response.GetResponseStream()) 
                        reader.ReadToEnd(); 
                    finally 
                        response.Close() 
                if result.Split('\n').Length < 2 then oops()
                if result.Split('\n').[1].Length < 2 then oops()
                if result.Split('\n').[1].Split(',').Length < 7 then oops()
                result.Split('\n').[1].Split(',')
            with 
                | _ -> [|date; "-1"; "-1"; "-1"; "-1"; "-1"; "-1";|]

        {
            yahooSymbol  = symbol ;
            day= resultsArr.[0] ;
            openPrice= Double.Parse(resultsArr.[1]);
            closePrice= Double.Parse(resultsArr.[4]);
            highPrice= Double.Parse(resultsArr.[2]);
            lowPrice= Double.Parse(resultsArr.[3]);
            volume= Double.Parse(resultsArr.[5]);
            adjustedClosePrice= Double.Parse(resultsArr.[6]);
        }


    let valu = historicalQuote {day="2010/04/26"; ticker="MSFT";}
module Yahoo
namespace System
namespace System.Net
namespace System.Text
namespace System.Web
namespace System.IO
namespace System.Security
namespace System.Security.Authentication
namespace System.Runtime
namespace System.Runtime.Serialization
type YahooPrice =
  {yahooSymbol: string;
   day: string;
   openPrice: float;
   closePrice: float;
   highPrice: float;
   lowPrice: float;
   adjustedClosePrice: float;
   volume: float;}

Full name: Yahoo.YahooPrice
YahooPrice.yahooSymbol: string
Multiple items
val string : value:'T -> string

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

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

Full name: Microsoft.FSharp.Core.string
YahooPrice.day: string
YahooPrice.openPrice: float
Multiple items
val float : value:'T -> float (requires member op_Explicit)

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

--------------------
type float = Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
YahooPrice.closePrice: float
YahooPrice.highPrice: float
YahooPrice.lowPrice: float
YahooPrice.adjustedClosePrice: float
YahooPrice.volume: float
type YahooRequest =
  {day: string;
   ticker: string;}

Full name: Yahoo.YahooRequest
YahooRequest.day: string
YahooRequest.ticker: string
exception BadResults of string * string

Full name: Yahoo.BadResults
val historicalQuote : r:YahooRequest -> YahooPrice

Full name: Yahoo.historicalQuote
val r : YahooRequest
val date : string
val symbol : string
val oops : (unit -> 'a)
val raise : exn:Exception -> 'T

Full name: Microsoft.FSharp.Core.Operators.raise
val pad : (int -> string)
val i : 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<_>
val s : string
Int32.ToString() : string
Int32.ToString(provider: IFormatProvider) : string
Int32.ToString(format: string) : string
Int32.ToString(format: string, provider: IFormatProvider) : string
property String.Length: int
val yr : string
String.Substring(startIndex: int) : string
String.Substring(startIndex: int, length: int) : string
val mth : int
type Int32 =
  struct
    member CompareTo : value:obj -> int + 1 overload
    member Equals : obj:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member GetTypeCode : unit -> TypeCode
    member ToString : unit -> string + 3 overloads
    static val MaxValue : int
    static val MinValue : int
    static member Parse : s:string -> int + 3 overloads
    static member TryParse : s:string * result:int -> bool + 1 overload
  end

Full name: System.Int32
Int32.Parse(s: string) : int
Int32.Parse(s: string, provider: IFormatProvider) : int
Int32.Parse(s: string, style: Globalization.NumberStyles) : int
Int32.Parse(s: string, style: Globalization.NumberStyles, provider: IFormatProvider) : int
val day : int
val u : string
val request : HttpWebRequest
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
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
property HttpWebRequest.Method: string
property HttpWebRequest.ContentType: string
val resultsArr : string []
val response : WebResponse
HttpWebRequest.GetResponse() : WebResponse
val result : string
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
WebResponse.GetResponseStream() : Stream
StreamReader.ReadToEnd() : string
WebResponse.Close() : unit
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 Double =
  struct
    member CompareTo : value:obj -> int + 1 overload
    member Equals : obj:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member GetTypeCode : unit -> TypeCode
    member ToString : unit -> string + 3 overloads
    static val MinValue : float
    static val MaxValue : float
    static val Epsilon : float
    static val NegativeInfinity : float
    static val PositiveInfinity : float
    ...
  end

Full name: System.Double
Double.Parse(s: string) : float
Double.Parse(s: string, provider: IFormatProvider) : float
Double.Parse(s: string, style: Globalization.NumberStyles) : float
Double.Parse(s: string, style: Globalization.NumberStyles, provider: IFormatProvider) : float
val valu : YahooPrice

Full name: Yahoo.valu
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/3s
Posted:13 years ago
Author:akaPhenom
Tags: histocical stock quote , finance , web