如何使用接口查询A股上市公司股价

import time
import requests
import json

# Extra headers
test_headers = {
    'Content-Type': 'application/json'
}

'''
# Special Note:
# GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
# Token Application: https://alltick.co
# Replace "testtoken" in the URL below with your own token
# API addresses for forex, cryptocurrencies, and precious metals:
# https://quote.tradeswitcher.com/quote-b-ws-api
# Stock API address:
# https://quote.tradeswitcher.com/quote-stock-b-ws-api
Encode the following JSON and copy it to the "query" field of the HTTP query string
{"trace": "python_http_test1", "data": {"code": "600519.SH", "kline_type": 1, "kline_timestamp_end": 0, "query_kline_num": 2, "adjust_type": 0}}
{"trace": "python_http_test2", "data": {"symbol_list": [{"code": "600519.SH"}]}}
{"trace": "python_http_test3", "data": {"symbol_list": [{"code": "600519.SH"}]}}
'''
test_url1 = 'https://quote.tradeswitcher.com/quote-stock-b-api/kline?token=testtoken&query=%7B%22trace%22%20%3A%20%22python_http_test1%22%2C%22data%22%20%3A%20%7B%22code%22%20%3A%20%22600519.SH%22%2C%22kline_type%22%20%3A%201%2C%22kline_timestamp_end%22%20%3A%200%2C%22query_kline_num%22%20%3A%202%2C%22adjust_type%22%3A%200%7D%7D'
test_url2 = 'https://quote.tradeswitcher.com/quote-stock-b-api/depth-tick?token=testtoken&query=%7B%22trace%22%20%3A%20%22python_http_test2%22%2C%22data%22%20%3A%20%7B%22symbol_list%22%3A%20%5B%7B%22code%22%3A%20%22600519.SH%22%7D%5D%7D%7D'
test_url3 = 'https://quote.tradeswitcher.com/quote-stock-b-api/trade-tick?token=testtoken&query=%7B%22trace%22%20%3A%20%22python_http_test3%22%2C%22data%22%20%3A%20%7B%22symbol_list%22%3A%20%5B%7B%22code%22%3A%20%22600519.SH%22%7D%5D%7D%7D'

resp1 = requests.get(url=test_url1, headers=test_headers)
time.sleep(1)
resp2 = requests.get(url=test_url2, headers=test_headers)
time.sleep(1)
resp3 = requests.get(url=test_url3, headers=test_headers)

# Decoded text returned by the request
text1 = resp1.text
print(text1)

text2 = resp2.text
print(text2)

text3 = resp3.text
print(text3)

导入库

  • time 用于延迟请求的发送。
  • requests 用于发送HTTP请求。
  • json 用于处理 JSON 格式的数据。

设置请求头

  • 定义 test_headers 字典,将请求头的 Content-Type 设置为 application/json,这表示发送的数据格式为 JSON。

定义请求的 URL

  • test_url1: 获取茅台(600519.SH)股票的K线数据。请求参数包括代码、K线类型、结束时间戳、请求K线条数和复权类型。
  • test_url2: 获取茅台股票的深度数据。请求参数仅包含股票代码。
  • test_url3: 获取茅台股票的逐笔成交数据。请求参数也是股票代码。
  • 各URL中 token=testtoken 表示请求需要验证身份,实际使用时应替换为有效的 API Token。

发送请求并延时

  • 使用 requests.get 方法向各个URL发送 GET 请求。
  • 每个请求发送后,调用 time.sleep(1),让程序暂停1秒,避免请求过快。
  • 返回的响应对象被存储在 resp1resp2resp3 中。

解析和打印响应

  • resp1.textresp2.textresp3.text 获取的是各请求返回的文本内容(JSON 格式)。
  • print 函数将结果打印到控制台,分别输出K线数据、深度数据和逐笔成交数据,方便查看每个接口的返回值。

详细接口文档

猜你喜欢

转载自blog.csdn.net/qq_34102871/article/details/142917885