:param code: code:  字符串str eg 600085
    :param start:  字符串str 开始日期 eg 2011-01-01
    :param end:  字符串str 结束日期 eg 2011-05-01
    :param if_drop_index: Ture False ， dataframe drop index or not
    :param collections:  mongodb 数据库
    :return:
160365
def QA_fetch_index_day_adv(
        code,
        start, end=None,
        if_drop_index=True,
        # 🛠 todo collections 参数没有用到， 且数据库是固定的， 这个变量后期去掉
        collections=DATABASE.index_day):
    '''
    
    '''
    '获取指数日线'
    end = start if end is None else end
    start = str(start)[0:10]
    end = str(end)[0:10]

    # 🛠 todo 报告错误 如果开始时间 在 结束时间之后
    # 🛠 todo 如果相等

    res = QA_fetch_index_day(code, start, end, format='pd')
    if res is None:
        print("QA Error QA_fetch_index_day_adv parameter code=%s start=%s end=%s call QA_fetch_index_day return None" % (
            code, start, end))
        return None
    else:
        res_set_index = res.set_index(['date', 'code'], drop=if_drop_index)
        # if res_set_index is None:
        #     print("QA Error QA_fetch_index_day_adv set index 'date, code' return None")
        #     return None
        return QA_DataStruct_Index_day(res_set_index)
993292
def QA_SU_save_index_day(client=DATABASE, ui_log=None, ui_progress=None):
    

    __index_list = QA_fetch_get_stock_list('index')
    coll = client.index_day
    coll.create_index(
        [('code',
          pymongo.ASCENDING),
         ('date_stamp',
          pymongo.ASCENDING)]
    )
    err = []

    def __saving_work(code, coll):

        try:
            ref_ = coll.find({'code': str(code)[0:6]})
            end_time = str(now_time())[0:10]
            if ref_.count() > 0:
                start_time = ref_[ref_.count() - 1]['date']

                QA_util_log_info(
                    '##JOB04 Now Saving INDEX_DAY==== \n Trying updating {} from {} to {}'
                        .format(code,
                                start_time,
                                end_time),
                    ui_log=ui_log
                )

                if start_time != end_time:
                    coll.insert_many(
                        QA_util_to_json_from_pandas(
                            QA_fetch_get_index_day(
                                str(code),
                                QA_util_get_next_day(start_time),
                                end_time
                            )
                        )
                    )
            else:
                try:
                    start_time = '1990-01-01'
                    QA_util_log_info(
                        '##JOB04 Now Saving INDEX_DAY==== \n Trying updating {} from {} to {}'
                            .format(code,
                                    start_time,
                                    end_time),
                        ui_log=ui_log
                    )
                    coll.insert_many(
                        QA_util_to_json_from_pandas(
                            QA_fetch_get_index_day(
                                str(code),
                                start_time,
                                end_time
                            )
                        )
                    )
                except:
                    start_time = '2009-01-01'
                    QA_util_log_info(
                        '##JOB04 Now Saving INDEX_DAY==== \n Trying updating {} from {} to {}'
                            .format(code,
                                    start_time,
                                    end_time),
                        ui_log=ui_log
                    )
                    coll.insert_many(
                        QA_util_to_json_from_pandas(
                            QA_fetch_get_index_day(
                                str(code),
                                start_time,
                                end_time
                            )
                        )
                    )
        except Exception as e:
            QA_util_log_info(e, ui_log=ui_log)
            err.append(str(code))
            QA_util_log_info(err, ui_log=ui_log)

    for i_ in range(len(__index_list)):
        # __saving_work('000001')
        QA_util_log_info(
            'The {} of Total {}'.format(i_,
                                        len(__index_list)),
            ui_log=ui_log
        )

        strLogProgress = 'DOWNLOAD PROGRESS {} '.format(
            str(float(i_ / len(__index_list) * 100))[0:4] + '%'
        )
        intLogProgress = int(float(i_ / len(__index_list) * 10000.0))
        QA_util_log_info(
            strLogProgress,
            ui_log=ui_log,
            ui_progress=ui_progress,
            ui_progress_int_value=intLogProgress
        )
        __saving_work(__index_list.index[i_][0], coll)
    if len(err) < 1:
        QA_util_log_info('SUCCESS', ui_log=ui_log)
    else:
        QA_util_log_info(' ERROR CODE \n ', ui_log=ui_log)
        QA_util_log_info(err, ui_log=ui_log)
634261
def QA_fetch_stock_terminated(collections=DATABASE.stock_terminated):
    ''
    # 🛠todo  转变成 dataframe 类型数据
    return pd.DataFrame([item for item in collections.find()]).drop('_id', axis=1, inplace=False).set_index('code', drop=False)
874447
def _get_date_range_query(self, start_date, end_date, timespan= 'DAY', date_field= None):
        '''
        
        '''
        if date_field is None:
            date_field = self._date_field
        query ={'q':'*:*',
                'rows':0,
                'facet':'true',
                'facet.range': date_field,
                'facet.range.gap': '+1{}'.format(timespan),
                'facet.range.end': '{}'.format(end_date),
                'facet.range.start': '{}'.format(start_date),
                'facet.range.include': 'all'
                }
        if self._per_shard:
            query['distrib'] = 'false'
        return query
