TransWikia.com

How to query a stock with the Yahoo Finance API by ISIN?

Personal Finance & Money Asked on June 25, 2021

Given an ISIN, e.g. FI0009800643, how can I query the history of this stock? I tried using yfinance as follows:

msft = yfinance.Ticker(FI0009800643"")
hist = msft.history(period="1d")

but this just returns an error No data found, symbol may be delisted.

But when I enter the same ISIN on the yahoo finance page https://fr.finance.yahoo.com/ I get to the correct result (in this case a company named YIT Oyj in Finland.

So how to query data with the Yahoo Finance API given the ISIN?

One Answer

You can query Yahoo finance to get the Yahoo ticker symbol using elemental (which is basically selenium). Here is the code:

import json
import elemental
import yfinance
import urllib.parse as urlparse
from urllib.parse import parse_qs

def get_quote(symbol):
    msft = yfinance.Ticker(symbol)
    try:
        hist = msft.history(period="2d")
    except json.decoder.JSONDecodeError:
        return None
    try:
        hist.reset_index(inplace=True)
        jsdata = json.loads(hist.to_json())
        return jsdata["Close"]["0"]
    except (ValueError, KeyError) as e:
       return None


def web_lookup(browser, isin):
    # Search PyPI for Elemental.
    browser = elemental.Browser()
    browser.visit("https://finance.yahoo.com/lookup")
    browser.get_input(id="yfin-usr-qry").fill(isin)
    browser.get_button(type="submit").click()

    time.sleep(5)

    parsed = urlparse.urlparse(browser.url)
    try:
        ticker = parse_qs(parsed.query)['p'][0]
    except KeyError:
        ticker = "n/a"
    browser.quit()
    return ticker

When you call the function web_lookup essentially the lookup page will, be opened, the ISIN will be entered into the search box, and the browser eventually navigates to the Yahoo page with the Yahoo ticker symbol, which will be extracted from the URL the browser navigates to. The code then tries to use this ticker symbol to get the quotes from the last two days using the yahoo finance API. If that all works fine, the function returns a working Yahoo ticker symbol, or n/a in case something did not work.

Answered by Alex on June 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP