Wind Python案例

基础函数使用实例

本案例演示如何使用WindPy接口提取数据。代码示例如下:

from WindPy import w

w.start()
# 命令如何写可以用命令生成器来辅助完成
# 定义打印输出函数,用来展示数据使用
def printpy(outdata):
    if outdata.ErrorCode!=0:
        print('error code:'+str(outdata.ErrorCode)+'\n')
        return()
    for i in range(0,len(outdata.Data[0])):
        strTemp=''
        if len(outdata.Times)>1:
            strTemp=str(outdata.Times[i])+' '
        for k in range(0, len(outdata.Fields)):
            strTemp=strTemp+str(outdata.Data[k][i])+' '
        print(strTemp)

# 通过wsd来提取时间序列数据,比如取开高低收成交量,成交额数据
print('\n\n'+'-----通过wsd来提取时间序列数据,比如取开高低收成交量,成交额数据-----'+'\n')
wsddata1=w.wsd("000001.SZ", "open,high,low,close,volume,amt", "2015-11-22", "2015-12-22", "Fill=Previous")
printpy(wsddata1)

# 通过wsd来提取各个报告期财务数据
print('\n\n'+'-----通过wsd来提取各个报告期财务数据-----'+'\n')
wsddata2=w.wsd("600000.SH", "tot_oper_rev,tot_oper_cost,opprofit,net_profit_is", "2008-01-01", "2015-12-22", "rptType=1;Period=Q;Days=Alldays;Fill=Previous")
printpy(wsddata2)

# 通过wss来取截面数据
print('\n\n'+'-----通过wss来取截面数据-----'+'\n')
wssdata=w.wss("600000.SH,600007.SH,600016.SH", "ev,total_shares","tradeDate=20151222;industryType=1")
printpy(wssdata)

# 通过wst来取日内成交数据,最新7日内数据
print('\n\n'+'-----通过wst来取日内成交数据-----'+'\n')
wstdata=w.wst("IF.CFE", "last,volume", "2019-4-2 09:00:00", "2019-4-2 14:04:45")
printpy(wstdata)

# 通过wsi来取日内分钟数据,三年内数据
print('\n\n'+'-----通过wsi来取日内分钟数据-----'+'\n')
wsidata=w.wsi("IF.CFE", "open,high,low,close,volume,amt", "2018-12-22 09:00:00", "2018-12-22 14:06:15")
printpy(wsidata)

# 通过wset来取数据集数据
print('\n\n'+'-----通过wset来取数据集数据,获取沪深300指数权重-----'+'\n')
wsetdata=w.wset("IndexConstituent","date=20151222;windcode=000300.SH;field=date,wind_code,i_weight")
printpy(wsetdata)

输出DataFrame格式

本案例演示如何以DataFrame格式输出数据。在测试以下案例前,请确保已经安装了Pandas。

案例1. 输出WindData对象并转化为Pandas格式

# 案例1. 输出WindData对象并转化为Pandas格式
'''本案例以WSD接口为例,演示如何将输出的WindData转化为DataFrame。

WSD接口返回的WindData对象有以下几个字段:
    ErrorCode
    Codes
    Fields
    Times
    Data
其中,Data为返回的数据,Fields和Times分别为获取的指标名称和日期序列。
'''
from WindPy import w
import pandas as pd
import datetime

w.start()

# 取数据的命令如何写可以用命令生成器来辅助完成
wsd_data=w.wsd("000001.SZ", "open,high,low,close", "2015-12-10", "2015-12-22", "Fill=Previous")

if wsd_data.ErrorCode == 0:
  #演示如何将api返回的数据装入Pandas的Series
  open=pd.Series(wsd_data.Data[0])
  high=pd.Series(wsd_data.Data[1])
  low=pd.Series(wsd_data.Data[2])
  close=pd.Series(wsd_data.Data[3])

  print('open:/n',open)
  print('high:/n',high)
  print('low:/n',low)
  print('close:/n',close)

  #演示如何将api返回的数据装入Pandas的DataFrame
  fm=pd.DataFrame(wsd_data.Data,index=wsd_data.Fields,columns=wsd_data.Times)
  fm=fm.T #将矩阵转置
  print('fm:/n',fm)
else:
  print("Error Code:", wsd_data.ErrorCode)
  print("Error Message:", wsd_data.Data[0][0])


案例2. 量化接口直接输出DataFrame

# 案例2. 量化接口直接输出DataFrame
'''
通过在参数表中增加usedf=True,WindPy支持直接输出DataFrame格式。此时,WindPy函数返回错误码和提取的数据。其中数据的格式为DataFrame。
以下以WSD为例,展示如何使用WindPy函数以DataFrame格式提取数据:
'''
from WindPy import w
import pandas as pd
import datetime

w.start()
error_code, wsd_data=w.wsd("000001.SZ", "open,high,low,close", "2015-12-10", "2015-12-22", "Fill=Previous", usedf=True)

if error_code == 0:
  print(wsd_data)
else:
  print("Error Code:", error_code)
  print("Error Message:", wsd_data.iloc[0, 0])

订阅实时行情

案例1. 订阅实时行情,并存储到硬盘中

# 案例1. 订阅实时行情,并存储到硬盘中
'''本案例演示如何通过WSQ函数订阅实时行情数据,并存储到硬盘中。示例代码分为两个部分,一部分是用WSQ订阅所需的行情指标,另一部分定义了回调函数,用于处理实时推送的行情数据。在运行示例代码后,程序会一致运行。如果需要停止运行,可以输入"q"结束订阅并保存文件。

以下为示例Python代码:
'''
from WindPy import w
import os


def myCallback(indata: w.WindData):
    """Callback function for WSQ

    params
    ------
    indata: WindData, accepts the received market quotation data. WindData has the following fields: 
              .ErrorCode: error code, if it is 0, the code runs successfully
              .StateCode: state code. No need to process it.
              .RequestID: save the request ID of WSQ request
              .Codes: wind code of the securities 
              .Fields: fields for the received data
              .Times: local time rather than the corresponding time for the recieved data
              .Data: market quotation data
    """
    print(indata)
    if indata.ErrorCode!=0:
        print('error code:'+str(indata.ErrorCode)+'\n')
        return()

    global begintime
    lastvalue =""
    for k in range(0,len(indata.Fields)):
        if(indata.Fields[k] == "RT_TIME"):
            begintime = indata.Data[k][0]
        if(indata.Fields[k] == "RT_LAST"):
            lastvalue = str(indata.Data[k][0])

    string = str(begintime) + " " + lastvalue +"\n"
    pf.writelines(string)
    print(string)
    pf.flush()


start_ret = w.start()

if start_ret.ErrorCode != 0:
    print("Start failed")
    print("Error Code:", start_ret.ErrorCode)
    print("Error Message:", start_ret.Data[0])
else:
    # Open a file to write.
    pf = open('pywsqdataif.data', 'w')
    # Subscribe market quotation data
    wsq_ret = w.wsq("CN.SG","rt_time,rt_last",func=myCallback)

    if wsq_ret.ErrorCode != 0:
        print("Error Code:", wsq_ret.ErrorCode)

    ext = ''
    while ext != 'q':
      ext = input('Enter "q" to exit')

    w.cancelRequest(0)
    pf.close()

案例2. 订阅实时行情,并在界面中展示

# 案例2. 订阅实时行情,并在界面中展示
'''本案例将演示如何通过WSQ订阅实时行情,同时通过PyQt模块在界面中展示所订阅的两个品种的现价、盘口报价、成交量及部分订阅指标差值的信息。

详细的代码可以从本案例的附件中下载。以下只展示主脚本的代码:
'''
# quotedlg.py

from PyQt5.Qt import *
from PyQt5.QtCore import pyqtSlot as Slot
from WindPy import w
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import globaldef
import ui_quote
import wsq

w.start()

MAC = True
try:
    from PyQt5.QtGui import qt_mac_set_native_menubar
except ImportError:
    MAC = False


