Python如何调用港股行情接口

1. 接口信息

接口类型:实时综合行情接口
支持品种:贵金属,商品期货,外汇,A股,港股,美股
查询方式:HTTP, WebSocket
申请密钥:https://infoway.io
官方对接文档:https://infoway.readme.io/reference/ws-subscription

2. 获取股票清单

这个接口用来查询股票的名单,比如我可以获取美股清单:

import requests

url = "https://data.infoway.io/common/basic/symbols?type=STOCK_HK"

headers = {"accept": "application/json"}

response = requests.get(url, headers=headers)

print(response.text)

只需要在type中传入STOCK_US,或者STOCK_CN即可查询所有美股或A股的清单。

3. 批量获取股票K线

这个接口用来获取多只股票的K线,请求地址:

https://data.infoway.io/stock/batch_kline/{klineType}/{klineNum}/{codes}

# {klineType} 是K线的时间
# 1 = 1分钟k线
# 2	= 5分钟k线
# 3 = 15分钟k线
# 4	= 30分钟k线
# 5	= 1小时k线
# 6	= 2小时k线
# 7	= 4小时k线
# 8	= 1日k线
# 9	= 1周k线
# 10	= 1月k线
# 11	= 1季k线
# 12	= 1年k线

# {klineNum}是需要返回的K线数量,最大支持一次性返回500根K线

可以跨市场查询,比如同时获取A股,港股和美股的个股K线:

import requests

api_url = 'https://data.infoway.io/stock/batch_kline/1/10/002594.SZ%2C00285.HK%2CTSLA.US'

# 申请免费密钥: https://infoway.io
# 设置请求头
headers = {
    'User-Agent': 'Mozilla/5.0',
    'Accept': 'application/json',
    'apiKey': 'yourApikey'
}

# 发送GET请求
response = requests.get(api_url, headers=headers)

# 输出结果
print(f"HTTP code: {response.status_code}")
print(f"message: {response.text}")

4. 查询股票盘口

这个接口用于查询股票的交易盘口,最大支持5档盘口查询:

import requests

url = "https://data.infoway.io/stock/batch_depth/002594.SZ%2C00285.HK%2CTSLA.US%2CAUDCAD%2CHK50%2CXNIUSD"

# 申请免费密钥: https://infoway.io
# 设置请求头

headers = {
    'User-Agent': 'Mozilla/5.0',
    'Accept': 'application/json',
    'apiKey': 'yourApikey'
}

response = requests.get(url, headers=headers)

print(response.text)

5. WebSocket订阅实时股票行情

以上介绍的是HTTP请求,这种方式存在一定的延时,在实盘交易中推荐使用WebSocket来获取实时的行情推送。WebSocket的优势是和服务器建立一个长连接,只要连接不断开都会收到来自服务器的数据推送,延时一般在120ms以内。而你只需要每隔一分钟向服务器发送一个心跳来保活即可。下面是WebSocket的代码示例,虽然是查询的贵金属,但原理是一样的:

import json
import time
import schedule
import threading
import websocket
from loguru import logger

