Download Historical Stock Quotes from Yahoo to Excel


Note: In May 2017, the "tables" and "ichart" API from Yahoo to download historical stock data was discontinued by the Yahoo Finance team. The following illustrates the new method of using the “query1” API to download historical stock data. A “cookie” and a “crumb” is required to call this new API successfully. The VBA programming codes for extracting these two components is shown below.

This document will show you how to automate the download of the Stock Quotes from Yahoo Finance (https://finance.yahoo.com) to Excel. We will be using a simple programming language called Visual Basic for Applications (VBA) and will be going through the steps, one at a time to allow you to construct the model without prior knowledge of VBA. The completed model is also available for download below.

1. Launch Excel and create a new workbook. Call this workbook AutomatedDownloadData.xlsm.

In Microsoft Excel 2003: Go to Tools->Macro->Visual Basic Editor

In Microsoft Excel 2007/2010/2013/2016: Go to Developer->Visual Basic

2. Right click on VBAProject (your Excel Filename) and select Insert->Module. A default Module1 will be inserted. Click on Module1 and paste the VBA code below on the right hand side of the Visual Basic Editor. The following VBA code allows you to download data from Yahoo Finance using a specified Stock symbol, Start Date and End Date.





Sub GetStock(ByVal stockSymbol As String, 
             ByVal StartDate As Date, ByVal EndDate As Date)
    
    Dim crumb               As String
    Dim cookie               As String
    Dim response               As String
    Dim strUrl As String
    Dim DownloadURL As String
    Dim period1, period2 As String
    Dim httpReq As WinHttp.WinHttpRequest
    Set httpReq = New WinHttp.WinHttpRequest
    
    Application.ScreenUpdating = False

    DownloadURL="https://finance.yahoo.com/lookup?s=" & stockSymbol
    With httpReq
        .Open "GET", DownloadURL, False
        .setRequestHeader "Content-Type", 
                  "application/x-www-form-urlencoded;charset=UTF-8"
        .send
        .waitForResponse
        response = .responseText
        cookie = Split(.getResponseHeader("Set-Cookie"), ";")(0)
    End With

    period1 = (StartDate - DateValue("January 1, 1970")) * 86400
    period2 = (EndDate - DateValue("January 1, 1970")) * 86400
    
    Dim counter As Long
    Dim startCounter As Long
    Dim result As String
    
    crumb = Chr(34) & "CrumbStore" & Chr(34) & ":{" 
            & Chr(34) & "crumb" & Chr(34) & ":" & Chr(34)
    startCounter = InStr(response, crumb) + Len(crumb)
    While Mid(response, startCounter, 1) <> Chr(34)
        result = result & Mid(response, startCounter, 1)
        startCounter = startCounter + 1
    Wend
    crumb = result
    DownloadURL="https://query1.finance.yahoo.com/v7/finance/download/" 
                &stockSymbol & "?period1=" & period1 & "&period2=" 
                &period2 & "&interval=1d&events=history&crumb=" & crumb

    With httpReq
        .Open "GET", DownloadURL, False
        .setRequestHeader "Cookie", cookie
        .send
        .waitForResponse
        dataResult = .responseText
    End With
    
    dataResult = Replace(dataResult, ",", vbTab)

    Dim dataObj As New DataObject
    dataObj.SetText dataResult
    dataObj.PutInClipboard
            
    Set currentWorksheet = ThisWorkbook.ActiveSheet
    Set currentRange = currentWorksheet.Range("A1")
    dataObj.GetFromClipboard
    currentRange.PasteSpecial
    
    ActiveWindow.SmallScroll Down:=-12
    Columns("A:A").TextToColumns Destination:=Range("A1"), _ 
        DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,ConsecutiveDelimiter:=False,_
        Tab:=True, _
        Semicolon:=False, Comma:=True, Space:=False, _
        Other:=False, FieldInfo _
        :=Array(Array(1, 1),Array(2, 1),Array(3, 1),Array(4, 1),_ 
        Array(5, 1), Array(6, 1), Array(7, 1))
    Columns("A:F").EntireColumn.AutoFit
    Range("A1").Select
    
    Application.ScreenUpdating = True

End Sub

Sub Download()
     Call GetStock("BAC", "01/01/2017", "06/21/2017")
End Sub




3. Next, in the Microsoft Visual Basic for Applications editor, click on the Tools->Reference menu item and ensure that “Microsoft WinHTTPServices” and “Microsoft Forms 2.0 Object Library” are included. If you do not see ”Microsoft.WinHTTPServices”, you can click on the “Browse” button and then navigate to the “C:\Windows\System32\” folder to add “winhttpcom.dll”.



4. Click on Save and then File->Close to return to Microsoft Excel. In Excel, try out the downloading of data by going to

Excel 2003:
Go to Tools->Macro->Macros…, select the Download macro and click run

Excel 2007/2010/2013:
Go to Developer->Macros, select the Download macro and click run.

This will initiate a download of Stock Prices from Yahoo! Finance.

What we have written is a subroutine that downloads stock data automatically and can be executed by Excel. It takes "stockSymbol", "StartDate" and "EndDate" as parameters.

In the whole block of code above, the most important part is the following.



    DownloadURL = "https://query1.finance.yahoo.com/v7/finance/download/" 
                  & stockSymbol & "?period1=" & period1 & "&period2=" 
                  & period2 & "&interval=1d&events=history&crumb=" 
                  & crumb
    With httpReq
        .Open "GET", DownloadURL, False
        .setRequestHeader "Cookie", cookie
        .send
        .waitForResponse
        dataResult = .responseText
    End With



It basically says that we will be downloading data from DownloadURL:

https://query1.finance.yahoo.com/v7/finance/download/" & stockSymbol & "?period1=" & period1 & "&period2=" & period2 & "&interval=1d&events=history&crumb=" & crumb

  • stockSymbol is the variable containing a stock symbol such as “BAC”.
  • period1 and period2 specifies the start date and end date to download data.
  • The “cookie” and “crumb” (extracted from response) required is extracted with the following VBA codes.


    DownloadURL="https://finance.yahoo.com/lookup?s="&stockSymbol
    With httpReq
        .Open "GET", DownloadURL, False
        .setRequestHeader "Content-Type", 
		"application/x-www-form-urlencoded; charset=UTF-8"
        .send
        .waitForResponse
        response = .responseText
        cookie = Split(.getResponseHeader("Set-Cookie"), ";")(0)
    End With



You can also find the implementation of this example in the workbook DownloadStockQuotes.xlsm.

Download


Free spreadsheet to download Stock Quotes - v1.1

System Requirements

Microsoft® Windows 7, Windows 8 or Windows 10
512 MB RAM
5 MB of Hard Disk space
Excel 2007, 2010, 2013, 2016

License

By downloading this software from our web site, you agree to the terms of our license agreement.

Download

DownloadStockQuotes.zip (Zip Format - 423 KB)