Nuggets Quantification—Python SDK Documentation—1. Quick Start

The Nuggets Quantitative Terminal is a full-featured floor-standing terminal for professional quantitative investment. It integrates modular functions from strategy development to firm offerings, connects research, simulation and performance links, and is compatible with multiple programming languages. It is easy to use, Reliable performance can help quantitative investors improve strategy development efficiency and reduce IT investment.

The Nuggets Quantitative Terminal currently only supports the use in the Windows environment. In order to ensure stable operation, it is recommended to use at least the following configurations:

Nuggets quantification supports four programming languages: python, matlab, C++, and C#. Backtesting and simulation can only be performed after installing a special Nuggets SDK. The following is the introduction of the Python SDK for beginners' reference.


Table of contents

Python SDK Documentation

1. Quick start

Timing task example

Data Event Driven Example

Time Series Data Event-Driven Example

Select backtest mode/live mode to run the example

Extract Data Study Example

Example of high-speed data processing in backtest mode

Example of dynamic parameters in real-time mode

level2 data-driven event example

Convertible bond data acquisition/transaction example


Python SDK Documentation

1. Quick start

Common policy structures mainly include three types, as shown in the following figure.

Users can choose the corresponding strategy structure according to the strategy requirements. For details, please refer to the classic strategy .

Timing task example

The content of the following code is: buy 200 shares of Shanghai Pudong Development Bank at the market price at 14:50:00 of each trading day:

# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *


def init(context):
    # 每天14:50 定时执行algo任务,
    # algo执行定时任务函数,只能传context参数
    # date_rule执行频率,目前暂时支持1d、1w、1m,其中1w、1m仅用于回测,实时模式1d以上的频率,需要在algo判断日期
    # time_rule执行时间, 注意多个定时任务设置同一个时间点,前面的定时任务会被后面的覆盖
    schedule(schedule_func=algo, date_rule='1d', time_rule='14:50:00')



def algo(context):
    # 以市价购买200股浦发银行股票, price在市价类型不生效
    order_volume(symbol='SHSE.600000', volume=200, side=OrderSide_Buy,
                 order_type=OrderType_Market, position_effect=PositionEffect_Open, price=0)


# 查看最终的回测结果
def on_backtest_finished(context, indicator):
    print(indicator)


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='strategy_id',
        filename='main.py',
        mode=MODE_BACKTEST,
        token='token_id',
        backtest_start_time='2020-11-01 08:00:00',
        backtest_end_time='2020-11-10 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)

copy successfully

The whole strategy requires three steps:

  1. Set the initialization function:  init  , use  the schedule  function for timing task configuration
  2. Configure the task, and the task will be executed at the point
  3. execution strategy

Data Event Driven Example

After using the subscribe() interface to subscribe to the target, the background will return tick data or bar data. Every time one or a set of data is generated, it will automatically trigger the execution of the content in on_tick() or on_bar(). For example, the following sample code snippet subscribes to the bar data of Shanghai Pudong Development Bank with a frequency of 1 day and 60s. Every time a bar is generated, the on_bar() call will be automatically triggered to print the obtained bar information:

# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *


def init(context):
    # 订阅浦发银行, bar频率为一天和一分钟
    # 订阅订阅多个频率的数据,可多次调用subscribe
    subscribe(symbols='SHSE.600000', frequency='1d')
    subscribe(symbols='SHSE.600000', frequency='60s')


def on_bar(context, bars):

    # 打印bar数据
    print(bars)


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='strategy_id',
        filename='main.py',
        mode=MODE_BACKTEST,
        token='token_id',
        backtest_start_time='2020-11-01 08:00:00',
        backtest_end_time='2020-11-10 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)


copy successfully

The whole strategy requires three steps:

  1. Set the initialization function: init, use the subscribe function for data subscription
  2. Implement a function: on_bar, to perform logic processing based on data push
  3. execution strategy

Time Series Data Event-Driven Example

The data window size and period are specified when the strategy subscribes to the code, and the platform creates a data sliding window, loads the initial data, and automatically refreshes the data when a new bar arrives.

When the on_bar event is triggered, the strategy can get the prepared time series data of the subscription code through context.data.

The following sample code snippet is a very simple example, subscribe to Shanghai Pudong Development Bank's daily line and minute bar, the update of bar data will automatically trigger the call of on_bar, each call to get the latest 50 minute bar information context.data:

# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *


def init(context):
    # 订阅浦发银行, bar频率为一天和一分钟
    # 指定数据窗口大小为50
    # 订阅订阅多个频率的数据,可多次调用subscribe
    subscribe(symbols='SHSE.600000', frequency='1d', count=50)
    subscribe(symbols='SHSE.600000', frequency='60s', count=50)


def on_bar(context, bars):
    # context.data提取缓存的数据滑窗, 可用于计算指标
    # 注意:context.data里的count要小于或者等于subscribe里的count
    data = context.data(symbol=bars[0]['symbol'], frequency='60s', count=50, fields='close,bob')

    # 打印最后5条bar数据(最后一条是最新的bar)
    print(data.tail())


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='strategy_id',
        filename='main.py',
        mode=MODE_BACKTEST,
        token='token_id',
        backtest_start_time='2020-11-01 08:00:00',
        backtest_end_time='2020-11-10 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)

copy successfully

The whole strategy requires three steps:

  1. Set the initialization function:  init  , use  the subscribe  function for data subscription
  2. Implement a function:  on_bar  to perform logical processing according to data push, by  context.data obtaining data sliding window
  3. execution strategy

Select backtest mode/live mode to run the example

Nuggets 3 strategy has only two modes, backtest mode (backtest) and real-time mode (live). Specify the mode parameter when loading the policy.

# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *


def init(context):
    # 订阅浦发银行的tick
    subscribe(symbols='SHSE.600000', frequency='60s')


def on_bar(context, bars):
    # 打印当前获取的bar信息
    print(bars)


if __name__ == '__main__':
    # 在终端仿真交易和实盘交易的启动策略按钮默认是实时模式,运行回测默认是回测模式,在外部IDE里运行策略需要修改成对应的运行模式
    # mode=MODE_LIVE 实时模式, 回测模式的相关参数不生效
    # mode=MODE_BACKTEST  回测模式

    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='strategy_id',
        filename='main.py',
        mode=MODE_LIVE,
        token='token_id',
        backtest_start_time='2020-11-01 08:00:00',
        backtest_end_time='2020-11-10 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)

copy successfully

The whole strategy requires three steps:

  1. Set the initialization function:  init  , use  the subscribe  function for data subscription code
  2. Implement a function:  on_bar  to perform logic processing based on data push
  3. Select the corresponding mode and execute the strategy

Extract Data Study Example

If you just want to extract data, you don't need real-time data-driven strategies, and you can query directly through the data query function without placing an order.

# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *


# 可以直接提取数据,掘金终端需要打开,接口取数是通过网络请求的方式,效率一般,行情数据可通过subscribe订阅方式
# 设置token, 查看已有token ID,在用户-密钥管理里获取
set_token('your token_id')

# 查询历史行情, 采用定点复权的方式, adjust指定前复权,adjust_end_time指定复权时间点
data = history(symbol='SHSE.600000', frequency='1d', start_time='2020-01-01 09:00:00', end_time='2020-12-31 16:00:00',
               fields='open,high,low,close', adjust=ADJUST_PREV, adjust_end_time='2020-12-31', df=True)
print(data)

copy successfully

The whole process only needs two steps:

  1. set_token sets the user token, if the token is incorrect, the function call will throw an exception
  2. Call the data query function to directly perform data query

Example of high-speed data processing in backtest mode

This example provides an efficient data processing method that prefetches the full set of data in init and calls the index after regularization, which can avoid the inefficiency caused by repeatedly calling the server interface. According to the idea of ​​this example, it can be applied to other data interfaces to improve efficiency.

# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *


def init(context):
	# 在init中一次性拿到所有需要的instruments信息
    instruments = get_history_instruments(symbols='SZSE.000001,SZSE.000002', start_date=context.backtest_start_time,end_date=context.backtest_end_time)
	# 将信息按symbol,date作为key存入字典
    context.ins_dict = {(i.symbol, i.trade_date.date()): i for i in instruments}
    subscribe(symbols='SZSE.000001,SZSE.000002', frequency='1d')

def on_bar(context, bars):
    print(context.ins_dict[(bars[0].symbol, bars[0].eob.date())])


if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='strategy_id',
        filename='main.py',
        mode=MODE_BACKTEST,
        token='token_id',
        backtest_start_time='2020-11-01 08:00:00',
        backtest_end_time='2020-11-10 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)

copy successfully

