Esempio n. 1
0
def is_suspended(order_book_ids, start_date=None, end_date=None):
    """获取停牌信息
    :param order_book_ids: 可转债ID
    :param start_date: 开始日期, 如'2013-01-04' (Default value = None)
    :param end_date: 结束日期,如'2014-01-04' (Default value = None)
    :returns: DataFrame
    """
    order_book_ids = ensure_order_book_ids(order_book_ids)
    if len(order_book_ids) == 1:
        instrument = instruments(order_book_ids[0], market="cn")
        start_date, end_date = ensure_dates_base_on_listed_date(
            instrument, start_date, end_date, "cn")
        if start_date is None:
            return
    start_date, end_date = ensure_date_range(start_date, end_date)

    trading_dates = pd.to_datetime(
        get_trading_dates(start_date, end_date, market="cn"))
    df = pd.DataFrame(data=False, columns=order_book_ids, index=trading_dates)
    data = get_client().execute("convertible.is_suspended",
                                order_book_ids,
                                start_date,
                                end_date,
                                market="cn")
    for (order_book_id, date) in data:
        date = to_datetime(date)
        df.at[date, order_book_id] = True
    return df
Esempio n. 2
0
def is_st_stock(order_book_ids, start_date=None, end_date=None, market="cn"):
    """判断股票在给定的时间段是否是ST股, 返回值为一个DataFrame

    :param order_book_ids: 股票 id
    :param start_date:  (Default value = None)
    :param end_date:  (Default value = None)
    :param market:  (Default value = "cn")

    """
    order_book_ids = ensure_order_book_ids(order_book_ids,
                                           type="CS",
                                           market=market)

    if len(order_book_ids) == 1:
        instrument = instruments(order_book_ids[0], market=market)
        start_date, end_date = ensure_dates_base_on_listed_date(
            instrument, start_date, end_date, market)
        if start_date is None:
            return

    start_date, end_date = ensure_date_range(start_date, end_date)

    trading_dates = pd.to_datetime(
        get_trading_dates(start_date, end_date, market=market))
    data = get_client().execute("get_st_days",
                                order_book_ids,
                                start_date=start_date,
                                end_date=end_date)
    df = pd.DataFrame(data=False, columns=order_book_ids, index=trading_dates)
    for idx, dates in data.items():
        for date in dates:
            date = to_datetime(date)
            df.at[date, idx] = True
    return df
Esempio n. 3
0
def is_suspended(order_book_ids, start_date=None, end_date=None, market="cn"):
    """获取股票停牌信息

    :param order_book_ids: 股票名称
    :param start_date: 开始日期, 如'2013-01-04' (Default value = None)
    :param end_date: 结束日期,如'2014-01-04' (Default value = None)
    :param market: 地区代码, 如 'cn' (Default value = "cn")
    :returns: DataFrame

    """
    order_book_ids = ensure_order_book_ids(order_book_ids, type="CS", market=market)

    if len(order_book_ids) == 1:
        instrument = instruments(order_book_ids[0], market=market)
        start_date, end_date = ensure_dates_base_on_listed_date(instrument, start_date, end_date, market)
        if start_date is None:
            return
    if end_date is None:
        end_date = datetime.date.today()
    start_date, end_date = ensure_date_range(start_date, end_date)

    trading_dates = pd.to_datetime(get_trading_dates(start_date, end_date, market=market))
    df = pd.DataFrame(data=False, columns=order_book_ids, index=trading_dates)
    data = get_client().execute("get_suspended_days", order_book_ids, start_date, end_date, market=market)
    for idx, dates in data.items():
        for date in dates:
            date = to_datetime(int(date))
            df.at[date, idx] = True
    df.sort_index(inplace=True)
    return df
Esempio n. 4
0
def ensure_trading_date(date):
    from rqdatac.services.calendar import get_trading_dates, get_previous_trading_date, get_next_trading_date

    trading_dates = get_trading_dates(get_previous_trading_date(date),
                                      get_next_trading_date(date))
    if date not in trading_dates:
        raise ValueError(
            "expect a trading date, got {}, for reference {}".format(
                date.strftime("%Y%m%d"), trading_dates))
    return date
