首页 > 解决方案 > 如何使用 PyQ 和 Python 连接到 KDB 服务器?

问题描述

我正在使用 Python 2.7,并且在 Debian 10 下安装了 PyQ,并正确设置了 q(x64 版本)。

问题是如何连接到 KDB 服务器(我有凭据(IP、端口、用户和密码))?

标签: pythonkdbpyq

解决方案


启动 pyq 会话,切换到 q 解释器,然后使用hopen

Using the q interpreter in PyQ:
>>> q()
q)h:hopen `:localhost:1234 // `:host:port:user:pass
q)h"2+2"
q)4

编辑 - 来自 Python 和创建 Pandas.DataFrame 的更多示例:

I have the following table defined on my q server process:

q)tbl:([]col1:`a`b`c;col2:til 3)
q)tbl
col1 col2
---------
a    0   
b    1   
c    2 

Then from my client PyQ interpreter:

from pyq import q
import numpy as np # Numpy is needed as a middle man for interpreting kdb objects to python.
import pandas as pd
import datetime # if your kdb table has dates and times

q("h:hopen `:localhost:1234")
tbl2 = q("h\"tbl\"") # need to escape the quotes around tbl
tblNP = np.array(tbl2)
df = pd.DataFrame(tblNP)
df
  col1  col2
0    a     0
1    b     1
2    c     2

使用 qPython:

from qpython import qconnection
import pandas as pd

if __name__ == '__main__':
    # create connection object
    q = qconnection.QConnection(host='localhost', port=1234, pandas=True)
    # initialize connection
    q.open()

    # simple query execution via: QConnection.sendSync
    df = q.sendSync('tbl')
    # close connection
    q.close()

有关如何从表中选择特定数据的信息,请参阅qSQL。kdb 中的表可能非常大,选择整个表可能是不明智的。情商

PyQ:
tbl2 = q("h\"select from trades where date = 2020.02.14\"")
qPython:
df = q.sendSync('select from trades where date = 2020.02.14')

您是否打算在 q 中进行任何数据处理客户端?如果只是想从 kdb 服务器获取数据以用于 python,qPython可能是一个更好的选择。


推荐阅读