一、前言
1、在量化交易中,行情数据是至关重要的。量化交易是利用算法和数学模型进行交易决策的过程,而行情数据是提供市场信息的基础,为了实现这一目标,许多开发者和交易者依赖于各种免费股票数据API,股票数据API还需要包含股票价格、成交量、市值、股票tick数据以及其他与交易相关的数据,
2、但是问题来了,在众多语言中,那种最快最适合?无疑是Python语言,Python语言接入股票数据API的好处是简单易用:Python是一种高级、可读性强且易学的编程语言,具有简洁的语法和丰富的标准库。下面将通过这个方法开展,让各位需要股票数据API来做量化交易的战友们提供一些帮助。

二、实战-通过python语言接入实时股票行情数据的步骤

2.1 请求K线数据
各类K线数据用于策略的回测,具体的策略此处不谈,下面直接介绍使用AllTick的已经封装好的API直接调用做为例子,下面上代码:
免费注册token:https://alltick.co
项目在github上:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api

import time
import requests
import json
 
# Extra headers
test_headers = {
    'Content-Type':'application/json'
}
 
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co
将如下JSON进行url的encode,复制到http的查询字符串的query字段里
{"trace":"python_http_test1","data":{"code":"AAPL.US","kline_type":1,"kline_timestamp_end":0,"query_kline_num":2,"adjust_type":0}}
'''
test_url1 = 'https://quote.tradeswitcher.com/quote-stock-b-api/kline?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806&query=%7B%22trace%22%3A%22python_http_test1%22%2C%22data%22%3A%7B%22code%22%3A%22AAPL.US%22%2C%22kline_type%22%3A1%2C%22kline_timestamp_end%22%3A0%2C%22query_kline_num%22%3A2%2C%22adjust_type%22%3A0%7D%7D'
 
resp1 = requests.get(url=test_url1, headers=test_headers)
 
# Decoded text returned by the request
text1 = resp1.text
print(text1)

2.2 请求最新成交报价数据
获取最新成交报价数据对于量化策略的分析和判断至关重要。接下来,我将分享如何直接获取这些数据的代码示例:

import time
import requests
import json
 
# Extra headers
test_headers = {
    'Content-Type':'application/json'
}
 
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co
将如下JSON进行url的encode,复制到http的查询字符串的query字段里
{"trace":"python_http_test2","data":{"symbol_list":[{"code": "700.HK"},{"code": "UNH.US"},{"code": "600416.SH"}]}}
'''
test_url1 = 'https://quote.tradeswitcher.com/quote-stock-b-api/trade-tick?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806&query=%7B%22trace%22%3A%22python_http_test2%22%2C%22data%22%3A%7B%22symbol_list%22%3A%5B%7B%22code%22%3A%20%22700.HK%22%7D%2C%7B%22code%22%3A%20%22UNH.US%22%7D%2C%7B%22code%22%3A%20%22600416.SH%22%7D%5D%7D%7D'
 
resp1 = requests.get(url=test_url1, headers=test_headers)
 
# Decoded text returned by the request
text1 = resp1.text
print(text1)

上面代码中symbol_list是可以同时传入多个的,分别传入不同的市场的产品也是可以的。

2.3、获取最新盘口报价数据

import time
import requests
import json
 
# Extra headers
test_headers = {
    'Content-Type':'application/json'
}
 
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co
将如下JSON进行url的encode,复制到http的查询字符串的query字段里
{"trace":"python_http_test2","data":{"symbol_list":[{"code": "700.HK"},{"code": "UNH.US"},{"code": "600416.SH"}]}}
'''
test_url1 = 'https://quote.tradeswitcher.com/quote-stock-b-api/depth-tick?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806&query=%7B%22trace%22%3A%22python_http_test2%22%2C%22data%22%3A%7B%22symbol_list%22%3A%5B%7B%22code%22%3A%20%22700.HK%22%7D%2C%7B%22code%22%3A%20%22UNH.US%22%7D%2C%7B%22code%22%3A%20%22600416.SH%22%7D%5D%7D%7D'
 
resp1 = requests.get(url=test_url1, headers=test_headers)
 
# Decoded text returned by the request
text1 = resp1.text
print(text1)

上面代码中symbol_list是可以同时传入多个的,分别传入不同的市场的产品也是可以的。

2.4、通过websockety订阅获取实时股票行情数据

import json
import websocket    # pip install websocket-client
 
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co
'''
 