The whole strategy requires three steps:

  1. Set the initialization function:  init  , get all the required instruments information at one time, store the information in the dictionary according to symbol and date as the key, and use the  subscribe  function for data subscription code
  2. Implement a function:  schedule  to perform logic processing based on data push
  3. execution strategy

Example of dynamic parameters in real-time mode

This example provides a method to set dynamic parameters through policies, which can be displayed and modified on the terminal interface, and the parameters can be manually modified and passed into the strategy without stopping the strategy.

# coding=utf-8
from __future__ import print_function, absolute_import, unicode_literals
from gm.api import *
import numpy as np
import pandas as pd


'''动态参数,是指在不终止策略的情况下,掘金终端UI界面和策略变量做交互,
    通过add_parameter在策略代码里设置动态参数,终端UI界面会显示对应参数
'''


def init(context):
    # log日志函数,只支持实时模式,在仿真交易和实盘交易界面查看,重启终端log日志会被清除,需要记录到本地可以使用logging库
    log(level='info', msg='平安银行信号触发', source='strategy')
    # 设置k值阀值作为动态参数
    context.k_value = 23
    # add_parameter设置动态参数函数,只支持实时模式,在仿真交易和实盘交易界面查看,重启终端动态参数会被清除,重新运行策略会重新设置
    add_parameter(key='k_value', value=context.k_value, min=0, max=100, name='k值阀值', intro='设置k值阀值',
                  group='1', readonly=False)

    # 设置d值阀值作为动态参数
    context.d_value = 20
    add_parameter(key='d_value', value=context.d_value, min=0, max=100, name='d值阀值', intro='设置d值阀值',
                  group='2', readonly=False)

    print('当前的动态参数有', context.parameters)
    # 订阅行情
    subscribe(symbols='SZSE.002400', frequency='60s', count=120)


def on_bar(context, bars):

    data = context.data(symbol=bars[0]['symbol'], frequency='60s', count=100)

    kdj = KDJ(data, 9, 3, 3)
    k_value = kdj['kdj_k'].values
    d_value = kdj['kdj_d'].values

    if k_value[-1] > context.k_value and d_value[-1] < context.d_value:
        order_percent(symbol=bars[0]['symbol'], percent=0.01, side=OrderSide_Buy, order_type=OrderType_Market, position_effect=PositionEffect_Open)
        print('{}下单买入, k值为{}'.format(bars[0]['symbol'], context.k_value))


# 计算KDJ
def KDJ(data, N, M1, M2):
    lowList= data['low'].rolling(N).min()
    lowList.fillna(value=data['low'].expanding().min(), inplace=True)
    highList = data['high'].rolling(N).max()
    highList.fillna(value=data['high'].expanding().max(), inplace=True)
    rsv = (data['close'] - lowList) / (highList - lowList) * 100
    data['kdj_k'] = rsv.ewm(alpha=1/M1).mean()
    data['kdj_d'] = data['kdj_k'].ewm(alpha=1/M2).mean()
    data['kdj_j'] = 3.0 * data['kdj_k'] - 2.0 * data['kdj_d']
    return data


# 动态参数变更事件
def on_parameter(context, parameter):
    # print(parameter)
    if parameter['name'] == 'k值阀值':
        # 通过全局变量把动态参数值传入别的事件里
        context.k_value = parameter['value']
        print('{}已经修改为{}'.format(parameter['name'], context.k_value))

    if parameter['name'] == 'd值阀值':
        context.d_value = parameter['value']
        print('{}已经修改为{}'.format(parameter['name'], context.d_value))


def on_account_status(context, account):
    print(account)