848186
def status_codes_by_date_stats():
    

    def date_counter(queryset):
        return dict(Counter(map(
            lambda dt: ms_since_epoch(datetime.combine(
                make_naive(dt), datetime.min.time())),
            list(queryset.values_list('datetime', flat=True)))))

    codes = {low: date_counter(
        RequestLog.objects.filter(status_code__gte=low, status_code__lt=high))
        for low, high in ((200, 300), (300, 400), (400, 500))}
    codes[500] = date_counter(RequestLog.objects.filter(status_code__gte=500))
    codes['attacks'] = date_counter(RequestLog.objects.filter(
        status_code__in=(400, 444, 502)))

    stats = {}
    for code in (200, 300, 400, 500, 'attacks'):
        for date, count in codes[code].items():
            if stats.get(date, None) is None:
                stats[date] = {200: 0, 300: 0, 400: 0, 500: 0, 'attacks': 0}
            stats[date][code] += count

    stats = sorted([(k, v) for k, v in stats.items()], key=lambda x: x[0])
    return stats
765531
def start_date(self):
        
        if self.start_==None:
            if len(self.time_index_max) > 0:
                return str(min(self.time_index_max))[0:10]
            else:
                print(
                    RuntimeWarning(
                        'QAACCOUNT: THIS ACCOUNT DOESNOT HAVE ANY TRADE'
                    )
                )
        else:
            return self.start_
1125282
def set_date_range(self, start=None, end=None):
        
        start = self._start if start is None else pd.to_datetime(start)
        end = self._end if end is None else pd.to_datetime(end)
        self._update(self._prices.loc[start:end])
802812
def _check_zone_exception_for_date(self, item, timestamp, data_dict, data_index_dict):
        
        if item in data_index_dict:
            for item in data_index_dict[item]:

                # startdate < timestamp
                if const.START in data_dict[item] and not const.END in data_dict[item]:
                    if data_dict[item][const.START] < timestamp:
                        return data_dict[item][const.CQZ]

                # enddate > timestamp
                elif not const.START in data_dict[item] and const.END in data_dict[item]:
                    if data_dict[item][const.END] > timestamp:
                        return data_dict[item][const.CQZ]

                # startdate > timestamp > enddate
                elif const.START in data_dict[item] and const.END in data_dict[item]:
                    if data_dict[item][const.START] < timestamp \
                            and data_dict[item][const.END] > timestamp:
                        return data_dict[item][const.CQZ]

                # no startdate or enddate available
                elif not const.START in data_dict[item] and not const.END in data_dict[item]:
                        return data_dict[item][const.CQZ]

        raise KeyError
704698
def time_slice(self, start, end):
        
        if start < self.start_time:
            raise ValueError('Time series does not contain a time as early as %s' % start)

        if end > self.end_time:
            raise ValueError('Time series does not contain a time as late as %s' % end)

        start_idx = int((start - self.start_time) * self.sample_rate)
        end_idx = int((end - self.start_time) * self.sample_rate)
        return self[start_idx:end_idx]
1032141
def collection(self, code):
        
        result = None
        result = self.dispatcher(
            'get_collection',
            code=code
        )

        if not result:
            logger.info('Collection not found for: %s', code)
            return None

        return result
985651
function(mongoDate) {
	//console.log(mongoDate);
	var jsDate = new Date(mongoDate);
	var d = zeroPad(jsDate.getDate(),2);
	var m = zeroPad(jsDate.getMonth()+1,2);
	var y = jsDate.getFullYear();
	var h = zeroPad(jsDate.getHours(),2);
	var mn = zeroPad(jsDate.getMinutes(),2);
	var s = zeroPad(jsDate.getSeconds(),2);
	var pickerDate = y+'-'+m+'-'+d+'T'+h+':'+mn+':'+s;
	//console.log(pickerDate);
	return pickerDate;
}
1336315
def users(self, drop_collections = True):
        
        base_df = self._data
        if drop_collections is True:
            out_df = self._drop_collections(base_df)
        else:
            out_df = base_df
        return out_df
961106
def __findRange(self, excelLib, start, end):
        '''  '''
        inc = 1
        low = 0
        high = 0
        dates = excelLib.readCol(0, 1)

        for index, date in enumerate(dates):
            if int(start) <= int(date):
                low = index + inc
                break

        if low:
            for index, date in reversed(list(enumerate(dates))):
                if int(date) <= int(end):
                    high = index + inc
                    break

        return low, high
596804
def index(self, date):
        
        for (i, (start, end, ruler)) in enumerate(self.table):
            if start <= date.jd <= end:
                return i
        return None
762956
def _get_range_timestamp_key(self, start: Key, end: Key,
                                 count: int = 0) -> List[Tuple[Key, Any]]:
        
        raise NotImplementedError()
308584
def QA_get_tick(code, start, end, market):
    
    res = None
    if market == MARKET_TYPE.STOCK_CN:
        res = QATdx.QA_fetch_get_stock_transaction(code, start, end)
    elif market == MARKET_TYPE.FUTURE_CN:
        res = QATdx.QA_fetch_get_future_transaction(code, start, end)
    return res
938761
def was_run_code(self, get_all=True):
        """"""
        if self.stored is None:
            return ""
        else:
            if get_all:
                self.stored = ["\n".join(self.stored)]
            return self.stored[-1]