Esempio n. 5
0
def get_factor(order_book_ids,
               factor,
               start_date=None,
               end_date=None,
               universe=None,
               expect_df=False,
               **kwargs):
    """获取因子

    :param order_book_ids: 股票代码或代码列表
    :param factor: 如 'total_income'
    :param date: 如 date='2015-01-05', 默认为前一交易日
    :param start_date: 开始日期'2015-01-05', 默认为前一交易日, 最小起始日期为'2000-01-04'
    :param end_date: 结束日期
    :param universe: 股票池,默认为全A股
    :param expect_df: 返回 MultiIndex DataFrame (Default value = False)
    :returns: pd.DataFrame
    """

    order_book_ids = ensure_order_book_ids(order_book_ids, type="CS")
    order_book_ids = list(set(order_book_ids))

    factor = ensure_list_of_string(factor)
    factor = list(OrderedDict.fromkeys(factor))

    if start_date and end_date:
        start_date, end_date = ensure_date_range(start_date, end_date,
                                                 datetime.timedelta(days=15))
        if start_date < 20000104:
            warnings.warn(
                "start_date is earlier than 2000-01-04, adjusted to 2000-01-04"
            )
            start_date = 20000104
    elif start_date:
        raise ValueError("Expect end_date")
    elif end_date:
        raise ValueError("Expect start_date")
    else:
        date = kwargs.pop("date", None)
        date = ensure_date_int(
            date or get_previous_trading_date(datetime.date.today()))
        start_date = end_date = date

    if kwargs:
        raise ValueError('unknown kwargs: {}'.format(kwargs))

    if universe is not None:
        universe = ensure_string(universe, "universe")
        if universe != "all":
            universe = ensure_order_book_id(universe, type="INDX")
            from rqdatac import index_components
            allowed_order_book_ids = set(
                index_components(universe, date=end_date) or [])
            not_permit_order_book_ids = [
                order_book_id for order_book_id in order_book_ids
                if order_book_id not in allowed_order_book_ids
            ]
            if not_permit_order_book_ids:
                warnings.warn(
                    "%s not in universe pool, value of those order_book_ids will always be NaN"
                    % not_permit_order_book_ids)

    data = get_client().execute("get_factor_from_store",
                                order_book_ids,
                                factor,
                                start_date,
                                end_date,
                                universe=universe)

    if not data:
        return

    factor_value_length = len(data[0][2])
    if factor_value_length == 0:
        return

    dates = pd.to_datetime(get_trading_dates(start_date, end_date))
    if len(dates) > factor_value_length:
        _get_factor_warning_msg(dates[factor_value_length], dates[-1])
        dates = dates[0:factor_value_length]

    if expect_df or len(factor) > 1:
        order_book_id_index_map = {o: i for i, o in enumerate(order_book_ids)}
        factor_index_map = {f: i for i, f in enumerate(factor)}
        arr = np.full((len(order_book_ids) * len(dates), len(factor)), np.nan)

        for order_book_id, factor_name, values in data:
            order_book_id_index = order_book_id_index_map[order_book_id]
            factor_index = factor_index_map[factor_name]
            slice_ = slice(order_book_id_index * len(dates),
                           (order_book_id_index + 1) * len(dates), None)
            arr[slice_, factor_index] = values

        multi_index = pd.MultiIndex.from_product(
            [order_book_ids, dates], names=["order_book_id", "date"])
        df = pd.DataFrame(index=multi_index, columns=factor, data=arr)
        return df

    order_book_id_index_map = {o: i for i, o in enumerate(order_book_ids)}
    arr = np.full((len(dates), len(order_book_ids)), np.nan)
    for order_book_id, _, values in data:
        arr[:, order_book_id_index_map[order_book_id]] = values
    df = pd.DataFrame(index=dates, columns=order_book_ids, data=arr)

    if len(df.index) == 1:
        return df.iloc[0]
    if len(df.columns) == 1:
        return df[df.columns[0]]
    return df
Esempio n. 6
0
def get_securities_margin(order_book_ids,
                          start_date=None,
                          end_date=None,
                          fields=None,
                          expect_df=False,
                          market="cn"):
    """获取股票融资融券数据

    :param order_book_ids: 股票代码或代码列表
    :param start_date: 开始时间,支持 str, date, datetime, pandasTimestamp
        默认为 end_date 之前一个月 (Default value = None)
    :param end_date: 结束时间 默认为当前日期前一天 (Default value = None)
    :param fields: str 或 list 类型. 默认为 None, 返回所有字段。可选字段包括:
                   today, week, month, three_month, six_month, year, current_year, total
                   (Default value = None)
    :param expect_df: 返回 MultiIndex DataFrame (Default value = False)
    :param market: 地区代码, 如: 'cn' (Default value = "cn")
    :returns: 如果传入多个股票代码,且 fields 为多个或者 None,返回 pandas.Panel
        如果传入一只股票或者 fields 为单个字段,则返回 pandas.DataFrame
        如果传入的股票代码和字段数都是1,则返回 pandas.Series

    """

    order_book_ids = ensure_list_of_string(order_book_ids, "order_book_ids")
    all_list = []
    for order_book_id in order_book_ids:
        if order_book_id.upper() in MARGIN_SUMMARY_MAP:
            all_list.append(MARGIN_SUMMARY_MAP[order_book_id.upper()])
        else:
            inst = instruments(order_book_id, market)

            if inst.type in ["CS", "ETF", "LOF"]:
                all_list.append(inst.order_book_id)
            else:
                warnings.warn(
                    "{} is not stock, ETF, or LOF.".format(order_book_id))
    order_book_ids = all_list
    if not order_book_ids:
        raise ValueError("no valid securities in {}".format(order_book_ids))

    if fields is None:
        fields = list(MARGIN_FIELDS)
    else:
        fields = ensure_list_of_string(fields, "fields")
        check_items_in_container(fields, MARGIN_FIELDS, "fields")
        fields = ensure_order(fields, MARGIN_FIELDS)
    start_date, end_date = ensure_date_range(start_date, end_date)
    if end_date > ensure_date_or_today_int(None):
        end_date = ensure_date_or_today_int(
            get_previous_trading_date(datetime.date.today()))
    trading_dates = pd.to_datetime(
        get_trading_dates(start_date, end_date, market=market))

    data = get_client().execute("get_securities_margin",
                                order_book_ids,
                                start_date,
                                end_date,
                                market=market)
    if not data:
        return

    if expect_df:
        df = pd.DataFrame(data)
        df.sort_values(["order_book_id", "date"], inplace=True)
        df.set_index(["order_book_id", "date"], inplace=True)
        df = df.reindex(columns=fields)
        return df

    pl = pd.Panel(items=fields,
                  major_axis=trading_dates,
                  minor_axis=order_book_ids)
    for r in data:
        for field in fields:
            value = r.get(field)
            pl.at[field, r["date"], r["order_book_id"]] = value

    if len(order_book_ids) == 1:
        pl = pl.minor_xs(order_book_ids[0])
    if len(fields) == 1:
        pl = pl[fields[0]]
    if len(order_book_ids) != 1 and len(fields) != 1:
        warnings.warn(
            "Panel is removed after pandas version 0.25.0."
            " the default value of 'expect_df' will change to True in the future."
        )
    return pl