Example #1
0
def get_fundamentals(table,
                     symbols,
                     start_date,
                     end_date,
                     fields=None,
                     filter=None,
                     order_by=None,
                     limit=1000,
                     df=False):
    """
    查询基本面财务数据
    """
    fields_str, fields_list = standard_fields(fields, letter_upper=True)
    start_date = utils.to_datestr(start_date)
    end_date = utils.to_datestr(end_date)
    data = fundamentalapi.get_fundamentals(table=table,
                                           symbols=symbols,
                                           start_date=start_date,
                                           end_date=end_date,
                                           fields=fields_str,
                                           filter=filter,
                                           order_by=order_by,
                                           limit=limit)

    if df:
        data = pd.DataFrame(data)
        if fields_list:
            fields_list = ['symbol', 'pub_date', 'end_date'] + fields_list
            columns = [field for field in fields_list if field in data.columns]
            data = data[columns]

    return data
Example #2
0
    def get_trading_dates(self, exchange, start_date, end_date):
        # type: (Text, GmDate, GmDate) -> List[Text]
        """
        查询交易日列表
        如果指定的市场不存在, 返回空列表. 有值的话,返回 yyyy-mm-dd 格式的列表
        """
        self._init_addr()

        exchange = utils.to_exchange(exchange)
        sdate = utils.to_datestr(start_date)
        edate = utils.to_datestr(end_date)
        if not exchange:
            return []
        if not sdate:
            return []
        if not end_date:
            edate = Datetime.now().strftime('%Y-%m-%d')
        req = GetTradingDatesReq(exchange=exchange, start_date=sdate, end_date=edate)
        resp = self.stub.GetTradingDates(req, metadata=[
            (str('authorization'), context.token),
            (str('sdk-lang'), context.sdk_lang),
            (str('sdk-version'), context.sdk_version),
            (str('sdk-arch'), context.sdk_arch),
            (str('sdk-os'), context.sdk_os),
        ])

        if len(resp.dates) == 0:
            return []
        ds = []
        for t in resp.dates:  # type: Timestamp
            ds.append(utils.utc_datetime2beijing_datetime(t.ToDatetime()).strftime('%Y-%m-%d'))

        return ds
Example #3
0
    def get_history_instruments(self, symbols, fields=None, start_date=None, end_date=None):
        """
        返回指定的symbols的标的日指标数据
        """
        self._init_addr()
        symbols = load_to_list(symbols)
        start_date = utils.to_datestr(start_date)
        end_date = utils.to_datestr(end_date)

        if not start_date:
            start_date = ''
        if not end_date:
            end_date = ''

        req = GetHistoryInstrumentsReq(symbols=','.join(symbols),
                                       fields=fields,
                                       start_date=start_date, end_date=end_date)
        resp = self.stub.GetHistoryInstruments(req, metadata=[
            (str('authorization'), context.token),
            (str('sdk-lang'), context.sdk_lang),
            (str('sdk-version'), context.sdk_version),
            (str('sdk-arch'), context.sdk_arch),
            (str('sdk-os'), context.sdk_os),
        ])
        result = [protobuf_to_dict(res_order, including_default_value_fields=True) for res_order in resp.data]
        for info in result:
            created_at_val = info.get('created_at', None)
            if isinstance(created_at_val, Datetime):
                info['trade_date'] = utils.utc_datetime2beijing_datetime(created_at_val)
                info.pop('created_at')
        return result
Example #4
0
    def get_fundamentals_n(self, table, symbols, end_date, fields=None, filter=None, order_by=None, count=1):
        """
        查询基本面财务数据,每个股票在end_date的前n条
        """
        self._init_addr()

        end_date = utils.to_datestr(end_date)

        if isinstance(symbols, string_types):
            symbols = [s.strip() for s in symbols.split(',') if s.strip()]

        req = GetFundamentalsNReq(table=table, end_date=end_date, fields=fields,
                                  symbols=','.join(symbols), filter=filter,
                                  order_by=order_by, count=count)

        resp = self.stub.GetFundamentalsN(req, metadata=[
            (str('authorization'), context.token),
            (str('sdk-lang'), context.sdk_lang),
            (str('sdk-version'), context.sdk_version),
            (str('sdk-arch'), context.sdk_arch),
            (str('sdk-os'), context.sdk_os),
        ])
        result = []
        for item in resp.data:  # type: GetFundamentalsRsp.Fundamental
            r = {
                'symbol': item.symbol,
                'pub_date': utils.utc_datetime2beijing_datetime(item.pub_date.ToDatetime()),
                'end_date': utils.utc_datetime2beijing_datetime(item.end_date.ToDatetime()),
            }
            r.update(item.fields)
            result.append(r)

        return result
