0
# Strategy Execution
1
2
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.
3
4
## Capabilities
5
6
### File-based Strategy Execution
7
8
Execute a trading strategy from a Python file with optional configuration override.
9
10
```python { .api }
11
def run_file(strategy_file_path: str, config: dict = None) -> dict:
12
"""
13
Execute strategy from file path.
14
15
Parameters:
16
- strategy_file_path (str): Path to strategy Python file
17
- config (dict, optional): Strategy configuration dictionary, overrides strategy's __config__
18
19
Returns:
20
dict: Strategy execution results with performance metrics
21
"""
22
```
23
24
**Usage Example:**
25
26
```python
27
import rqalpha
28
29
config = {
30
"base": {
31
"start_date": "2020-01-01",
32
"end_date": "2020-12-31",
33
"accounts": {"stock": 100000},
34
"benchmark": "000300.XSHG"
35
},
36
"mod": {
37
"sys_analyser": {
38
"enabled": True,
39
"plot": True
40
}
41
}
42
}
43
44
result = rqalpha.run_file("my_strategy.py", config=config)
45
print(f"Total return: {result['summary']['total_returns']:.2%}")
46
```
47
48
### Code String Strategy Execution
49
50
Execute a trading strategy from a code string with optional configuration.
51
52
```python { .api }
53
def run_code(code: str, config: dict = None) -> dict:
54
"""
55
Execute strategy from code string.
56
57
Parameters:
58
- code (str): Strategy code string containing init, handle_bar, etc. functions
59
- config (dict, optional): Strategy configuration dictionary
60
61
Returns:
62
dict: Strategy execution results with performance metrics
63
"""
64
```
65
66
**Usage Example:**
67
68
```python
69
import rqalpha
70
71
strategy_code = """
72
def init(context):
73
context.stocks = ["000001.XSHE", "000002.XSHE"]
74
context.counter = 0
75
76
def handle_bar(context, bar_dict):
77
context.counter += 1
78
if context.counter % 20 == 0: # Rebalance every 20 days
79
for stock in context.stocks:
80
order_target_percent(stock, 1.0 / len(context.stocks))
81
"""
82
83
config = {
84
"base": {
85
"start_date": "2020-01-01",
86
"end_date": "2020-12-31",
87
"accounts": {"stock": 100000}
88
}
89
}
90
91
result = rqalpha.run_code(strategy_code, config=config)
92
```
93
94
### Function Callback Strategy Execution
95
96
Execute a trading strategy using user-defined function callbacks with flexible configuration.
97
98
```python { .api }
99
def run_func(**kwargs) -> dict:
100
"""
101
Execute strategy using function callbacks.
102
103
Keyword Arguments:
104
- config (dict): Strategy configuration dictionary
105
- init (callable): Strategy initialization function
106
- before_trading (callable): Pre-market function
107
- open_auction (callable): Open auction function
108
- handle_bar (callable): Bar data handler function
109
- handle_tick (callable): Tick data handler function
110
- after_trading (callable): Post-market function
111
112
Returns:
113
dict: Strategy execution results with performance metrics
114
"""
115
```
116
117
**Usage Example:**
118
119
```python
120
import rqalpha
121
122
def init(context):
123
context.stocks = ["000001.XSHE"]
124
context.target_position = {}
125
126
def before_trading(context):
127
# Daily pre-market logic
128
pass
129
130
def handle_bar(context, bar_dict):
131
stock = context.stocks[0]
132
current_price = bar_dict[stock].close
133
134
# Simple momentum strategy
135
if len(context.portfolio.positions) == 0:
136
order_target_percent(stock, 0.5)
137
138
def after_trading(context):
139
# Daily post-market logic
140
pass
141
142
config = {
143
"base": {
144
"start_date": "2020-01-01",
145
"end_date": "2020-12-31",
146
"accounts": {"stock": 100000},
147
"frequency": "1d"
148
}
149
}
150
151
result = rqalpha.run_func(
152
config=config,
153
init=init,
154
before_trading=before_trading,
155
handle_bar=handle_bar,
156
after_trading=after_trading
157
)
158
```
159
160
### Legacy Strategy Execution
161
162
Deprecated legacy run function maintained for backward compatibility.
163
164
```python { .api }
165
def run(config: dict, source_code: str = None) -> dict:
166
"""
167
[DEPRECATED] Legacy run function.
168
169
Parameters:
170
- config (dict): Parsed configuration
171
- source_code (str, optional): Strategy source code
172
173
Returns:
174
dict: Strategy execution results
175
"""
176
```
177
178
### IPython Integration
179
180
IPython and Jupyter notebook integration for interactive strategy development.
181
182
```python { .api }
183
def load_ipython_extension(ipython):
184
"""
185
Load RQAlpha IPython extension.
186
187
Parameters:
188
- ipython: IPython instance
189
190
Enables %%rqalpha magic command in Jupyter notebooks.
191
"""
192
193
def run_ipython_cell(line: str, cell: str = None):
194
"""
195
Execute strategy in IPython cell.
196
197
Parameters:
198
- line (str): Command line arguments
199
- cell (str, optional): Cell content with strategy code
200
"""
201
```
202
203
**Usage in Jupyter:**
204
205
```python
206
%load_ext rqalpha
207
208
%%rqalpha --start-date 2020-01-01 --end-date 2020-12-31 --stock-starting-cash 100000
209
def init(context):
210
context.stock = "000001.XSHE"
211
212
def handle_bar(context, bar_dict):
213
order_target_percent(context.stock, 0.8)
214
```
215
216
## Configuration Structure
217
218
### Base Configuration
219
220
```python { .api }
221
base_config = {
222
"start_date": "2020-01-01", # Backtest start date
223
"end_date": "2020-12-31", # Backtest end date
224
"accounts": { # Account configurations
225
"stock": 100000, # Stock account initial cash
226
"future": 50000, # Future account initial cash
227
"bond": 25000 # Bond account initial cash
228
},
229
"benchmark": "000300.XSHG", # Benchmark instrument
230
"frequency": "1d", # Data frequency ('1d', '1m', 'tick')
231
"run_type": "b", # Run type ('b'=backtest, 'p'=paper, 'r'=live)
232
"strategy_file": "path/to/strategy.py", # Strategy file path
233
"persist": {
234
"persist_mode": "real_time" # Persistence mode
235
}
236
}
237
```
238
239
### Extended Configuration
240
241
```python { .api }
242
extended_config = {
243
"extra": {
244
"log_level": "info", # Logging level
245
"context_vars": {}, # Additional context variables
246
"enable_profiler": False # Performance profiling
247
},
248
"mod": { # Module configurations
249
"sys_progress": {
250
"enabled": True,
251
"show": True
252
},
253
"sys_analyser": {
254
"enabled": True,
255
"plot": True,
256
"output_file": "results.pkl"
257
}
258
}
259
}
260
```
261
262
## Execution Results
263
264
All execution functions return a comprehensive results dictionary:
265
266
```python { .api }
267
ExecutionResult = {
268
"summary": {
269
"total_returns": float, # Total return percentage
270
"annual_returns": float, # Annualized return
271
"benchmark_returns": float, # Benchmark return
272
"max_drawdown": float, # Maximum drawdown
273
"sharpe": float, # Sharpe ratio
274
"sortino": float, # Sortino ratio
275
"information_ratio": float, # Information ratio
276
"tracking_error": float, # Tracking error
277
"downside_risk": float, # Downside risk
278
"alpha": float, # Alpha vs benchmark
279
"beta": float, # Beta vs benchmark
280
"calmar": float, # Calmar ratio
281
"volatility": float # Volatility
282
},
283
"portfolio": {
284
"total_value": float, # Final portfolio value
285
"cash": float, # Final cash amount
286
"market_value": float, # Final market value
287
"positions": list # Final positions
288
},
289
"trades": list, # All trade records
290
"benchmark_portfolio": dict # Benchmark portfolio data
291
}
292
```