Option Explicit
'Grabs Yahoo historical stock data
'tstom@fuse.net
'requires Microsoft ActiveX Data Objects 2.6 or later
Private pWinHttpRequest As WinHttp.WinHttpRequest
Friend Function GetHistoricalData(Symbol As String, _
Optional FromDate As Date = #12:00:00 AM#, _
Optional ToDate As Date = #12:00:00 AM#, _
Optional Interval As String = "Daily") As ADODB.RecordSet
Dim URL As String, ResponseText As String
Dim pRecordSet As ADODB.RecordSet
Dim DateString As String, IntervalString As String
Dim RTS() As String, RTFI
Dim x As Long
'http://ichart.finance.yahoo.com/table.csv?s=INTC&a=06&b=9&c=1986&d=2&e=5&f=2008&g=d
If FromDate <> #12:00:00 AM# Or ToDate <> #12:00:00 AM# Then
If FromDate = 0 And ToDate > 0 Then
FromDate = #1/1/1900#
ElseIf FromDate > 0 And ToDate = 0 Then
ToDate = Date
End If
DateString = "&a=" & Format(Month(FromDate) - 1, "00") & "&b=" & Format(FromDate, "DD") & "&c=" & Format(FromDate, "YYYY") & _
"&d=" & Format(Month(ToDate) - 1, "00") & "&e=" & Format(ToDate, "DD") & "&f=" & Format(ToDate, "YYYY")
End If
Select Case Interval
Case "Daily", "": IntervalString = "&g=d"
Case "Weekly": IntervalString = "&g=w"
Case "Monthly": IntervalString = "&g=m"
Case Else
Err.Raise 10001, "HistoricalStockDataFromYahoo.GetHistoricalData", "Invalid Interval. Expected ""Daily"", ""Weekly"", or ""Monthly"""
End Select
URL = "http://ichart.finance.yahoo.com/table.csv?s=" & Symbol & DateString & IntervalString
pWinHttpRequest.Open "GET", URL, False
pWinHttpRequest.Send
ResponseText = pWinHttpRequest.ResponseText
If InStr(ResponseText, "<title>Yahoo! - 404 Not Found</title>") Then
Err.Raise 10002, "HistoricalStockDataFromYahoo.GetHistoricalData", "Invalid Search Parameters or other error. No data was returned."
End If
Set pRecordSet = New ADODB.RecordSet
pRecordSet.Fields.Append "Date", adDBDate
pRecordSet.Fields.Append "Open", adCurrency
pRecordSet.Fields.Append "High", adCurrency
pRecordSet.Fields.Append "Low", adCurrency
pRecordSet.Fields.Append "Close", adCurrency
pRecordSet.Fields.Append "Volume", adInteger
pRecordSet.Fields.Append "Adj Close", adCurrency
pRecordSet.Open
RTS = Split(ResponseText, Chr(10))
For x = LBound(RTS) + 1 To UBound(RTS)
If RTS(x) <> "" Then
RTFI = Split(RTS(x), ",")
pRecordSet.AddNew Array("Date", "Open", "High", "Low", "Close", "Volume", "Adj Close"), Array(RTFI(0), RTFI(1), RTFI(2), RTFI(3), RTFI(4), RTFI(5), RTFI(6))
pRecordSet.Update
End If
Next x
pRecordSet.MoveFirst
Set GetHistoricalData = pRecordSet
End Function
Private Sub Class_Initialize()
On Error Resume Next
Set pWinHttpRequest = New WinHttpRequest
If pWinHttpRequest Is Nothing Then
Err.Raise 10000, "HistoricalStockDataFromYahoo.Class_Initialize", "Could not create WinHttp.WinHttpRequest object..."
End If
End Sub