Example #5
0
    def get_next_trading_date(self, exchange, date):
        # type: (Text, GmDate) -> TextNone
        """
        返回指定日期的下一个交易日
        @:param exchange: 交易市场
        @:param date: 指定日期, 可以是datetime.date 或者 datetime.datetime 类型. 或者是 yyyy-mm-dd 或 yyyymmdd 格式的字符串
        @:return 返回下一交易日, 为 yyyy-mm-dd 格式的字符串, 如果不存在则返回None
        """
        self._init_addr()

        exchange = utils.to_exchange(exchange)
        date_str = utils.to_datestr(date)
        if not date_str or not exchange:
            return None

        req = GetNextTradingDateReq(exchange=exchange, date=date_str)
        resp = self.stub.GetNextTradingDate(req, metadata=[
            (str('authorization'), context.token),
            (str('sdk-lang'), context.sdk_lang),
            (str('sdk-version'), context.sdk_version),
            (str('sdk-arch'), context.sdk_arch),
            (str('sdk-os'), context.sdk_os),
        ])
        rdate = resp.date  # type: Timestamp
        if not rdate.ListFields():  # 这个说明查询结果没有
            return None
        return utils.utc_datetime2beijing_datetime(rdate.ToDatetime()).strftime('%Y-%m-%d')
Example #6
0
    def get_continuous_contracts(self, csymbol, start_date=None, end_date=None):
        # type: (Text, GmDate, GmDate) -> List[Dict[Text, Any]]

        self._init_addr()

        start_date = utils.to_datestr(start_date)
        end_date = utils.to_datestr(end_date)

        req = GetContinuousContractsReq(csymbol=csymbol, start_date=start_date, end_date=end_date)
        resp = self.stub.GetContinuousContracts(req, metadata=[
            (str('authorization'), context.token),
            (str('sdk-lang'), context.sdk_lang),
            (str('sdk-version'), context.sdk_version),
            (str('sdk-arch'), context.sdk_arch),
            (str('sdk-os'), context.sdk_os),
        ])

        result = []
        for cc in resp.data:  # type: ContinuousContract
            row = {'symbol': cc.symbol, 'trade_date': utils.utc_datetime2beijing_datetime(cc.created_at.ToDatetime())}
            result.append(row)
        return result
Example #7
0
    def get_history_constituents(self, index, start_date=None, end_date=None):
        # type: (TextNone, GmDate, GmDate) -> List[Dict[Text, Any]]
        """
        查询指数历史成分股
        返回的list每项是个字典,包含的key值有:
        trade_date: 交易日期(datetime类型)
        constituents: 一个字典. 每个股票的sybol做为key值, weight做为value值
        """
        self._init_addr()

        start_date = utils.to_datestr(start_date)
        end_date = utils.to_datestr(end_date)

        if not start_date:
            start_date = Date.today()
        else:
            start_date = Datetime.strptime(start_date, '%Y-%m-%d').date()

        if not end_date:
            end_date = Date.today()
        else:
            end_date = Datetime.strptime(end_date, '%Y-%m-%d').date()

        req = GetConstituentsReq(index=index, start_date=start_date.strftime('%Y-%m-%d'),
                                 end_date=end_date.strftime('%Y-%m-%d'))
        resp = self.stub.GetConstituents(req, metadata=[
            (str('authorization'), context.token),
            (str('sdk-lang'), context.sdk_lang),
            (str('sdk-version'), context.sdk_version),
            (str('sdk-arch'), context.sdk_arch),
            (str('sdk-os'), context.sdk_os),
        ])

        return [
            {'trade_date': utils.utc_datetime2beijing_datetime(item.created_at.ToDatetime()),
             'constituents': dict(item.constituents)}
            for item in resp.data
        ]
Example #8
0
    def get_dividend(self, symbol, start_date, end_date=None):
        # type: (Text, GmDate, GmDate) -> List[Dict[Text, Any]]
        """
        查询分红送配
        """
        self._init_addr()

        if not symbol or not start_date:
            return []
        sym_tmp = symbol.split('.')  # List[Text]
        sym_tmp[0] = sym_tmp[0].upper()
        symbol = '.'.join(sym_tmp)

        if not end_date:
            end_date = Datetime.now().strftime('%Y-%m-%d')
        start_date = utils.to_datestr(start_date)
        end_date = utils.to_datestr(end_date)

        req = GetDividendsReq(symbol=symbol, start_date=start_date, end_date=end_date)
        resp = self.stub.GetDividends(req, metadata=[
            (str('authorization'), context.token),
            (str('sdk-lang'), context.sdk_lang),
            (str('sdk-version'), context.sdk_version),
            (str('sdk-arch'), context.sdk_arch),
            (str('sdk-os'), context.sdk_os),
        ])
        result = []
        fields = ['symbol', 'cash_div', 'share_div_ratio', 'share_trans_ratio', 'allotment_ratio', 'allotment_price',
                  'created_at']
        for divi in resp.data:  # type: Dividend
            row = dict()
            utils.protomessage2dict(divi, row, *fields)
            created_at_val = row.get('created_at', None)
            if isinstance(created_at_val, Datetime):
                row['created_at'] = utils.utc_datetime2beijing_datetime(created_at_val)
            result.append(row)
        return result