class QuoteDlg(QDialog, ui_quote.Ui_Dialog):

    def __init__(self, parent=None):
        super(QuoteDlg, self).__init__(parent)
        self.setupUi(self)
        self.sec1Edit.setFocus()
        self.setWindowTitle("Wind API Demo---WSQ Subscrib")
        self.updateUi()
        self.initGraph()

    def initGraph(self):
        self.scene = QGraphicsScene()
        self.dr = Figure_Canvas()
        self.scene.addWidget(self.dr)
        self.graphicsView.setScene(self.scene)

    @Slot()
    def on_subscribeButton_clicked(self):
        self.subscribeButton.setEnabled(False)
        self.cancelButton.setEnabled(True)
        self.textBrowser.clear()
        globaldef.secID = []
        globaldef.indID = []
        globaldef.secID.extend([self.sec1Edit.te
1 WINDPY接口说明 ................................................................................................. 1 1.1 WINDPY接口概述 ............................................................................................... 1 1.2 WINDPY接口安装 ............................................................................................... 2 1.2.1 WindPy对系统环境要求 ............................................................... 2 1.2.2 Python环境安装 .......................................................................... 2 1.2.3 正常WindPy接口安装 .................................................................. 3 1.2.4 特殊安装WindPy方式 .................................................................. 6 1.3 接口向导界面 ..................................................................................................... 6 1.4 WINDPY获取帮助途径 ....................................................................................... 7 1.4.1 本用户手册 .................................................................................... 7 1.4.2 量化交易群和R语言交流群 ........................................................... 7 1.5 WINDPY接口相关规范 ....................................................................................... 1 1.5.1 以下所有命令都有如下假设 ........................................................... 1 1.5.2 命令区分大小写,且“w.”不能省略 ............................................... 1 1.5.3 中文以及单字节码和双字节码的问题 ............................................. 1 1.5.4 品种、指标、参数等引号内的部分不区分大小写 ........................... 1 1.5.5 参数支持list输入 ...................................................................... 1 1.5.6 时间、日期支持Python语言的时间、日期格式 ........................... 2 1.5.7 参数中有缺省值的可以不用输入 .................................................... 2 1.5.8 可以带参数名输入 ......................................................................... 2 精于数据,一直进步 IV 1.5.9 Showblank参数 ........................................................................... 3 1.5.10 交易接口中Showfields参数................................................ 3 1.5.11 ErrorCode定义 .................................................................... 3 2 WIND PY插件命令说明 ....................................................................................... 1 2.1 FROM WINDPY IMPORT *:装载WINDPY包 ..................................................... 1 2.2 W.START:启动WINDPY ..................................................................................... 1 2.3 W.STOP:停止WINDPY ....................................................................................... 2 2.4 W.ISCONNECTED:判断是否已经登录 .............................................................. 2 2.5 W.CANCELREQUEST:取消订阅 .......................................................................... 2 2.6 W.WSD:获取历史序列数据 .............................................................................. 3 2.7 W.WSI:获取分钟数据 ...................................................................................... 3 2.8 W.WST:获取日内TICK级别数据 .................................................................... 4 2.9 W.WSS:获历史截面数据 .................................................................................. 5 2.10 W.WSQ:获取和订阅实时行情数据 ................................................................. 5 2.11 W.WSET:获取板块、指数等成分数据 ........................................................... 6 2.12 W.WEQS:获取条件选股结果 ............................................................................ 7 2.13 W.WPF:获取资产管理、组合管理数据 ......................................................... 7 2.14 交易相关函数 ..................................................................................................... 8 2.14.1 w.tlogon交易登录 ............................................................... 8 2.14.2 w.tlogout交易登出 ............................................................. 9 2.14.3 w.torder委托下单 ............................................................. 10 2.14.4 w.tcancel撤销委托 ........................................................... 11 精于数据,一直进步 V 2.14.5 w.tquery交易查询 ............................................................. 12 2.15 W.TDAYS, W.TDAYSOFFSET,W.TDAYSCOUNT:日期函数 ............................... 14 2.15.1 w.tdays:返回区间内的日期序列 ....................................... 14 2.15.2 w.tdaysoffset:返回某个偏移值对应的日期 ................... 14 2.15.3 w.tdayscount:返回某个区间内日期数量 ......................... 15 3 WINPY插件函数体说明........................................................................................ 1 3.1 日期序列(WSD)................................................................................................. 1 3.2 历史截面数据(WSS) ........................................................................................ 3 3.3 分钟序列(WSI)................................................................................................. 3 3.4 日内跳价(WST)................................................................................................. 4 3.5 实时数据(WSQ)................................................................................................. 5 3.6 数据集(WSET) ..............................................
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值