Recorrí una lista devuelta por una API y agarré 1.longName 2. RegularPrice 3.MarketCap que hice pero quiero que la capitalización de mercado devuelva 'mil millones de dólares' si es mayor o igual a 10 cifras también devuelve millones de dólares si es Menos de 10 cifras.

import requests
import pprint
import json



url = "https://yahoo-finance15.p.rapidapi.com/api/yahoo/ga/topgainers"

querystring = {"start":"0"}

headers = {
    'x-rapidapi-host': "yahoo-finance15.p.rapidapi.com",
    'x-rapidapi-key': "9efd0f3e52mshd859f5daf34a429p11cb2ajsn2b0e421d681e"
    }

response = requests.request("GET", url, headers=headers, params=querystring)
data = response.json()

#print(response.text)


def new_stock(data):
    new_market = []

    for item in data ['quotes']:
        new_name = item.get ('longName')
        new_price = item.get ('regularMarketPrice')
        res_price = (f'{new_price} Dollars')
        cap =item.get('marketCap')
        cap2 = str(cap)
        for i in cap2:
            if i == 1000000000:
                return(f'{cap2} Billion Dollars')
            else:
                return(f'{cap2} million Dollars')
        return cap2



        new_market.append((new_name, res_price, cap2))

    return new_market

value = new_stock(data)
dict = {i: value[i] for i in range(0, len(value))}
print(dict)

Entonces quiero un diccionario como

{Wienerberger AG', '4.38 Dollars', '2607606784 Billion Dollars} or {EPR Properties', '31.62 Dollars', '246636006 million Dollars}

0
ifeanyi omeifejideofor 29 abr. 2020 a las 19:05

3 respuestas

La mejor respuesta

2 cosas que modifiqué en tu código:

  1. compresión de valor
  2. función de retorno

Código:

    import requests
    import pprint
    import json
    url = "https://yahoo-finance15.p.rapidapi.com/api/yahoo/ga/topgainers"
    querystring = {"start":"0"}
    headers = {'x-rapidapi-host': "yahoo-finance15.p.rapidapi.com",'x-rapidapi-key': "9efd0f3e52mshd859f5daf34a429p11cb2ajsn2b0e421d681e"}
    response = requests.request("GET", url, headers=headers, params=querystring)
    data = response.json()
    def new_stock(data):
        new_market = []
        for item in data ['quotes']:
            new_name = item.get ('longName')
            new_price = item.get ('regularMarketPrice')
            res_price = (f'{new_price} Dollars')
            cap =item.get('marketCap')
            cap2 = int(cap)        
            if cap2>=1000000000:
                cap2 = f'{cap2} Billion Dollars'
            else:
                cap2 = f'{cap2} million Dollars'
            new_market.append((new_name, res_price, cap2))
        return new_market
    value = new_stock(data)
    dict = {i: value[i] for i in range(0, len(value))}
    print(dict)

Salida:

{0: ('Cimpress plc', '78.2325 Dollars', '2050129536 Billion Dollars'), 1: ('CaixaBank, S.A.', '0.636 Dollars', '12386608128 Billion Dollars'), 2: ('Park Hotels & Resorts Inc.', '10.7 Dollars', '2567807232 Billion Dollars'), 3: ('Norwegian Cruise Line Holdings Ltd.', '15.705 Dollars', '3348353280 Billion Dollars'), 4: ('Sabre Corporation', '7.42 Dollars', '2031269504 Billion Dollars'), 5: ('AerCap Holdings N.V.', '28.36 Dollars', '3731694080 Billion Dollars'), 6: ('Spirit AeroSystems Holdings, Inc.', '23.94 Dollars', '2508385280 Billion Dollars'), 7: ('Saia, Inc.', '99 Dollars', '2580266752 Billion Dollars'), 8: ('Ryman Hospitality Properties, Inc.', '37.56 Dollars', '2064669568 Billion Dollars'), 9: ('DNB ASA', '12.06 Dollars', '18676477952 Billion Dollars'), 10: ('Alliance Data Systems Corporation', '54.7384 Dollars', '2607025664 Billion Dollars'), 11: ('OneMain Holdings, Inc.', '26.38 Dollars', '3543097600 Billion Dollars'), 12: ('Fox Factory Holding Corp.', '56.2175 Dollars', '2170147328 Billion Dollars'), 13: ('CarGurus, Inc.', '23.31 Dollars', '2625498368 Billion Dollars'), 14: ('Builders FirstSource, Inc.', '19.81 Dollars', '2300535296 Billion Dollars'), 15: ('Air Lease Corporation', '26.33 Dollars', '2992009472 Billion Dollars'), 16: ('Lattice Semiconductor Corporation', '22.38 Dollars', '3008431104 Billion Dollars'), 17: ('Discover Financial Services', '45.66 Dollars', '13982827520 Billion Dollars'), 18: ('Penn National Gaming, Inc.', '18.14 Dollars', '2122452480 Billion Dollars'), 19: ('Companhia Siderurgica Nacional', '1.56 Dollars', '2037796608 Billion Dollars'), 20: ("Aaron's, Inc.", '31.78 Dollars', '2121140224 Billion Dollars'), 21: ('Paycom Software, Inc.', '269.235 Dollars', '15839551488 Billion Dollars'), 22: ('Nexstar Media Group, Inc.', '76.9 Dollars', '3526603264 Billion Dollars'), 23: ('Blackstone Mortgage Trust, Inc.', '23.8 Dollars', '3221472768 Billion Dollars'), 24: ('Centrica plc', '2.014 Dollars', '2800688640 Billion Dollars')}
1
Vishal Upadhyay 29 abr. 2020 a las 16:36

Esa no es realmente la forma de usar return en su función si el resultado esperado será una lista. Lo he corregido a:

def new_stock(data):
    new_market = []

    for item in data ['quotes']:
        new_name = item.get ('longName')
        new_price = item.get ('regularMarketPrice')
        res_price = (f'{new_price} Dollars')
        cap =item.get('marketCap')
        if cap >= 1000000000:
            cap=f'{cap} Billion Dollars'
        else:
            cap=f'{cap} million Dollars'
        new_market.append((new_name, res_price, cap))

    return new_market
0
0buz 29 abr. 2020 a las 16:18

Por lo que observo, su problema es específicamente esta línea

if i == 1000000000:
    return(f'{cap2} Billion Dollars')

El problema con esto es que Billion Dollars solo se agregará si i es exactamente igual a 1000000000 Lo que debes escribir en su lugar, es:

if i >= 1000000000:
    return(f'{cap2} Billion Dollars')

Esto asegura que los valores superiores a 1000000000 también se capturen.

0
Luke-zhang-04 29 abr. 2020 a las 16:10