Comprehensive algorithmic trading framework for Python with backtesting, simulation, and live trading capabilities
—
Core entry points for running trading strategies in RQAlpha, supporting multiple execution modes including file-based strategies, code strings, and function callbacks with comprehensive configuration options.
Execute a trading strategy from a Python file with optional configuration override.
def run_file(strategy_file_path: str, config: dict = None) -> dict:
"""
Execute strategy from file path.
Parameters:
- strategy_file_path (str): Path to strategy Python file
- config (dict, optional): Strategy configuration dictionary, overrides strategy's __config__
Returns:
dict: Strategy execution results with performance metrics
"""Usage Example:
import rqalpha
config = {
"base": {
"start_date": "2020-01-01",
"end_date": "2020-12-31",
"accounts": {"stock": 100000},
"benchmark": "000300.XSHG"
},
"mod": {
"sys_analyser": {
"enabled": True,
"plot": True
}
}
}
result = rqalpha.run_file("my_strategy.py", config=config)
print(f"Total return: {result['summary']['total_returns']:.2%}")Execute a trading strategy from a code string with optional configuration.
def run_code(code: str, config: dict = None) -> dict:
"""
Execute strategy from code string.
Parameters:
- code (str): Strategy code string containing init, handle_bar, etc. functions
- config (dict, optional): Strategy configuration dictionary
Returns:
dict: Strategy execution results with performance metrics
"""Usage Example:
import rqalpha
strategy_code = """
def init(context):
context.stocks = ["000001.XSHE", "000002.XSHE"]
context.counter = 0
def handle_bar(context, bar_dict):
context.counter += 1
if context.counter % 20 == 0: # Rebalance every 20 days
for stock in context.stocks:
order_target_percent(stock, 1.0 / len(context.stocks))
"""
config = {
"base": {
"start_date": "2020-01-01",
"end_date": "2020-12-31",
"accounts": {"stock": 100000}
}
}
result = rqalpha.run_code(strategy_code, config=config)Execute a trading strategy using user-defined function callbacks with flexible configuration.
def run_func(**kwargs) -> dict:
"""
Execute strategy using function callbacks.
Keyword Arguments:
- config (dict): Strategy configuration dictionary
- init (callable): Strategy initialization function
- before_trading (callable): Pre-market function
- open_auction (callable): Open auction function
- handle_bar (callable): Bar data handler function
- handle_tick (callable): Tick data handler function
- after_trading (callable): Post-market function
Returns:
dict: Strategy execution results with performance metrics
"""Usage Example:
import rqalpha
def init(context):
context.stocks = ["000001.XSHE"]
context.target_position = {}
def before_trading(context):
# Daily pre-market logic
pass
def handle_bar(context, bar_dict):
stock = context.stocks[0]
current_price = bar_dict[stock].close
# Simple momentum strategy
if len(context.portfolio.positions) == 0:
order_target_percent(stock, 0.5)
def after_trading(context):
# Daily post-market logic
pass
config = {
"base": {
"start_date": "2020-01-01",
"end_date": "2020-12-31",
"accounts": {"stock": 100000},
"frequency": "1d"
}
}
result = rqalpha.run_func(
config=config,
init=init,
before_trading=before_trading,
handle_bar=handle_bar,
after_trading=after_trading
)Deprecated legacy run function maintained for backward compatibility.
def run(config: dict, source_code: str = None) -> dict:
"""
[DEPRECATED] Legacy run function.
Parameters:
- config (dict): Parsed configuration
- source_code (str, optional): Strategy source code
Returns:
dict: Strategy execution results
"""IPython and Jupyter notebook integration for interactive strategy development.
def load_ipython_extension(ipython):
"""
Load RQAlpha IPython extension.
Parameters:
- ipython: IPython instance
Enables %%rqalpha magic command in Jupyter notebooks.
"""
def run_ipython_cell(line: str, cell: str = None):
"""
Execute strategy in IPython cell.
Parameters:
- line (str): Command line arguments
- cell (str, optional): Cell content with strategy code
"""Usage in Jupyter:
%load_ext rqalpha
%%rqalpha --start-date 2020-01-01 --end-date 2020-12-31 --stock-starting-cash 100000
def init(context):
context.stock = "000001.XSHE"
def handle_bar(context, bar_dict):
order_target_percent(context.stock, 0.8)base_config = {
"start_date": "2020-01-01", # Backtest start date
"end_date": "2020-12-31", # Backtest end date
"accounts": { # Account configurations
"stock": 100000, # Stock account initial cash
"future": 50000, # Future account initial cash
"bond": 25000 # Bond account initial cash
},
"benchmark": "000300.XSHG", # Benchmark instrument
"frequency": "1d", # Data frequency ('1d', '1m', 'tick')
"run_type": "b", # Run type ('b'=backtest, 'p'=paper, 'r'=live)
"strategy_file": "path/to/strategy.py", # Strategy file path
"persist": {
"persist_mode": "real_time" # Persistence mode
}
}extended_config = {
"extra": {
"log_level": "info", # Logging level
"context_vars": {}, # Additional context variables
"enable_profiler": False # Performance profiling
},
"mod": { # Module configurations
"sys_progress": {
"enabled": True,
"show": True
},
"sys_analyser": {
"enabled": True,
"plot": True,
"output_file": "results.pkl"
}
}
}All execution functions return a comprehensive results dictionary:
ExecutionResult = {
"summary": {
"total_returns": float, # Total return percentage
"annual_returns": float, # Annualized return
"benchmark_returns": float, # Benchmark return
"max_drawdown": float, # Maximum drawdown
"sharpe": float, # Sharpe ratio
"sortino": float, # Sortino ratio
"information_ratio": float, # Information ratio
"tracking_error": float, # Tracking error
"downside_risk": float, # Downside risk
"alpha": float, # Alpha vs benchmark
"beta": float, # Beta vs benchmark
"calmar": float, # Calmar ratio
"volatility": float # Volatility
},
"portfolio": {
"total_value": float, # Final portfolio value
"cash": float, # Final cash amount
"market_value": float, # Final market value
"positions": list # Final positions
},
"trades": list, # All trade records
"benchmark_portfolio": dict # Benchmark portfolio data
}Install with Tessl CLI
npx tessl i tessl/pypi-rqalpha