request.get works OUTSIDE of function but not INSIDE function

Viewed 51

I am trying to build my own function to pass a stock quote through a financial API and collect key financial ratios in a JSON response.

#import packages
import pandas as pd
import requests
import json

def financialratios(quote):
    Chrislink = 'https://financialmodelingprep.com/api/v3/financial-ratios/'+str(quote)
    print(Chrislink)
    print(str("Link is a ")+str(type(Chrislink)))
    fr = requests.get(Chrislink)
    fr = fr.json()

That is returning a 'None' result when I call it.

x = financialratios('AAPL')
print(x)

https://financialmodelingprep.com/api/v3/financial-ratios/AAPL
Link is a <class 'str'>
None

However, when I take all of this work OUTSIDE of the function, it returns the expected result...

quote = 'AAPL'
Chrislink = 'https://financialmodelingprep.com/api/v3/financial-ratios/'+str(quote)
print(Chrislink)
print(str("Link is a ")+str(type(Chrislink)))
fr = requests.get(Chrislink)
fr = fr.json()
fr

{'symbol': 'AAPL',
 'ratios': [{'date': '2019-09-28',
   'investmentValuationRatios': {'priceBookValueRatio': '10.666314697418441',
    'priceToBookRatio': '10.666314697418441',
    'priceToSalesRatio': '3.709723048190826',
    'priceEarningsRatio': '17.46730643441436',
    'receivablesTurnover': '11.34842536857716',
    'priceToFreeCashFlowsRatio': '16.38775951405868',
    'priceToOperatingCashFlowsRatio': '13.909202696891526',
    'priceCashFlowRatio': '13.909202696891526',
    'priceEarningsToGrowthRatio': '1.3549431647588217',
    'priceSalesRatio': '3.709723048190826',
    'dividendYield': '0.014628458229615355',
    'enterpriseValueMultiple': '13.31637596061561',
    'priceFairValue': '10.666314697418441'},
...

I am sure that I must be making some type of dumb mistake here, however, i am not quite sure what that mistake is. Any insight into why this would fail in a function but succeed outside of that function?

1 Answers

You have to return fr, from your function like this:

import pandas as pd
import requests
import json

def financialratios(quote):
    Chrislink = 'https://financialmodelingprep.com/api/v3/financial-ratios/'+str(quote)
    print(Chrislink)
    print(str("Link is a ")+str(type(Chrislink)))
    fr = requests.get(Chrislink)
    fr = fr.json()
    return fr

Hope this helps!

Related