if __name__ == '__main__':
    '''
    strategy_id策略ID,由系统生成
    filename文件名,请与本文件名保持一致
    mode实时模式:MODE_LIVE回测模式:MODE_BACKTEST
    token绑定计算机的ID,可在系统设置-密钥管理中生成
    backtest_start_time回测开始时间
    backtest_end_time回测结束时间
    backtest_adjust股票复权方式不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
    backtest_initial_cash回测初始资金
    backtest_commission_ratio回测佣金比例
    backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='07c08563-a4a8-11ea-a682-7085c223669d',
        filename='main.py',
        mode=MODE_LIVE,
        token='2c4e3c59cde776ebc268bf6d7b4c457f204482b3',
        backtest_start_time='2020-09-01 08:00:00',
        backtest_end_time='2020-10-01 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=500000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)

copy successfully


level2 data-driven event example

This example provides subscription to level2 market quotations, including tick-by-tick transactions, tick-by-tick orders, and order queues, which are only supported by brokerage hosting versions

# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *


def init(context):
    # 查询历史L2 Tick行情
    history_l2tick=get_history_l2ticks('SHSE.600519', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None,
                        skip_suspended=True, fill_missing=None,
                        adjust=ADJUST_NONE, adjust_end_time='', df=False)
    print(history_l2tick[0])

    # 查询历史L2 Bar行情
    history_l2bar=get_history_l2bars('SHSE.600000', '60s', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None,
                       skip_suspended=True, fill_missing=None,
                       adjust=ADJUST_NONE, adjust_end_time='', df=False)
    print(history_l2bar[0])

    # 查询历史L2 逐笔成交
    history_transactions = get_history_l2transactions('SHSE.600000', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None, df=False)
    print(history_transactions[0])

    # 查询历史L2 逐笔委托
    history_order=get_history_l2orders('SZSE.000001', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None, df=False)
    print(history_order[0])

    # 查询历史L2 委托队列
    history_order_queue = get_history_l2orders_queue('SZSE.000001', '2020-11-23 14:00:00', '2020-11-23 15:00:00', fields=None, df=False)
    print(history_order_queue[0])
    # 订阅浦发银行的逐笔成交数据
    subscribe(symbols='SHSE.600000', frequency='l2transaction')
    # 订阅平安银行的逐笔委托数据(仅支持深市标的)
    subscribe(symbols='SZSE.000001', frequency='l2order')


def on_l2order(context, order):
    # 打印逐笔成交数据
    print(order)


def on_l2transaction(context, transition):
    # 打印逐笔委托数据
    print(transition)



if __name__ == '__main__':
    '''
        strategy_id策略ID, 由系统生成
        filename文件名, 请与本文件名保持一致
        mode运行模式, 实时模式:MODE_LIVE回测模式:MODE_BACKTEST
        token绑定计算机的ID, 可在系统设置-密钥管理中生成
        backtest_start_time回测开始时间
        backtest_end_time回测结束时间
        backtest_adjust股票复权方式, 不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
        backtest_initial_cash回测初始资金
        backtest_commission_ratio回测佣金比例
        backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='strategy_id',
        filename='main.py',
        mode=MODE_BACKTEST,
        token='token_id',
        backtest_start_time='2020-11-01 08:00:00',
        backtest_end_time='2020-11-10 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001)

copy successfully


Convertible bond data acquisition/transaction example

This example provides convertible bond data acquisition, convertible bond transaction

# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *


def init(context):
    # 订阅可转债行情。与股票无异
    subscribe(symbols='SHSE.113038', frequency='tick', count=2)

    # 获取可转债基本信息,输入可转债代码即可
    infos = get_instrumentinfos(symbols='SHSE.113038', df=True)

    # 输入可转债标的代码,可以获取到历史行情
    history_data = history(symbol='SHSE.113038', frequency='60s', start_time='2021-02-24 14:50:00',
                                end_time='2021-02-24 15:30:30', adjust=ADJUST_PREV, df=True)


    # 可转债回售、转股、转股撤销,需要券商实盘环境,仿真回测不可用。
    bond_convertible_call('SHSE.110051', 100, 0)
    bond_convertible_put('SHSE.183350', 100, 0)
    bond_convertible_put_cancel('SHSE.183350', 100)

    # 可转债下单,仅将symbol替换为可转债标的代码即可
    order_volume(symbol='SZSE.128041', volume=100, side=OrderSide_Buy, order_type=OrderType_Limit, position_effect=PositionEffect_Open, price=340)

    # 直接获取委托,可以看到相应的可转债委托,普通买卖通过标的体现可转债交易,转股、回售、回售撤销通过order_business字段的枚举值不同来体现。
    A = get_orders()


def on_tick(context, tick):
    # 打印频率为tick,可转债最新tick
    print(tick)


if __name__ == '__main__':
    run(strategy_id='strategy_id',
        filename='main.py',
        mode=MODE_LIVE,
        token='token_id',
        backtest_start_time='2020-12-16 09:00:00',
        backtest_end_time='2020-12-16 09:15:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=10000000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001
        )

 

Guess you like

Origin blog.csdn.net/weixin_42219751/article/details/131700284