-
Notifications
You must be signed in to change notification settings - Fork 2
/
query.py
386 lines (360 loc) · 10.4 KB
/
query.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import datetime
import numpy
import pandas as pd
from pandas import DataFrame
from QUANTAXIS.QAUtil import (
DATABASE,
QA_Setting,
QA_util_date_stamp,
QA_util_date_valid,
QA_util_dict_remove_key,
QA_util_log_info,
QA_util_code_tolist,
QA_util_date_str2int,
QA_util_date_int2str,
QA_util_sql_mongo_sort_DESCENDING,
QA_util_time_stamp,
QA_util_to_json_from_pandas,
trade_date_sse
)
from QUANTAXIS.QAData.financial_mean import financial_dict
def filter_dates(start, end):
'''
filter dates method
:param start, end: can be str/int of 2019, 201901, '2019-01', '2019-01-01'
:return: string eg: '2019-01-01'
'''
begining_date = '1990-01-01'
start_day = '-01'
start_month = '-01-01'
end_day = '-31'
end_month = '-12-31'
if start == 'all':
start = begining_date
end = str(datetime.date.today())
return start, end
start = str(start)
end = start if end is None else str(end)
if len(start) == 4:
start += start_month
elif len(start) == 6:
start = start[:4] + '-' + start[-2:] + start_day
elif len(start) == 7:
start += start_day
if not QA_util_date_valid(start):
start = begining_date
if len(end) == 4:
end += end_month
elif len(end) == 6:
end = end[:4] + '-' + end[-2:] + end_day
elif len(end) == 7:
end += end_day
if QA_util_date_valid(end):
return start, end
else:
return None, None
def _database_query_dict(code, start, end, frequence=''):
'''
database query string method
:param code: stock/future/index code list
:param start, end: date string
:param frequence: minute frequence, default is empty string
:return: dict of database query depends on frequence
'''
if frequence:
return {
'code': {
'$in': code
},
"time_stamp": {
"$gte": QA_util_time_stamp(start),
"$lte": QA_util_time_stamp(end)
},
'type': frequence
}
else:
return {
'code': {
'$in': code
},
"date_stamp": {
"$lte": QA_util_date_stamp(end),
"$gte": QA_util_date_stamp(start)
}
}
def _database_collections(data_type, code, start, end, frequence=''):
'''
database collection method
:param data_type: stock_day, stock_min etc
:param code: stock/future/index code list
:param start, end: date string
:param frequence: minute frequence, default is empty string
:return: dict of database collection configuration
'''
query = _database_query_dict(
code=code,
start=start,
end=end,
frequence=frequence
)
database_d = {
'stock_day': {
'collection':
DATABASE.stock_day,
'query':
query,
'columns': [
'code',
'open',
'high',
'low',
'close',
'volume',
'amount',
'datetime'
]
},
'stock_min': {
'collection':
DATABASE.stock_min,
'query':
query,
'columns': [
'code',
'open',
'high',
'low',
'close',
'volume',
'amount',
'datetime',
'type'
]
},
'index_day': {
'collection':
DATABASE.index_day,
'query':
query,
'columns': [
'code',
'open',
'high',
'low',
'close',
'up_count',
'down_count',
'volume',
'amount',
'datetime'
]
},
'index_min': {
'collection':
DATABASE.index_min,
'query':
query,
'columns': [
'code',
'open',
'high',
'low',
'close',
'up_count',
'down_count',
'volume',
'amount',
'datetime',
'time_stamp',
'date',
'type'
]
},
'future_day': {
'collection':
DATABASE.future_day,
'query':
query,
'columns': [
'code',
'open',
'high',
'low',
'close',
'position',
'price',
'trade',
'datetime'
]
},
'future_min': {
'collection':
DATABASE.future_min,
'query':
query,
'columns': [
'code',
'open',
'high',
'low',
'close',
'position',
'price',
'trade',
'datetime',
'tradetime',
'time_stamp',
'date',
'type'
]
}
}
if data_type in database_d.keys():
return database_d[data_type]
else:
return 'please provide the correct data type: {}'.format(
', '.join(database_d.keys())
)
def QA_list_fetch(data_type):
'''
database collection method
:param data_type: stock_day, stock_min etc
:return: dataframe of given data_type
'''
list_collections = {
'stock_list': {
'collection': DATABASE.stock_list
},
'index_list': {
'collection': DATABASE.index_list
},
'future_list': {
'collection': DATABASE.future_list
},
'etf_list': {
'collection': DATABASE.etf_list
},
}
if data_type in list_collections.keys():
collections = list_collections[data_type]['collection']
res = pd.DataFrame([item for item in collections.find()]).drop(
'_id',
axis=1,
inplace=False
).set_index(
'code',
drop=False
)
if len(res) == 0:
print(
"QA Error QA_data_fetch_adv call item for item in collections.find() return 0 item, maybe the DATABASE.{} is empty!"
.format(data_type)
)
return None
else:
return res
else:
return None
def QA_data_fetch(
code='',
start='all',
end=None,
data_type='stock_day',
frequence='',
format='numpy'
):
"""'fetch data from database'
:param code: code list of stock, index, future, etf
:param start: date of start, can be str/int of 2019, 201901, '2019-01', '2019-01-01'
:param end: date of end, can be str/int of 2019, 201901, '2019-01', '2019-01-01'
:param data_type: stock_day, stock_min etc
:param frequence: minute freq of min data like 15, 30min
Returns:
[type] -- [description]
感谢@几何大佬的提示
https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-the-specified-fields-and-the-id-field-only
"""
start, end = filter_dates(start, end)
if end is None:
QA_util_log_info(
'QA Error QA_fetch_stock_day data parameter start=%s end=%s is not right'
% (start,
end)
)
return None
if frequence:
if str(frequence).split('m')[0] in ['1', '5', '15', '30', '60']:
frequence = str(frequence).split('m')[0] + 'min'
start = '{} 09:30:00'.format(start)
end = '{} 15:00:00'.format(end)
else:
print(
"QA Error QA_fetch_stock_min_adv parameter frequence=%s is none of 1min 1m 5min 5m 15min 15m 30min 30m 60min 60m"
% frequence
)
return None
db_collection = _database_collections(
data_type=data_type,
code=code,
start=start,
end=end,
frequence=frequence
)
# code checking
# only fot stock currenting
# todo: check future code
code = QA_util_code_tolist(code)
__data = []
# return None if db_collection is an error message
if isinstance(db_collection, str):
print(db_collection)
return None
collections = db_collection['collection']
try:
cursor = collections.find(
db_collection['query'],
{"_id": 0},
batch_size=10000
)
res = pd.DataFrame([item for item in cursor])
if 'datetime' not in res.columns:
try:
res.rename({'date': 'datetime'}, axis=1, inplace=True)
except:
pass
else:
res = res.assign(type=frequence)
if 'vol' in res.columns:
res = res.assign(
volume=res.vol,
datetime=pd.to_datetime(res.datetime)
).query('volume>1').drop_duplicates(['datetime',
'code']).set_index(
'datetime',
drop=False
)
else:
res = res.assign(datetime=pd.to_datetime(res.datetime)
).drop_duplicates(['datetime',
'code']).set_index(
'datetime',
drop=False
)
res = round(res[db_collection['columns']], 2)
except:
res = None
if format in ['P', 'p', 'pandas', 'pd']:
return res
elif format in ['json', 'dict']:
return QA_util_to_json_from_pandas(res)
# 多种数据格式
elif format in ['n', 'N', 'numpy']:
return numpy.asarray(res)
elif format in ['list', 'l', 'L']:
return numpy.asarray(res).tolist()
else:
print(
"QA Error QA_fetch_stock_day format parameter %s is none of \"P, p, pandas, pd , json, dict , n, N, numpy, list, l, L, !\" "
% format
)
return None