class WebsocketExample:
    def __init__(self):
        self.session = None
        # 申请免费API Key: https://infoway.io
        self.ws_url = "wss://data.infoway.io/ws?business=common&apikey=YourAPIKey" 
        self.reconnecting = False
        self.last_ping_time = 0
        self.max_ping_interval = 30  # 最大心跳包间隔时间
        self.retry_attempts = 0  # 重试次数
        self.max_retry_attempts = 5  # 最大重试次数

    def connect_all(self):
        """建立WebSocket连接并启动自动重连机制"""
        try:
            self.connect(self.ws_url)
            self.start_reconnection(self.ws_url)
        except Exception as e:
            logger.error(f"Failed to connect to {self.ws_url}: {str(e)}")

    def start_reconnection(self, url):
        """启动定时重连检查"""
        def check_connection():
            if not self.is_connected():
                logger.debug("Reconnection attempt...")
                self.retry_attempts += 1
                if self.retry_attempts <= self.max_retry_attempts:
                    self.connect(url)
                else:
                    logger.error("Exceeded max retry attempts.")
        
        # 使用线程定期检查连接状态
        threading.Thread(target=lambda: schedule.every(10).seconds.do(check_connection), daemon=True).start()

    def is_connected(self):
        """检查WebSocket连接状态"""
        return self.session and self.session.connected

    def connect(self, url):
        """建立WebSocket连接"""
        try:
            if self.is_connected():
                self.session.close()
            
            self.session = websocket.WebSocketApp(
                url,
                on_open=self.on_open,
                on_message=self.on_message,
                on_error=self.on_error,
                on_close=self.on_close
            )
            
            # 启动WebSocket连接(非阻塞模式)
            threading.Thread(target=self.session.run_forever, daemon=True).start()
        except Exception as e:
            logger.error(f"Failed to connect to the server: {str(e)}")

    def on_open(self, ws):
        """WebSocket连接建立成功后的回调"""
        logger.info(f"Connection opened")
        
        try:
            # 发送贵金属实时成交明细订阅请求
            trade_send_obj = {
                "code": 10000,
                "trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
                "data": {"codes": "XAUUSD"}  # XAUUSD 为贵金属黄金(黄金/美元)
            }
            self.send_message(trade_send_obj)
            
            # 不同请求之间间隔一段时间
            time.sleep(5)
            
            # 发送贵金属实时盘口数据订阅请求
            depth_send_obj = {
                "code": 10003,
                "trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
                "data": {"codes": "XAUUSD"}  # XAUUSD为黄金的实时盘口数据
            }
            self.send_message(depth_send_obj)
            
            # 不同请求之间间隔一段时间
            time.sleep(5)
            
            # 发送贵金属实时K线数据订阅请求
            kline_data = {
                "arr": [
                    {
                        "type": 1,
                        "codes": "XAUUSD"  # XAUUSD 为黄金K线数据
                    }
                ]
            }
            kline_send_obj = {
                "code": 10006,
                "trace": "01213e9d-90a0-426e-a380-ebed633cba7a",
                "data": kline_data
            }
            self.send_message(kline_send_obj)
            
            # 启动定时心跳任务
            threading.Thread(target=lambda: schedule.every(30).seconds.do(self.ping), daemon=True).start()
            
        except Exception as e:
            logger.error(f"Error sending initial messages: {str(e)}")

    def on_message(self, ws, message):
        """接收消息的回调"""
        try:
            logger.info(f"Message received: {message}")
        except Exception as e:
            logger.error(f"Error processing message: {str(e)}")

    def on_close(self, ws, close_status_code, close_msg):
        """连接关闭的回调"""
        logger.info(f"Connection closed: {close_status_code} - {close_msg}")

    def on_error(self, ws, error):
        """错误处理的回调"""
        logger.error(f"WebSocket error: {str(error)}")

    def send_message(self, message_obj):
        """发送消息到WebSocket服务器"""
        if self.is_connected():
            try:
                self.session.send(json.dumps(message_obj))
            except Exception as e:
                logger.error(f"Error sending message: {str(e)}")
        else:
            logger.warning("Cannot send message: Not connected")

    def ping(self):
        """发送心跳包"""
        current_time = time.time()
        if current_time - self.last_ping_time >= self.max_ping_interval:
            ping_obj = {
                "code": 10010,
                "trace": "01213e9d-90a0-426e-a380-ebed633cba7a"
            }
            self.send_message(ping_obj)
            self.last_ping_time = current_time
        else:
            logger.debug(f"Ping skipped: Time interval between pings is less than {self.max_ping_interval} seconds.")

# 使用示例
if __name__ == "__main__":
    ws_client = WebsocketExample()
    ws_client.connect_all()
    
    # 保持主线程运行
    try:
        while True:
            schedule.run_pending()
            time.sleep(1)
    except KeyboardInterrupt:
        logger.info("Exiting...")
        if ws_client.is_connected():
            ws_client.session.close()            

