Overview of sys_accounts Mod
mastersys_accounts module is an RQAlpha extension module that implements account logic for both stocks and futures. It provides specialized APIs for managing stock and futures accounts within the RQAlpha environment.repository·master·Indexed 27 days ago
https://github.com/ricequant/rqalphaRQAlpha is a quantitative trading research platform and algorithm trading system. It features an event-driven architecture, a mod system for extensibility, and a specific strategy lifecycle consisting of init, before_trading, handle_bar, and after_trading. The platform supports HDF5 data bundles, YAML configuration, and provides a comprehensive API for order execution, position management, and historical data retrieval.
sys_accounts module is an RQAlpha extension module that implements account logic for both stocks and futures. It provides specialized APIs for managing stock and futures accounts within the RQAlpha environment.add_listener. When an event occurs, the registered code executes immediately. This allows developers to seamlessly insert custom logic (like risk control or progress monitoring) into the backtesting process by subscribing to existing events.You can read local files or access databases directly within your strategy.
Important Considerations:
init, before_trading, handle_bar, handle_tick, or after_trading functions. Do not execute data retrieval code outside these functions.rqalpha command is executed, not the strategy file's directory. To avoid errors with relative paths, use context.config.base.strategy_file to locate the strategy file and derive relative paths from there.from rqalpha.api import *
import os
import pandas as pd
def read_csv_as_df(csv_path):
data = pd.read_csv(csv_path)
return data
def init(context):
# Get the absolute path of the strategy file
strategy_file_path = context.config.base.strategy_file
# Resolve relative path based on the strategy file location
csv_path = os.path.join(os.path.dirname(strategy_file_path), "../IF1706_20161108.csv")
# Load data and attach to context for use in other functions
IF1706_df = read_csv_as_df(csv_path)
context.IF1706_df = IF1706_df
def before_trading(context):
logger.info(context.IF1706_df)
__config__ = {
"base": {
"start_date": "2015-01-09",
"end_date": "2015-01-10",
"frequency": "1d",
"matching_type": "current_bar",
"benchmark": None,
"accounts": {
"future": 1000000
}
},
"extra": {
"log_level": "verbose",
},
}To reproduce bugs or test logic, create a strategy file using the rqalpha.apis module. A standard strategy includes init, before_trading, handle_bar, and after_trading functions.
Key lifecycle functions:
init(context): Initialize strategy parameters and universe.before_trading(context): Execute logic before the market opens.handle_bar(context, bar_dict): Main trading logic executed at every bar.after_trading(context): Execute logic after the market closes.from rqalpha.apis import *
def init(context):
"""初始化策略"""
logger.info("策略初始化")
context.stock = "000001.XSHE" # 平安银行
update_universe(context.stock)
def before_trading(context):
"""每日开盘前执行"""
logger.info(f"日期: {context.now.date()}")
def handle_bar(context, bar_dict):
"""每个bar执行一次 - 主要交易逻辑"""
# 获取历史数据
prices = history_bars(context.stock, 20, '1d', 'close')
if prices is not None:
avg_price = prices.mean()
current_price = bar_dict[context.stock].close
# 简单的均值回归策略
if current_price < avg_price * 0.98:
order_value(context.stock, 30000)
logger.info(f"买入 {context.stock}")
elif current_price > avg_price * 1.02:
position = get_position(context.stock)
if position.quantity > 0:
order_target_percent(context.stock, 0)
logger.info(f"卖出 {context.stock}")
def after_trading(context):
"""每日收盘后执行"""
positions = context.portfolio.positions
if len(positions) > 0:
logger.info(f"持仓: {[p.order_book_id for p in positions.values()]}")AbstractMod interface. This enables customization of the engine's behavior through modular extensions.RQData is a financial data service that integrates seamlessly with RQAlpha. To use it, simply import rqdatac within your strategy. It provides access to various data types including:
sys_risk module provides pre-trade risk control validation for orders. This is a system module and cannot be deleted. You can enable or disable it using the RQAlpha CLI.RQAlpha uses specific branches to manage stability and development:
master: The latest stable version. Only team members merge develop into master during official releases.develop: The latest development version. All new code submissions must pass all tests before being merged here.Branch Naming Rules:
bug/xxx: Use this for bug fixes.feature/xxx: Use this for adding new features (ensure documentation and tests are updated).To extend RQAlpha, implement the AbstractMod interface. You can use the start_up method to access the env.event_bus and register listeners for specific events using add_listener(EVENT_TYPE, callback_function).
Example: Creating a progress bar module that updates after each trading day.
import click
from rqalpha.interface import AbstractMod
from rqalpha.events import EVENT
class ProgressMod(AbstractMod):
def __init__(self):
self._env = None
self.progress_bar = None
def start_up(self, env, mod_config):
self._env = env
# Registering listeners for system init and post-trading events
env.event_bus.add_listener(EVENT.POST_AFTER_TRADING, self._tick)
env.event_bus.add_listener(EVENT.POST_SYSTEM_INIT, self._init)
def _init(self, event):
# Initialize progress bar based on trading calendar length
trading_length = len(self._env.config.base.trading_calendar)
self.progress_bar = click.progressbar(length=trading_length, show_eta=False)
def _tick(self, event):
# Update progress bar on every tick/trading day end
self.progress_bar.update(1)
def tear_down(self, success, exception=None):
# Clean up/finish progress bar on exit
if self.progress_bar:
self.progress_bar.render_finish()
def load_mod():
return ProgressMod()You can manage the availability of the sys_accounts module using the RQAlpha CLI. Use the disable command to turn it off and the enable command to turn it on.
# 关闭账户 Mod
$ rqalpha mod disable sys_accounts
# 启用账户 Mod
$ rqalpha mod enable sys_accountsUse the following make commands to manage the documentation build process:
make html: Compiles the documentation and generates HTML files in {project}/docs/build/.make htmlview: Starts a local server to view the compiled documentation.make clean: Removes all files in the build directory.make watch: Automatically recompiles the documentation whenever source files are changed.make html
make htmlview
make clean
make watch