sample yfinance api for python code to get and return recommendation_summary for a stock symbol to javascript

80 views Asked by At

I am getting "Failed to fetch data for symbol AAPL. Status code: 403" response from the following code:

@app.route('/get_recommendations', methods=['GET', 'POST'])
def get_recommendations(symbol):
    url = f"https://query2.finance.yahoo.com/v10/finance/quoteSummary/{symbol}?modules=recommendationTrend&corsDomain=finance.yahoo.com&formatted=false"
    response = requests.get(url)
    
    if response.status_code == 200:
        data = response.json()
        return data
    else:
        print(f"Failed to fetch data for symbol {symbol}. Status code: {response.status_code}")
        return None

I am expecting to get recommendations for stock symbol from yfinance.

1

There are 1 answers

0
Sam Morgan On

HTTP 403 means you aren't authorized to make requests against the given endpoint. This is happening because the Yahoo Finance API was shut down in 2017. The only way to do it now is via screen scraping, which is almost always a bad idea. That being said, there's an existing library for this: yfinance

While I'm here, here's a slight refactor of your code that makes better use of Requests and doesn't print (which is a bad practice).

import logging

import requests
from flask import Flask

logger = logging.getLogger(__name__)
app = Flask(__name__)


@app.route("/get_recommendations", methods=["GET", "POST"])
def get_recommendations(symbol):
    try:
        response = requests.get(
            f"https://query2.finance.yahoo.com/v10/finance/quoteSummary/{symbol}",
            params={
                "modules": "recommendationTrend",
                "corsDomain": "finance.yahoo.com",
                "formatted": "false",
            },
            timeout=5,
        )
        response.raise_for_status()
        return response.json()
    except requests.HTTPError:
        logger.exception(
            f"Failed to fetch data for symbol {symbol}. Status code: {response.status_code}"
        )
        return None