0
# Data Access
1
2
Market data and historical data functions providing comprehensive access to pricing data, instrument information, calendar data, financial metrics, and fundamental data. All functions support flexible querying with proper data alignment and adjustments.
3
4
## Capabilities
5
6
### Historical Market Data
7
8
Functions for accessing historical OHLCV bar data and tick data with various frequencies and adjustments.
9
10
```python { .api }
11
def history_bars(order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False, adjust_type='pre', adjust_orig=None):
12
"""
13
Historical OHLCV bar data with adjustments.
14
15
Parameters:
16
- order_book_id (str): Instrument identifier
17
- bar_count (int): Number of bars to retrieve
18
- frequency (str): Data frequency ('1d', '1m', '5m', '15m', '30m', '60m')
19
- fields (str|list, optional): Fields to retrieve ('open', 'high', 'low', 'close', 'volume')
20
- skip_suspended (bool): Skip suspended trading periods
21
- include_now (bool): Include current incomplete bar
22
- adjust_type (str): Adjustment type ('pre', 'post', 'none')
23
- adjust_orig (str, optional): Original adjustment reference point
24
25
Returns:
26
numpy.ndarray|pandas.DataFrame: Historical bar data
27
"""
28
29
def history_ticks(order_book_id, count):
30
"""
31
Historical tick data.
32
33
Parameters:
34
- order_book_id (str): Instrument identifier
35
- count (int): Number of ticks to retrieve
36
37
Returns:
38
list[TickObject]: List of tick data objects
39
"""
40
```
41
42
### Real-time Market Data
43
44
Functions for accessing current market snapshots and real-time pricing information.
45
46
```python { .api }
47
def current_snapshot(id_or_symbol):
48
"""
49
Current market snapshot with bid/ask and volume.
50
51
Parameters:
52
- id_or_symbol (str): Instrument ID or symbol
53
54
Returns:
55
dict: Market snapshot with bid_price, ask_price, last_price, volume, etc.
56
"""
57
```
58
59
### Instrument Information
60
61
Functions for discovering and accessing instrument metadata and classifications.
62
63
```python { .api }
64
def all_instruments(type=None, date=None):
65
"""
66
Get all available instruments by type and date.
67
68
Parameters:
69
- type (str, optional): Instrument type filter ('CS', 'FUTURE', 'OPTION', 'ETF')
70
- date (str|datetime, optional): Date for instrument universe
71
72
Returns:
73
pandas.DataFrame: DataFrame with instrument information
74
"""
75
76
def instruments(id_or_symbols):
77
"""
78
Get specific instruments by ID.
79
80
Parameters:
81
- id_or_symbols (str|list[str]): Instrument ID(s) to retrieve
82
83
Returns:
84
Instrument|list[Instrument]: Instrument object(s) with metadata
85
"""
86
87
def symbol(order_book_id, sep=", "):
88
"""
89
Get human-readable instrument symbol.
90
91
Parameters:
92
- order_book_id (str): Instrument identifier
93
- sep (str): Separator for multiple symbols
94
95
Returns:
96
str: Human-readable symbol name
97
"""
98
```
99
100
### Trading Calendar
101
102
Functions for accessing trading calendar information and date calculations.
103
104
```python { .api }
105
def get_trading_dates(start_date, end_date):
106
"""
107
Get trading calendar dates between start and end.
108
109
Parameters:
110
- start_date (str|datetime): Start date
111
- end_date (str|datetime): End date
112
113
Returns:
114
list[datetime.date]: List of trading dates
115
"""
116
117
def get_previous_trading_date(date, n=1):
118
"""
119
Get previous trading day.
120
121
Parameters:
122
- date (str|datetime): Reference date
123
- n (int): Number of trading days back
124
125
Returns:
126
datetime.date: Previous trading date
127
"""
128
129
def get_next_trading_date(date, n=1):
130
"""
131
Get next trading day.
132
133
Parameters:
134
- date (str|datetime): Reference date
135
- n (int): Number of trading days forward
136
137
Returns:
138
datetime.date: Next trading date
139
"""
140
```
141
142
### Fixed Income Data
143
144
Functions for accessing bond and fixed income market data.
145
146
```python { .api }
147
def get_yield_curve(date=None, tenor=None):
148
"""
149
Yield curve data.
150
151
Parameters:
152
- date (str|datetime, optional): Date for yield curve
153
- tenor (str, optional): Specific tenor ('1Y', '2Y', '5Y', '10Y', '30Y')
154
155
Returns:
156
pandas.DataFrame: Yield curve data with tenors and rates
157
"""
158
```
159
160
### Market Structure Data
161
162
Functions for accessing index compositions, industry classifications, and market structure information.
163
164
```python { .api }
165
def index_components(order_book_id, date=None):
166
"""
167
Index constituent stocks.
168
169
Parameters:
170
- order_book_id (str): Index identifier
171
- date (str|datetime, optional): Date for composition
172
173
Returns:
174
list[str]: List of constituent instrument IDs
175
"""
176
177
def index_weights(order_book_id, date=None):
178
"""
179
Index constituent weights.
180
181
Parameters:
182
- order_book_id (str): Index identifier
183
- date (str|datetime, optional): Date for weights
184
185
Returns:
186
pandas.DataFrame: DataFrame with instruments and weights
187
"""
188
189
def concept(*concept_names):
190
"""
191
Get stocks by concept categories.
192
193
Parameters:
194
- concept_names (str): Concept category names
195
196
Returns:
197
list[str]: List of instrument IDs in concept
198
"""
199
200
def get_industry(industry, source='citics'):
201
"""
202
Get stocks by industry.
203
204
Parameters:
205
- industry (str): Industry name or code
206
- source (str): Classification source ('citics', 'sw', 'zjw')
207
208
Returns:
209
list[str]: List of instrument IDs in industry
210
"""
211
212
def get_instrument_industry(order_book_ids, source='citics', level=1):
213
"""
214
Get instrument industry classification.
215
216
Parameters:
217
- order_book_ids (str|list[str]): Instrument ID(s)
218
- source (str): Classification source ('citics', 'sw', 'zjw')
219
- level (int): Classification level (1, 2, 3)
220
221
Returns:
222
pandas.DataFrame: DataFrame with instruments and industry classifications
223
"""
224
```
225
226
### Margin and Trading Data
227
228
Functions for accessing margin trading information and special trading programs.
229
230
```python { .api }
231
def get_margin_stocks(exchange=None, margin_type="all"):
232
"""
233
Margin trading eligible stocks.
234
235
Parameters:
236
- exchange (str, optional): Exchange filter ('XSHE', 'XSHG')
237
- margin_type (str): Margin type ('margin', 'short_selling', 'all')
238
239
Returns:
240
list[str]: List of margin-eligible instrument IDs
241
"""
242
243
def get_stock_connect(order_book_ids, count=1, fields=None, expect_df=False):
244
"""
245
Stock connect data.
246
247
Parameters:
248
- order_book_ids (str|list[str]): Instrument ID(s)
249
- count (int): Number of periods to retrieve
250
- fields (list, optional): Specific fields to retrieve
251
- expect_df (bool): Return DataFrame instead of dict
252
253
Returns:
254
dict|pandas.DataFrame: Stock connect trading data
255
"""
256
```
257
258
### Financial Factor Data
259
260
Functions for accessing quantitative factors and financial metrics.
261
262
```python { .api }
263
def get_factor(order_book_ids, factor_names, start_date, end_date, universe=None, expect_df=False):
264
"""
265
Multi-factor data.
266
267
Parameters:
268
- order_book_ids (str|list[str]): Instrument ID(s)
269
- factor_names (str|list[str]): Factor name(s)
270
- start_date (str|datetime): Start date
271
- end_date (str|datetime): End date
272
- universe (str, optional): Universe filter
273
- expect_df (bool): Return DataFrame instead of dict
274
275
Returns:
276
dict|pandas.DataFrame: Factor data
277
"""
278
279
def get_securities_margin(order_book_ids, count=1, fields=None, expect_df=False):
280
"""
281
Securities margin data.
282
283
Parameters:
284
- order_book_ids (str|list[str]): Instrument ID(s)
285
- count (int): Number of periods to retrieve
286
- fields (list, optional): Specific fields
287
- expect_df (bool): Return DataFrame instead of dict
288
289
Returns:
290
dict|pandas.DataFrame: Margin trading data
291
"""
292
293
def get_shares(order_book_ids, count=1, fields=None, expect_df=False):
294
"""
295
Share count data.
296
297
Parameters:
298
- order_book_ids (str|list[str]): Instrument ID(s)
299
- count (int): Number of periods to retrieve
300
- fields (list, optional): Fields ('total_shares', 'float_shares', etc.)
301
- expect_df (bool): Return DataFrame instead of dict
302
303
Returns:
304
dict|pandas.DataFrame: Share count data
305
"""
306
307
def get_turnover_rate(order_book_ids, count=1, fields=None, expect_df=False):
308
"""
309
Turnover rate data.
310
311
Parameters:
312
- order_book_ids (str|list[str]): Instrument ID(s)
313
- count (int): Number of periods to retrieve
314
- fields (list, optional): Specific fields
315
- expect_df (bool): Return DataFrame instead of dict
316
317
Returns:
318
dict|pandas.DataFrame: Turnover rate data
319
"""
320
321
def get_price_change_rate(order_book_ids, count=1, expect_df=False):
322
"""
323
Price change rate data.
324
325
Parameters:
326
- order_book_ids (str|list[str]): Instrument ID(s)
327
- count (int): Number of periods to retrieve
328
- expect_df (bool): Return DataFrame instead of dict
329
330
Returns:
331
dict|pandas.DataFrame: Price change rate data
332
"""
333
```
334
335
### Corporate Actions
336
337
Functions for accessing corporate action data including splits and dividends.
338
339
```python { .api }
340
def get_split(order_book_ids, start_date=None):
341
"""
342
Stock split adjustment data.
343
344
Parameters:
345
- order_book_ids (str|list[str]): Instrument ID(s)
346
- start_date (str|datetime, optional): Start date for splits
347
348
Returns:
349
pandas.DataFrame: Split data with dates and ratios
350
"""
351
```
352
353
### Futures Market Data
354
355
Functions for accessing futures-specific market data and contract information.
356
357
```python { .api }
358
def get_dominant_future(underlying_symbol, rule=0):
359
"""
360
Get dominant future contract.
361
362
Parameters:
363
- underlying_symbol (str): Underlying asset symbol
364
- rule (int): Dominance rule (0=volume, 1=open_interest)
365
366
Returns:
367
str: Dominant contract instrument ID
368
"""
369
```
370
371
### Financial Statements
372
373
Functions for accessing fundamental financial data from company reports.
374
375
```python { .api }
376
def get_pit_financials(fields, quarter=None, interval=None, order_book_ids=None, if_adjusted='all'):
377
"""
378
Point-in-time financial data.
379
380
Parameters:
381
- fields (str|list[str]): Financial statement fields
382
- quarter (str, optional): Specific quarter ('2020Q1')
383
- interval (str, optional): Data interval
384
- order_book_ids (str|list[str], optional): Instrument filter
385
- if_adjusted (str): Adjustment type ('all', 'none')
386
387
Returns:
388
pandas.DataFrame: Financial statement data
389
"""
390
391
def get_pit_financials_ex(order_book_ids, fields, count, statements='latest'):
392
"""
393
Enhanced PIT financial data.
394
395
Parameters:
396
- order_book_ids (str|list[str]): Instrument ID(s)
397
- fields (str|list[str]): Financial fields
398
- count (int): Number of periods
399
- statements (str): Statement type filter
400
401
Returns:
402
pandas.DataFrame: Enhanced financial data
403
"""
404
405
def get_current_performance(order_book_id, quarter, fields=None):
406
"""
407
Current performance data.
408
409
Parameters:
410
- order_book_id (str): Instrument identifier
411
- quarter (str): Quarter specification
412
- fields (list, optional): Specific performance fields
413
414
Returns:
415
dict: Performance metrics
416
"""
417
```
418
419
### Data Query Interface
420
421
SQL-like query interface for flexible data access.
422
423
```python { .api }
424
def query(*entities):
425
"""
426
SQL-like query interface for data.
427
428
Parameters:
429
- entities: Query entities and filters
430
431
Returns:
432
QueryResult: Query result object with data access methods
433
434
Usage:
435
from rqalpha.apis import query
436
result = query(fundamentals.income_statement.revenue).filter(
437
fundamentals.stockcode.in_(["000001.XSHE", "000002.XSHE"])
438
)
439
"""
440
```
441
442
## Data Usage Examples
443
444
### Historical Data Analysis
445
446
```python
447
def init(context):
448
# Get 252 days of daily data
449
hist_data = history_bars("000001.XSHE", 252, "1d", fields=["close", "volume"])
450
451
# Calculate moving average
452
ma_20 = hist_data["close"][-20:].mean()
453
ma_60 = hist_data["close"][-60:].mean()
454
455
context.ma_signal = ma_20 > ma_60
456
457
def handle_bar(context, bar_dict):
458
# Get recent 5-minute data
459
recent_data = history_bars("000001.XSHE", 12, "5m")
460
461
# Current snapshot
462
snapshot = current_snapshot("000001.XSHE")
463
bid_price = snapshot["bid_price"]
464
ask_price = snapshot["ask_price"]
465
```
466
467
### Universe Construction
468
469
```python
470
def init(context):
471
# Get all stocks
472
all_stocks = all_instruments(type="CS")
473
474
# Filter by industry
475
tech_stocks = get_industry("软件服务", source="sw")
476
477
# Get index components
478
hs300_stocks = index_components("000300.XSHG")
479
480
# Combine filters
481
context.universe = list(set(tech_stocks) & set(hs300_stocks))
482
update_universe(context.universe)
483
484
def handle_bar(context, bar_dict):
485
# Get factor data for universe
486
factor_data = get_factor(
487
context.universe,
488
["pe_ratio", "pb_ratio", "roe"],
489
context.now,
490
context.now
491
)
492
```
493
494
### Calendar and Timing
495
496
```python
497
def before_trading(context):
498
# Check if today is month end
499
next_trading_day = get_next_trading_date(context.now)
500
if next_trading_day.month != context.now.month:
501
context.is_month_end = True
502
else:
503
context.is_month_end = False
504
505
# Get trading dates for the month
506
month_start = context.now.replace(day=1)
507
trading_days = get_trading_dates(month_start, context.now)
508
context.trading_days_in_month = len(trading_days)
509
```