【问题标题】:Looping through stock market API using python使用python循环股市API
【发布时间】:2020-08-04 10:14:06
【问题描述】:

我希望您希望循环遍历来自 yahoo Finance api 的结果,以返回公司名称和股票价格以获得最高收益者。

    import requests
    import pprint


    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)
    new_response = response.text




    def new_stock(one_stock):
       arranged = []
      for items in (one_stock):
        new_name = dict.get("regularMarketPrice")
        result = arranged.append(one_stock)
        return result

   print(new_stock(new_response))

但它一直返回此错误

      'File "monitor.py", line 27, in <module>
           print(new_stock(new_response))
          File "monitor.py", line 23, in new_stock
           new_name = dict.get("regularMarketPrice")
           TypeError: descriptor 'get' requires a 'dict' object but received a 'str'

【问题讨论】:

  • 先见print(response.text)。如果您期望 JSON 数据,那么您可能必须使用模块 json 将字符串转换为字典。或使用new_response = response.json()
  • 您还应该检查您在字典中得到的内容 - 您得到的是嵌套字典。如果值在data["A"]["B"]["regularMarketPrice"] 中,则无法直接使用.get("regularMarketPrice") 获取,但必须使用["A"]["B"]["regularMarketPrice"]
  • 顺便说一句:append() 不会创建新列表,它会返回None 所以result = arranged.append(one_stock) 表示result = None,你应该使用return arranged 而不是return result
  • 其他错误 - 你应该append(new_name),而不是append(one_stock)

标签: python


【解决方案1】:

你的错误很少


如果您需要 JSON 数据,请使用 response.json() 而不是 response.text

data = response.json()

.text 给出字符串,您必须使用模块json 将其转换为 python 字典

import json

data = json.loads(response.text)

你得到嵌套数据,你需要使用data['quotes'] 来获取结果列表。

for item in data['quotes']:
    #print(item.keys())

    name = item.get("shortName")
    price = item.get("regularMarketPrice")

append() 不会创建新列表并返回 `None so

 result = arranged.append(one_stock)

意思

 result = None

你应该使用

arranged.append(one_stock)

以后

return arranged

你应该附加你得到的值,而不是one_stock

arranged.append( (name, price) )

工作代码

import requests
import pprint

# --- functions ---

def new_stock(data):
    result = []

    for item in data['quotes']:
        #print(item.keys())
        name = item.get("shortName")
        price = item.get("regularMarketPrice")

        result.append((name, price))

    return result

# --- main ---

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()

#pprint.pprint(data)

pprint.pprint(new_stock(data))

结果:

[('ROLLS ROYCE HOLDINGS NON CUM RE', 0.0048),
 ('CIELO SA', 0.914),
 ('ASX LTD', 51.45),
 ('FLIR Systems, Inc.', 42.735),
 ('EQUATORIAL ENERGIA SA', 3.87),
 ('LOCALIZA RENT A CAR SA', 6.961),
 ('ADYEN NV UNSPON ADS EACH REP 0.', 18.64),
 ('Beyond Meat, Inc.', 84.35),
 ('SIKA AG', 17.025),
 ('Equifax, Inc.', 133.01),
 ('FUJI ELECTRIC CO. LTD.', 5.88),
 ('New Residential Investment Corp', 5.265),
 ('ENAGAS SA', 10.8301),
 ('THAI BEVERAGE PUBLIC COMPANY LT', 0.4749),
 ('ManpowerGroup', 64.61),
 ('Viela Bio, Inc.', 40.8),
 ('BANCO ACTINVER SA', 0.8351),
 ('Simmons First National Corporat', 18.3182),
 ('Suzano S.A.', 6.75),
 ('New Oriental Education & Techno', 113.04),
 ('PEUGEOT SA', 12.7148),
 ('The Madison Square Garden Compa', 237.22),
 ('FLUTTER ENTERTAINMENT PLC UNSPO', 56.65)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2013-01-20
    • 2016-06-06
    • 1970-01-01
    相关资源
    最近更新 更多