class Feed(object):
 
    def __init__(self):
        self.url = 'wss://quote.tradeswitcher.com/quote-stock-b-ws-api?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806'  # 这里输入websocket的url
        self.ws = None
 
    def on_open(self, ws):
        """
        Callback object which is called at opening websocket.
        1 argument:
        @ ws: the WebSocketApp object
        """
        print('A new WebSocketApp is opened!')
 
        # 开始订阅(举个例子)
        sub_param = {
            "cmd_id": 22002, 
            "seq_id": 123,
            "trace":"3baaa938-f92c-4a74-a228-fd49d5e2f8bc-1678419657806",
            "data":{
                "symbol_list":[
                    {
                        "code": "700.HK",
                        "depth_level": 5,
                    },
                    {
                        "code": "UNH.US",
                        "depth_level": 5,
                    },
                    {
                        "code": "600416.SH",
                        "depth_level": 5,
                    }
                ]
            }
        }
        
        #如果希望长时间运行,除了需要发送订阅之外,还需要修改代码,定时发送心跳,避免连接断开,具体查看接口文档
        sub_str = json.dumps(sub_param)
        ws.send(sub_str)
        print("depth quote are subscribed!")
 
    def on_data(self, ws, string, type, continue_flag):
        """
        4 argument.
        The 1st argument is this class object.
        The 2nd argument is utf-8 string which we get from the server.
        The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.
        The 4th argument is continue flag. If 0, the data continue
        """
 
    def on_message(self, ws, message):
        """
        Callback object which is called when received data.
        2 arguments:
        @ ws: the WebSocketApp object
        @ message: utf-8 data received from the server
        """
        # 对收到的message进行解析
        result = eval(message)
        print(result)
 
    def on_error(self, ws, error):
        """
        Callback object which is called when got an error.
        2 arguments:
        @ ws: the WebSocketApp object
        @ error: exception object
        """
        print(error)
 
    def on_close(self, ws, close_status_code, close_msg):
        """
        Callback object which is called when the connection is closed.
        2 arguments:
        @ ws: the WebSocketApp object
        @ close_status_code
        @ close_msg
        """
        print('The connection is closed!')
 
    def start(self):
        self.ws = websocket.WebSocketApp(
            self.url,
            on_open=self.on_open,
            on_message=self.on_message,
            on_data=self.on_data,
            on_error=self.on_error,
            on_close=self.on_close,
        )
        self.ws.run_forever()
 
 
if __name__ == "__main__":
    feed = Feed()
    feed.start()

上面的代码展示了如何通过API订阅实时股票数据。在代码中,symbol_list表示你要订阅的产品列表,你可以同时传入多个市场的多个产品进行订阅。通过设置cmd_id为22002,你可以订阅盘口数据,而设置cmd_id为22004时,则是订阅成交报价数据。一旦订阅成功,实时股票行情数据就会不断地推送过来,并且是实时更新的。

三、总结

这种方法为股票量化交易提供了一种免费获取实时股票数据的途径。通过订阅数据,你可以及时获取到最新的市场行情,为你的量化交易策略提供支持和决策依据。无论是分析价格走势、计算指标还是进行交易信号的生成,实时数据的获取对于量化交易至关重要。

要注意的是,订阅实时股票数据需要确保代码的稳定性和可靠性。你应该处理连接中断、数据异常等情况,并进行相应的错误处理和容错机制。同时,还要了解数据提供商的使用限制和许可要求,遵守相关的使用条款和规定。

综上所述,通过上述代码示例和订阅实时股票数据的方法,你可以免费获取并实时接收股票行情数据。这为量化交易提供了一个经济实惠且可行的途径,帮助你更好地进行交易决策和策略优化。记住,在实践中,要不断学习和改进你的量化交易系统,以适应不断变化的市场环境。

好了。今天的技术干货就分享到这里,感谢大家支持。


量化集结者
1 声望1 粉丝