Getting Financial Intraday Stock data with Azure Functions

Learn how you can easily get historical stock intraday data through Azure Functions!

Getting Financial Intraday Stock data with Azure Functions
Photo by Nick Chong / Unsplash

People are looking into stocks these days and want to get proper insights. Gathering these insights requires working with ticker data and looking at trying to predict the future and create signals. Now, one of the key issues however in the finance world is how to get the data required to work with it, more specifically: the intraday minute data.

⚠️ while insights are provided to work with intraday data, I recommend purchasing the data if more granularity is required as even these tools are not stable, nor do they provide data fast enough when looking at more than 10 tickers at the same time.

Trying out Y!Finance

One of the most common tools used is Y!Finance which allows us to download stock data from Yahoo Finance in Python and work with it. We simply import it and request it to download a ticker of our likings:

import yfinance as yf
import datetime
import os

# Define the ticker
ticker = "msft"
stock = yf.Ticker(ticker)

# Download the data from today
today = datetime.now()
data = stock.history(start='2006-01-01', end=today)

# Save as CSV
if not os.path.exists('data'):
	os.makedirs('data')

data.to_csv(f'data/{ticker}.csv')

The code above will then download all the stock data since 2006 and save it to a folder named data under data/msft.csv in our example.

Although working great, one issue is that this provides us the daily closing price, while most of the time we want to have the price for certain intervals (1m, 5m, 15m, 30m, 1h, 2h, and 4h being the most common ones) which we call Intraday Trades.

Luckily for us, yfinance API also allows us to do this by adapting the stock.history method to include intraday data if we keep the interval < 60 days. But what if we want longer? Well for that we have 2 options:

  1. Purchase the data
  2. Start collecting the data

So let's go into the second option on how we can start to collect the data.

Collecting Historical Data with Azure Functions

To collect this data, I want to build an Azure Function that can return the stock data for the provided ticker. We will thus have to:

  1. Create a function
  2. Running the Function Locally for development
  3. Deploy the function

So, let's go through these steps:

Creating the Azure Function

To get started, run the following command to create an Azure function project:

# More info: https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-python?tabs=azure-cli%2Cbash%2Cbrowser

# Create the function app
func init functions --python

# Create the function
cd functions
func new --name GetStockData --template "HTTP trigger" --authlevel "anonymous"

Running the Azure Function Locally

We now have a function created, so let's start the function runtime locally so we can debug our function while debugging it. To run your function app, simply use:

# In your function app folder (i.e., functions/) run:
func start

Writing our Azure Function

Now, take the learnings above with Y!Finance and let's create a function with this. In your functions/GetStockData/__init__.py file put the following content:

import yfinance as yf
import azure.functions as func

# Download the data for the provided stock
def data_download(ticker, interval="1m", period="1d"):
    stock = yf.Ticker(ticker)

    # # Download the data from yesterday
    # # @note: we take yesterday to ensure we have the entire day
    # #        an alternative could be to take data from today and do it multiple times per day
    # date_start = datetime.now()
    # date_end = datetime.now()

    data = stock.history(
        # start=date_start,
        # end=date_end,
        period=period,
        interval=interval
    )

    return data

def main(req: func.HttpRequest) -> func.HttpResponse:
    ticker = req.params.get('ticker')

    if not ticker:
        return func.HttpResponse(f"The ticker '{ticker}' was not found.", status_code=400)

    stock_intervals = ["1m", "5m", "15m", "30m", "1h", "2h", "4h", "1d"]

    stock_data = data_download(ticker, stock_intervals[0])
    stock_data_csv = stock_data.to_csv()

    return func.HttpResponse(stock_data_csv)

And importantly, update your functions/requirements.txt to include the dependencies:

azure-functions
yfinance
💡 Azure functions will take this file and install it on deployment

Deploying the Azure Function

Finally, deploy the azure function by running:

func azure functionapp publish <your_azure_func_app_name>

Testing our Function

We can now test our function by simply navigating to its url https://your_azure_func_app_name.azurewebsites.net/api/GetStockData?ticker=AAPL which should return the data as a beautiful CSV:

Datetime,Open,High,Low,Close,Volume,Dividends,Stock Splits
2022-10-20 09:30:00-04:00,143.02000427246094,144.22000122070312,142.91000366210938,144.2050018310547,3622060,0,0
2022-10-20 09:31:00-04:00,144.2100067138672,144.3000030517578,144.02999877929688,144.06320190429688,320432,0,0
2022-10-20 09:32:00-04:00,144.05999755859375,144.0800018310547,143.8096923828125,143.8498992919922,219477,0,0
2022-10-20 09:33:00-04:00,143.83999633789062,144.14999389648438,143.72999572753906,143.99000549316406,305619,0,0
2022-10-20 09:34:00-04:00,143.97999572753906,144.16000366210938,143.8300018310547,143.94000244140625,228319,0,0
2022-10-20 09:35:00-04:00,143.94000244140625,143.97000122070312,143.4199981689453,143.5,313779,0,0
...

Summary

In a few easy steps we have now created an Azure Function that can get the stock data that we require to start collecting historical data!

Subscribe to Xavier Geerinck

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe