### RQData Initialization and Usage Source: https://www.ricequant.com/doc/rqdata/python/manual This section covers the essential steps to get started with RQData, including installation, initialization, and basic usage patterns. ```APIDOC ## Installation ```bash pip install rqdatac ``` For installing with additional packages like fund or bond: ```bash pip install "rqdatac[fund]" pip install "rqdatac[fund,bond]" ``` ## Initialization Before using any RQData API, you must initialize it. This is not required in the `rqsdk shell` environment. ```python import rqdatac # Initialize RQData rqdatac.init() ``` ## Checking Version and Login Info Use the `rqdatac.info()` function to get the current RQData version and server information. ### `rqdatac.info()` Returns the current RQData version and server address. **Example:** ```python # Get user login information info() ``` **Output Example:** ``` RQData version: 2.6.0 Server address: rqdatad-pro.ricequant.com:16011 You are using account: +86186XXXX6610 ``` ## Quota Information Check your current data traffic quota usage, remaining days, and license type. ### `rqdatac.user.get_quota()` Retrieves user quota information. **Returns:** * `bytes_limit` (int): Daily traffic usage limit in bytes (0 for unlimited). * `bytes_used` (int): Daily traffic used in bytes. * `remaining_days` (int): Remaining days on the license. * `license_type` (str): License type ('TRIAL' or 'FULL'). **Example:** ```python # Get user quota information rqdatac.user.get_quota() ``` **Output Example:** ```json { "bytes_limit": 0, "bytes_used": 954, "remaining_days": 16, "license_type": "TRIAL" } ``` ## Date Format Support RQData APIs support various date formats for parameters: | Format Description | Example Format | |---|---| | Numeric YYYYDDMM | 20150101 | | String "YYYY-DD-MM" | "2015-01-01" | | `datetime` object | `datetime.datetime(2015, 1, 3)` | | `date` object | `datetime.date(2015, 1, 3)` | | Pandas Timestamp | `pandas.Timestamp('20150103')` | **Example Usage:** ```python import rqdatac import pandas import datetime # Initialize RQData rqdatac.init() # Using different date formats price_data_1 = rqdatac.get_price('000001.XSHE', start_date=20150101, end_date="2015-02-01") price_data_2 = rqdatac.get_price('000002.XSHE', start_date=pandas.Timestamp("20150101"), end_date=datetime.datetime(2015, 2, 1)) ``` ## Saving Data to CSV Data returned by RQData APIs is often in Pandas DataFrame format. You can easily save this data to a CSV file. ```python import rqdatac # Initialize RQData rqdatac.init() # Get price data (returns a Pandas DataFrame) price_df = rqdatac.get_price('000001.XSHE', start_date=20150101, end_date=20150201) # Save to CSV price_df.to_csv('xxxx.csv') ``` ## Glossary * **rqdatac**: RQData Client. * **rqdatad**: RQData Server. * **order_book_id**: A unique identifier for financial instruments within Ricequant, used to refer to contract codes, stock codes, bond codes, etc. ``` -------------------------------- ### 期货开仓买入示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 使用 buy_open 接口进行期货多头开仓交易。该示例展示了如何买入 2 手 RB2010 合约。 ```python buy_open("RB2010", 2) ``` -------------------------------- ### Load Local Holding Weights for Backtesting Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Example strategy code for backtesting using local holding weights. This involves importing pandas and numpy, and potentially rqdatac. The example strategy is simplified. ```python import pandas import numpy import rqdatac # pip install -i https://pypi.tuna.tsinghua.edu.cn/simple xlrd # rqalpha-plus run -f holding_target_position_simplified.py __config__ = { "base": { "start_date": "20191201", "end_date": "20200930", "accounts": { "stock": 100000000, }, }, } ``` -------------------------------- ### Simple Mutual Fund Backtesting Example Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial This Python code provides a basic example of backtesting a mutual fund strategy. It initializes with a set amount of cash, subscribes to a fund, and implements a simple logic to redeem shares if the total returns exceed certain thresholds. It includes configurations for fund fees and settlement times. ```python INIT_CASH = 100000 __config__ = { "base": { "start_date": "20190105", "end_date": "20200809", "accounts": { "stock": INIT_CASH } }, "mod": { "sys_progress": { "enabled": True, "show": True }, "sys_analyser": { "enabled": True, "plot":True }, "fund": { # 基金申购前端费率 "fee_ratio": 0.015, # 基金份额到账时间 "subscription_receiving_days": 1, # 赎回金回款时间 "redemption_receiving_days": 3, # 申购金额上下限检查限制 "subscription_limit": True, # 申购状态检查限制 "status_limit": True, }, 'sys_simulation': { 'enabled': True, 'matching_type': 'current_bar', }, } } # 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。 def init(context): logger.info("init") context.s1 = "004241" context.fired = False def before_trading(context): pass # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新 def handle_bar(context, bar_dict): if not context.fired: subscribe_value(context.s1,INIT_CASH) context.fired = True if context.portfolio.total_returns > 0.4 or context.portfolio.total_returns < -0.2: context.quantity = get_position(context.s1).quantity if context.quantity > 0: redeem_shares(context.s1,context.quantity) ``` -------------------------------- ### Python Options Backtesting Strategy Setup Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial This Python code sets up a backtesting environment for an options strategy based on the CSI 300 index. It configures the backtest with specific dates, an initial capital for the future account, and enables the option module with specific simulation and analysis settings. It then defines initialization and trading functions to subscribe to relevant contracts and execute initial trades. ```python import rqalpha_plus import rqalpha_mod_option __config__ = { "base": { "start_date": "20200101", "end_date": "20200221", 'frequency': '1d', "accounts": { # 股指期权使用 future 账户 "future": 1000000 } }, "mod": { "option": { "enabled": True, "exercise_slippage": 0 }, 'sys_simulation': { 'enabled': True, 'matching_type': 'current_bar', 'volume_limit': False, 'volume_percent': 0, }, 'sys_analyser': { 'plot': True, }, } } def init(context): context.s1 = 'IO2002C3900' context.s2 = 'IO2002P3900' context.s3 = 'IF2002' subscribe(context.s1) subscribe(context.s2) subscribe(context.s3) context.counter = 0 print('******* INIT *******') def before_trading(context): pass def handle_bar(context, bar_dict): context.counter += 1 if context.counter == 1: sell_open(context.s1, 3) buy_open(context.s2, 3) buy_open(context.s3, 1) def after_trading(context): pass ``` -------------------------------- ### Strategy Internal Configuration Example Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Demonstrates how to define strategy-specific configurations within the strategy file itself by assigning a dictionary to the global `__config__` variable. This configuration has lower precedence than command-line arguments. ```python import talib __config__ = { "base": { "accounts": { "STOCK": 100000, }, "start_date": "20190101", "end_date": "20191231", }, "mod": { "sys_analyser": { "plot": True, "benchmark": "000300.XSHG" } } } def init(context): context.stock = "000001.XSHE" context.SHORTPERIOD = 12 context.LONGPERIOD = 26 context.SMOOTHPERIOD = 9 context.OBSERVATION = 100 def handle_bar(context, bar_dict): prices = history_bars(context.stock, context.OBSERVATION, '1d', 'close') macd, macd_signal, _ = talib.MACD( prices, context.SHORTPERIOD, context.LONGPERIOD, context.SMOOTHPERIOD ) if macd[-1] > macd_signal[-1] and macd[-2] < macd_signal[-2]: order_target_percent(context.stock, 1) if macd[-1] < macd_signal[-1] and macd[-2] > macd_signal[-2]: if get_position(context.stock).quantity > 0: order_target_percent(context.stock, 0) ``` -------------------------------- ### 设置期权行权滑点配置示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 通过配置行权滑点来模拟真实市场中行权过程中的价格波动风险。示例展示了如何设置 0.1 的行权滑点。支持命令行参数和函数入口配置。 ```json {"mod": {"option": {"exercise_slippage": 0.1}}} ``` -------------------------------- ### Fetch Stock Price using RQDatac API (Python) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Demonstrates how to fetch stock price data using the `rqdatac.get_price` function. This is an example of using the `rqdatac` package directly within a strategy, which might have different usage patterns compared to RQAlphaPlus internal APIs. ```python import rqdatac rqdatac.get_price("000001.XSHE") ``` -------------------------------- ### List Enabled Mods (Command Line) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Lists all currently enabled modules for RQAlpha Plus using the command line. ```bash rqalpha-plus mod list ``` -------------------------------- ### 分钟回测 Subscribe 接口示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 在分钟回测中,使用 subscribe 接口订阅关注的期货或期权合约,以便 RQAlphaPlus 在正确的时间触发 handle_bar 函数。该示例展示了如何订阅一个期货合约。 ```python subscribe('RB2010') ``` -------------------------------- ### 设置期货保证金倍率配置示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 通过设置保证金倍率来调整期货交易的实际保证金率。示例展示了如何将保证金倍率设置为 1.1。支持命令行参数和函数入口配置。 ```json {"base": {"margin_multiplier": 1.1}} ``` -------------------------------- ### 使用 Pickle 读取 RQAlphaPlus 回测结果文件 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 这段 Python 代码展示了如何使用 pickle 模块加载 'result.pkl' 文件,该文件存储了 RQAlphaPlus 回测的原始结果。加载后,代码打印出结果字典的键,并展示了 'trades' 键对应的数据。 ```python import pickle with open("result.pkl", "rb") as f: result = pickle.load(f) result.keys() result['trades'] ``` -------------------------------- ### 设置股票佣金倍率配置示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 通过配置佣金倍率来调整股票交易的佣金费率。示例展示了如何将佣金倍率设置为 1.1,使实际佣金率为万分之 8.8。支持命令行参数和函数入口配置。 ```json {"mod": {"sys_transaction_cost": {"commission_multiplier": 1.1}}} ``` -------------------------------- ### Enable Incremental Backtesting (Command Line) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Enables the incremental backtesting module using the command line. Incremental backtesting saves and reuses previous backtesting results. ```bash rqalpha-plus mod enable incremental ``` -------------------------------- ### 期货平仓卖出示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 使用 sell_close 接口进行期货多头平仓交易。该示例展示了如何平仓 1 手 RB2010 合约,指定价格并选择是否平当日期货。 ```python sell_close("RB2010", 1, price=3100, close_today=True) ``` -------------------------------- ### 开启分红再投资配置示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 配置分红再投资功能,使 RQAlphaPlus 在发生分红时自动使用现金买入相同的股票或场内基金。支持命令行参数和函数入口配置。 ```json {"mod": {"sys_accounts": {"dividend_reinvestment": True}}} ``` -------------------------------- ### Strategy Initialization with Context Variable Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Example 'init' function for an RQAlphaPlus strategy that initializes a context variable 'context.stock' to store the target security code ('000001.XSHE'). This variable can be accessed by other parts of the strategy. ```python def init(context): context.stock = "000001.XSHE" ``` -------------------------------- ### RQAlphaPlus 账户和持仓结构示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 此图示展示了 RQAlphaPlus 内部维护的多层级账户和持仓结构。从顶层的 Portfolio 到中间的 Account (STOCK, FUTURE),再到底层的 Position,清晰地描绘了策略中的资产构成。 ```text Portfolio() # 投资组合 │ └─── Account("STOCK") # 股票账户 │ │ │ └─── Position("000001.XSHE") # 平安银行持仓 │ │ │ └─── Position("90000003", "SHORT") # 300ETF购1月3900义务方持仓 │ │ │ └─── Position("128032.XSHE") # 双环转债持仓 │ │ │ └─── Position("AU9999.SGEX", "LONG") # 上金所Au99.99黄金现货合约多头持仓 │ | │ └─── Position("004241") # 中欧时代先锋股票C持仓 │ └─── Account("FUTURE") # 期货账户 │ └─── Position("RB2010", "LONG") # 螺纹钢2010多头持仓 │ └─── Position("RB2010", "SHORT") # 螺纹钢2010空头持仓 │ └─── Position("IO2004C4150", "LONG") # 300INDEX2004购4150权利方持仓 ``` -------------------------------- ### Run Strategy Programmatically with `run_func` Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial This Python code shows how to run a trading strategy programmatically using Ricequant's `run_func`. It defines a configuration dictionary for backtesting parameters such as initial capital, start and end dates, and benchmark. The `init` and `handle_bar` functions of the strategy are passed as arguments to `run_func`. ```python config = { "base": { "accounts": { "STOCK": 100000, }, "start_date": "20190101", "end_date": "20191231", }, "mod": { "sys_analyser": { "plot": True, "benchmark": "000300.XSHG" } } } if __name__ == "__main__": from rqalpha_plus import run_func run_func(config=config, init=init, handle_bar=handle_bar) ``` -------------------------------- ### Configure Incremental Backtesting (Command Line) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Configures incremental backtesting parameters when running via the command line. Requires specifying a persist folder and an optional strategy ID. ```bash # 在当前目录的/persist下查看是否有文件名为2的文件夹,若有则读取文件内容,在本地保存回测结果的基础上运行增量回测,若没有则在当前目录/persist下生成一个命名为2的文件夹保存本次回测的结果 --persist-folder . --strategy-id 2 ``` -------------------------------- ### Retrieve Strategy Backtesting Results Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial This Python code snippet illustrates how to obtain the results from a strategy run executed via `run_func`. The `run_func` call returns a dictionary, and this example shows how to access the 'summary' key within the 'sys_analyser' part of the results dictionary to retrieve performance metrics. ```python result = run_func(config=config, init=init, handle_bar=handle_bar) result['sys_analyser']["summary"] ``` -------------------------------- ### Configure Custom Benchmark (Command Line) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Sets a custom benchmark for backtesting using command-line arguments. It supports weighting multiple contracts for the benchmark. ```bash --benchmark 000300.XSHE:0.7,000905.XSHG:0.3 ``` -------------------------------- ### 访问当前策略的 Portfolio 对象 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 在 RQAlphaPlus 策略中,可以通过 `context.portfolio` 访问 Portfolio 对象。该对象提供了如 `portfolio_value`(总权益)、`unit_net_value`(净值)、`daily_pnl`(当日盈亏)等属性,用于获取策略的整体财务状况。 ```python # 获取当前策略总权益 context.portfolio.portfolio_value ``` -------------------------------- ### 使用 get_positions 获取所有持仓对象列表 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 通过调用 `get_positions()` 函数,RQAlphaPlus 返回一个包含策略中所有 Position 对象的列表。这个接口可以一次性获取所有持仓信息,方便进行批量处理或分析。 ```python get_positions() ``` -------------------------------- ### Download Sample Data Package Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Command to download a sample data package for RQAlphaPlus, which includes historical daily, minute, and tick data for various instruments. This is useful for quickly testing backtesting functionalities. ```bash rqsdk download-data --sample ``` -------------------------------- ### Deposit Funds (Stock Account) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Demonstrates how to deposit funds into a stock account during backtesting using the `deposit` function. Specify the account type and the amount. ```python #对股票账户增加10w资金 deposit("STOCK", 100000) ``` -------------------------------- ### 使用 get_position 获取单个持仓对象 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial RQAlphaPlus 提供了 `get_position` 函数来获取单个持仓对象。该函数接收标的代码和可选的方向参数(默认为多头),返回对应的 Position 对象,可用于查询特定金融标的的持仓信息。 ```python get_position("000001.XSHE") get_position("004241") get_position("RB2010", "SHORT") ``` -------------------------------- ### Run Strategy with Internal Configuration (Command Line) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Executes a strategy file that contains its configuration within the `__config__` variable, using the `-f` parameter to specify the strategy file path. ```bash rqalpha-plus run -f macd_000001.py ``` -------------------------------- ### Configure Management Fee (Command Line) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Sets the management fee for stock accounts using command-line arguments. The fee is charged daily based on total value and rate. ```bash --management-fee stock 0.02% ``` -------------------------------- ### RQAlphaPlus 回测结果保存为 Pickle 和 CSV 报告 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 该命令将 RQAlphaPlus 回测结果保存为 pickle 文件 'result.pkl' 和一个包含多个 CSV 文件的 'report' 目录。pickle 文件存储了 run_func 返回的字典,CSV 报告提供了易于分析的收益、持仓、交易流水等数据。 ```shell rqalpha-plus run -f macd_000001.py -a stock 100000 -s 20190101 -e 20191231 -p -bm 000300.XSHG -o result.pkl --report report ``` -------------------------------- ### 访问 RQAlphaPlus Account 对象属性 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 策略中可通过 `context.portfolio.accounts` 访问账户字典,例如 `context.portfolio.accounts["STOCK"]` 来获取单个 Account 对象。Account 对象具有 `cash`(可用资金)、`market_value`(持仓市值)、`total_value`(账户权益)等属性。 ```python # 访问股票账户对象 context.portfolio.accounts["STOCK"] # 访问股票账户的可用资金 context.portfolio.accounts["STOCK"].cash # 访问股票账户的持仓市值 context.portfolio.accounts["STOCK"].market_value # 访问股票账户的总权益 context.portfolio.accounts["STOCK"].total_value ``` -------------------------------- ### Example: Portfolio Optimization with Style Deviation Source: https://www.ricequant.com/doc/rqoptimize/manual Demonstrates how to use the portfolio_optimize function to minimize style deviation. This example sets individual stock position bounds, defines a style deviation objective function with specific factor exposures, and applies hard constraints for style neutrality relative to a benchmark. It utilizes RQData for data retrieval and assumes the RQOptimizer library is installed. ```python from rqoptimizer import * import rqdatac from rqdatac import * rqdatac.init() # 优化日期 date = '2019-02-28' # 候选合约 pool = index_components('000906.XSHG',date) # 对组合中所有个股头寸添加相同的约束0~5% bounds = {'*': (0, 0.05)} # 优化函数,风格偏离最小化,优化组合beta风格因子暴露度相对于基准组合高出1个标准差 objective = MinStyleDeviation({'size': 0, 'beta': 1, 'book_to_price': 0, 'earnings_yield': 0, 'growth': 0, 'leverage': 0, 'liquidity': 0, 'momentum': 0, 'non_linear_size': 0, 'residual_volatility': 0}, relative=True) # 约束条件,对所有风格因子添加基准中性约束,允许偏离±0.3个标准差 cons = [ WildcardStyleConstraint(lower_limit=-0.3, upper_limit=0.3, relative=True, hard=True) ] portfolio_optimize(pool, date, bnds=bounds, cons=cons, benchmark='000300.XSHG',objective = objective) ``` -------------------------------- ### Configure Incremental Backtesting (Function Entry) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Configures incremental backtesting parameters when running via a function entry. Specifies whether it's enabled, the persistence folder, and the strategy ID. ```json { "mod": { "incremental":{ 'enabled': True, "persist_folder": '.', "strategy_id": 2, } } } ``` -------------------------------- ### 生成回测样例策略 Source: https://www.ricequant.com/doc/rqsdk 此命令用于在当前目录下生成一个名为 'examples' 的目录,其中包含多个可以直接运行的回测策略示例。这些示例旨在帮助用户快速理解和上手策略编写。 ```bash rqalpha-plus examples ``` -------------------------------- ### Run Strategy via Command Line Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial This command demonstrates how to execute a trading strategy script using the `rqalpha-plus` command-line interface. It specifies the strategy file, initial capital, backtesting date range, and a benchmark index for performance comparison. The `-p` flag enables the display of performance plots upon completion. ```bash rqalpha-plus run -f macd_000001.py -a stock 100000 -s 20190101 -e 20191231 -bm 000300.XSHG -p ``` -------------------------------- ### Multi-Stock RSI Trading Strategy Example (Python) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial An example trading strategy that implements a multi-stock Relative Strength Index (RSI) algorithm. It calculates RSI for multiple stocks and places orders (buy or sell) based on predefined RSI thresholds (HIGH_RSI and LOW_RSI). The strategy uses the `talib` library for RSI calculation and `history_bars` to fetch historical data. ```python import talib def init(context): context.s1 = "000001.XSHE" context.s2 = "601988.XSHG" context.s3 = "000068.XSHE" context.stocks = [context.s1, context.s2, context.s3] context.TIME_PERIOD = 14 context.HIGH_RSI = 85 context.LOW_RSI = 30 context.ORDER_PERCENT = 0.3 def handle_bar(context, bar_dict): # 对我们选中的股票集合进行loop,运算每一只股票的RSI数值 for stock in context.stocks: # 读取历史数据 prices = history_bars(stock,context.TIME_PERIOD+1, '1d', 'close') # 用Talib计算RSI值 rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1] cur_position = context.portfolio.positions[stock].quantity # 用剩余现金的30%来购买新的股票 target_available_cash = context.portfolio.cash * context.ORDER_PERCENT # 当RSI大于设置的上限阀值,清仓该股票 if rsi_data > context.HIGH_RSI and cur_position > 0: order_target_value(stock, 0) # 当RSI小于设置的下限阀值,用剩余cash的一定比例补仓该股 if rsi_data < context.LOW_RSI: logger.info("target available cash caled: " + str(target_available_cash)) # 如果剩余的现金不够一手 - 100shares,那么会被ricequant 的order management system reject掉 order_value(stock, target_available_cash) ``` -------------------------------- ### Update Specific Data Types and Instruments Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Example command to perform an incremental data package update, specifying the update of daily bars, minute bars for a specific stock (000001.XSHE), minute bars for all 'RB' futures, and tick data for a specific option (IO2002C3900). ```bash rqsdk update-data --minbar 000001.XSHE --minbar RB --tick IO2002C3900 ``` -------------------------------- ### Install RQOptimizer Source: https://www.ricequant.com/doc/rqoptimize/manual Installs the RQOptimizer package using the rqsdk command-line tool. Ensure RQSDK is installed beforehand. This command fetches and installs the latest version of the optimizer. ```bash rqsdk install rqoptimizer ``` -------------------------------- ### 关闭股票 T+1 限制配置示例 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 关闭股票交易的 T+1 限制,允许当日买入的股票当日卖出。支持命令行参数和函数入口配置。 ```json {"mod": {"sys_accounts": {"stock_t1": False}}} ``` -------------------------------- ### RQOptimizer Installation Source: https://www.ricequant.com/doc/rqoptimize/manual Instructions for installing and updating the RQOptimizer package using the rqsdk command-line tool. ```APIDOC ## Installation To install RQOptimizer, ensure you have RQSDK installed and then run the following command: ```bash rqsdk install rqoptimizer ``` To update to the latest version, use: ```bash rqsdk update rqoptimizer ``` ``` -------------------------------- ### Install and Configure RQSDK Source: https://context7.com/context7/ricequant_doc/llms.txt Installs the RiceQuant SDK using pip and configures commercial licenses through interactive commands. It also allows installing specific product components and updating the SDK. ```bash # 安装 RQSDK pip install -i https://pypi.tuna.tsinghua.edu.cn/simple rqsdk # 配置许可证 rgsdk license # 根据提示输入米筐发放的许可证字符串 # 查看许可证信息 rgsdk license info # 安装特定产品组件(例如安装回测引擎) rgsdk install rqalpha_plus # 更新 SDK 到最新版本 rgsdk update ``` -------------------------------- ### Disable Incremental Backtesting (Command Line) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Disables the incremental backtesting module using the command line. ```bash rqalpha-plus mod disable incremental ``` -------------------------------- ### Get Macroeconomic Factors - Python Source: https://www.ricequant.com/doc/rqdata/python/macro-economy Retrieves macroeconomic factor data. Requires specifying the factor name, start date, and end date. The output is a pandas DataFrame with factor details, including information date, start date, end date, and the corresponding value. ```python econ.get_factors(factors, start_date, end_date) # Example: econ.get_factors(factors='工业品出厂价格指数PPI_当月同比_(上年同月=100)', start_date='20170801', end_date='20180801') ``` -------------------------------- ### Get Single Futures Contract Historical Tick Data using Python Source: https://www.ricequant.com/doc/rqdata/python/generic-api Fetches historical tick-level data for a single futures contract. Requires specifying the contract symbol, start date, end date, and desired frequency. Returns a pandas DataFrame containing detailed tick information such as open, last, high, low prices, volume, and open interest. `expect_df=False` is used in the example, implying data might be processed before returning a DataFrame. ```python get_price('IF1608', '20160801', '20160801', 'tick',expect_df=False).head() ``` -------------------------------- ### Subscribe Outer Fund by Amount (Python) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Subscribes to an outer fund by specifying the contract code and the subscription amount. This is a direct monetary subscription. ```Python subscribe_value("004241", 1000) ``` -------------------------------- ### 配置 RQAlphaPlus 账户初始资金 Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial 此代码段展示了两种配置 RQAlphaPlus 账户初始资金的方式:一是通过命令行参数 `-a stock 100000 -a future 100000`,二是在函数入口的配置文件中设置,例如 `{"base": {"accounts": {"STOCK": 100000, "FUTURE": 100000}}}`。 ```json { "base": {"accounts": { "STOCK": 100000, "FUTURE": 100000, }}} ``` -------------------------------- ### Withdraw Funds (Future Account) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Demonstrates how to withdraw funds from a future account during backtesting using the `withdraw` function. Specify the account type and the amount. ```python #对期货账户减少10w资金 withdraw("FUTURE", 100000) ``` -------------------------------- ### 查看回测运行帮助 Source: https://www.ricequant.com/doc/rqsdk 此命令用于显示 'rqalpha-plus run' 命令的所有可用配置参数和选项。这对于了解回测引擎的详细配置非常有用。 ```bash rqalpha-plus run --help ``` -------------------------------- ### Get Warehouse Stocks Source: https://www.ricequant.com/doc/rqdata/python/futures-mod Retrieves registered warehouse stock data for futures commodities. Requires specifying a start date and supports market filtering. ```APIDOC ## GET /futures/get_warehouse_stocks ### Description Retrieves registered warehouse stock data for futures commodities. This function allows you to track inventory levels for specific futures contracts. ### Method GET ### Endpoint /futures/get_warehouse_stocks ### Parameters #### Query Parameters - **underlying_symbols** (_str_) - Required - The futures contract symbol for which to retrieve warehouse stock data. - **start_date** (_str_) - Required - The start date for the data retrieval (YYYYMMDD). - **end_date** (_str_) - Optional - The end date for the data retrieval (YYYYMMDD). Defaults to the day before the current strategy date if not provided. - **market** (_str_) - Optional - The market to query. Currently only supports 'cn' (China). ### Request Example ```python # Get warehouse stock data for a futures contract starting from a specific date futures.get_warehouse_stocks(underlying_symbols='CU', start_date='20180910') ``` ### Response #### Success Response (200) - **on_warrant** (_int_) - The quantity of registered warrants (inventory). - **exchange** (_str_) - The exchange where the futures contract is listed. - **effective_forecast** (_str_) - Effective forecast data. Only supported for Zhengzhou Commodity Exchange (CZCE) contracts. - **warrant_units** (_str_) - Unit of warrants. Only supported for Zhengzhou Commodity Exchange (CZCE) contracts. - **deliverable** (_str_) - Quantity of goods meeting delivery quality standards. Only supported for Shanghai Futures Exchange (SHFE) contracts. #### Response Example ```json { "on_warrant": 10000, "exchange": "SHFE", "effective_forecast": null, "warrant_units": null, "deliverable": "9500" } ``` ``` -------------------------------- ### Install RQData using pip Source: https://www.ricequant.com/doc/rqdata/python/manual This command installs the core rqdatac package using pip. It's the basic installation for the RQData client. Ensure you have pip installed and are in a suitable Python environment. ```bash pip install rqdatac ``` -------------------------------- ### Configure Custom Benchmark (Function Entry) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Sets a custom benchmark for backtesting when running via a function entry. It supports weighting multiple contracts for the benchmark. ```json { "mod": { "sys_analyser": { "benchmark": { "000300.XSHE": 0.7, "000905.XSHG": 0.3 } } } } ``` -------------------------------- ### Python: Initialize RQData and Import Optimizer Modules Source: https://www.ricequant.com/doc/rqoptimize/manual This code block shows the necessary imports for using Ricequant's features, including data initialization (`rqdatac.init()`) and importing components from `rqdatac` and `rqoptimizer`. This setup is fundamental for running quantitative trading strategies and optimizations. ```python import rqdatac from rqoptimizer import * from rqdatac import * # Initialize the rqdatac connection # rqdatac.init() # Now you can use functions and classes from rqdatac and rqoptimizer # For example: # from rqdatac import get_price # from rqoptimizer import Portfolio ``` -------------------------------- ### Simple Portfolio Allocation Strategy - Python Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial A basic trading strategy that buys a specified stock at a target percentage of the portfolio on the first day and holds it until the end of the strategy run. It uses the `order_target_percent` function for order execution. This strategy is suitable for beginners to understand basic order placement. ```python def init(context): context.fired = False def handle_bar(context, bar_dict): if not context.fired: order_target_percent("000001.XSHE", 0.5) context.fired = True Copied! ``` -------------------------------- ### Configure Management Fee (Function Entry) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Configures the management fee rate for accounts when running via a function entry. It specifies the account type and the fee percentage. ```json { "mod": { "sys_simulation":{ "enabled": True, "management_fee": [("stock", 0.02%)] } } } ``` -------------------------------- ### Redeem Outer Fund by Percentage (Python) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Redeems an outer fund by specifying the contract code and a percentage of remaining shares to redeem. This facilitates proportional redemptions of holdings. ```Python redeem_percent("004241", 0.1) ``` -------------------------------- ### Redeem Outer Fund by Shares (Python) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Redeems a specified number of shares for an outer fund, identified by its contract code. This is useful for exact share quantity redemptions. ```Python redeem_shares("004241", 500) ``` -------------------------------- ### Install RQData with optional packages Source: https://www.ricequant.com/doc/rqdata/python/manual This command installs RQData along with specific optional packages like 'fund' or 'bond'. Use this if you need to work with specific financial instruments supported by these additional packages. You can install multiple packages by listing them separated by commas within the brackets. ```bash pip install "rqdatac[fund]" pip install "rqdatac[fund,bond]" ``` -------------------------------- ### Python Hello World Buy and Hold Strategy Source: https://www.ricequant.com/doc/quant/backtest A simple buy-and-hold strategy in Python for demonstration. It initializes the strategy, sets a target stock, and places an order to buy and hold it. This example illustrates the basic structure of a Ricequant strategy, including the `init` and `handle_bar` methods. ```python # Can import third-party python modules supported by our platform, such as pandas, numpy, etc. # Write any initialization logic in this method. The context object will be passed between any methods of your algorithm strategy. def init(context): context.s1 = "000001.XSHE" # Whether the order has been sent context.fired = False # The update of the securities data you selected will trigger this logic, such as daily or minute historical data slices or real-time data slice updates def handle_bar(context, bar_dict): # Start writing your main algorithm logic # bar_dict[order_book_id] can get the bar information of a security # context.portfolio can get the current portfolio information # Use order_shares to place an order # TODO: Start writing your algorithm! if not context.fired: # order_percent and pass 1 to buy the stock and make it occupy 100% of the portfolio order_percent(context.s1, 1) context.fired = True ``` -------------------------------- ### Subscribe Outer Fund by Shares (Python) Source: https://www.ricequant.com/doc/rqalpha-plus/tutorial Subscribes to an outer fund by specifying the contract code and the number of shares to subscribe. This allows for precise share quantity purchases. ```Python subscribe_shares("004241", 500) ```