6. 常见问题

HTTP和WebSocket有什么区别?

通过HTTP请求,返回的数据是基于请求和响应传输的。客户端向服务器发送请求,服务器返回响应。每次请求/响应都必须是完整的。而WebSocket的数据是全双工的,客户端和服务器可以随时向对方发送数据,也就是所谓的长连接。它更适用于实时通信,因为一旦连接建立,可以保持双向流量。

港股的延迟是多少?

这个和接口的设计有关,一般通过WebSocket获取的数据,延迟在100ms左右。

<think>好的,我需要帮助用户查找Python中访问问财股票数据的API接口及其使用方法。首先,我需要回顾用户提供的引用内容,看看是否有相关的信息。 根据引用[2],用户提到已经安装好了stockapi,可以通过HTTP请求获取数据,包括选股、技术指标、龙虎榜数据等。网址是https://stockapi.com.cn。这可能是一个可用的接口。另外,引用[3]提到了ContextInfo.get_financial_data的用法,但具体参数和来源不明确,可能属于某个特定的库或框架,需要进一步确认。 接下来,我应该整理这些信息,分步骤说明如何使用这些API接口。首先,引用[2]中的HTTP请求方法可能较为直接,适合大部分用户使用。需要给出具体的代码示例,比如使用requests库发送GET请求,并处理返回的数据。同时,要提醒用户可能需要注册获取API密钥,并注意请求频率限制。 对于引用[3]中的方法,可能存在上下文依赖,比如属于某个特定的Python库,用户可能需要安装相应的库或模块才能使用。需要建议用户查阅相关文档,或者提供更多的上下文信息。 此外,用户可能遇到的常见问题,比如安装问题或数据解析错误,也需要在注意事项中提及。同时,可以建议用户参考官方文档或社区支持以解决更复杂的问题。 最后,生成相关问题,帮助用户进一步探索,比如如何获取实时数据、处理数据或常见的错误解决方法。这样用户可以按图索骥,逐步解决问题。</think>### Python问财股票API接口使用方法 以下是基于站内引用整理的Python访问问财股票数据的API接口使用方法: #### 方法1:通过HTTP请求直接调用(推荐) ```python import requests # 示例:获取股票技术指标数据 url = "https://stockapi.com.cn/ai" params = { "type": "tech", # 数据类型(技术指标、龙虎榜等) "code": "000001", # 股票代码 "start": "20230101", # 开始日期 "end": "20231231" # 结束日期 } response = requests.get(url, params=params) data = response.json() # 返回JSON格式数据 print(data) ``` *注意:实际使用时需注册获取API密钥,并遵守频率限制[^2]。* #### 方法2:使用封装好的接口(需安装库) ```python from stockapi import ContextInfo # 获取财务数据示例 financial_data = ContextInfo.get_financial_data( tabname='income_statement', # 表名(利润表、资产负债表等) colname='net_profit', # 列名(净利润、营业收入等) market='SZ', # 市场标识 code='000001', # 股票代码 barpos=0 # 时间偏移量 ) ``` *注:需先安装对应库并配置认证信息[^3]。* ### 关键参数说明 | 参数类型 | 常见值示例 | 说明 | |----------------|--------------------------|------------------------------| | 接口类型 | `tech`/`bidding`/`lh` | 技术指标/竞价数据/龙虎榜 | | 市场标识 | `SH`/`SZ`/`HK` | 上海/深圳/港股市场 | | 时间格式 | `YYYYMMDD` | 统一使用8位数字日期格式 | ### 注意事项 1. 接口认证:大多数API需要`API-Key`和`Secret`进行身份验证 2. 频率限制:免费接口通常限制为5-10次/秒[^2] 3. 数据格式:返回数据多为JSON格式,建议使用`pandas`进行结构化处理 4. 错误处理:需添加`try-except`块处理网络异常
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值