示例#1
0
def get_price_change_rate(order_book_ids,
                          start_date=None,
                          end_date=None,
                          expect_df=False,
                          market="cn"):
    """获取价格变化信息

    :param order_book_ids: 股票列表
    :param start_date: 开始日期: 如'2013-01-04'
    :param end_date: 结束日期: 如'2014-01-04';在 start_date 和 end_date 都不指定的情况下,默认为最近3个月
    :param expect_df: 返回 DataFrame (Default value = False)
    :param market: 地区代码
    :returns: 如果输入一只股票, 则返回pandas.Series, 否则返回pandas.DataFrame

    """
    start_date, end_date = ensure_date_range(start_date, end_date)
    order_book_ids = ensure_order_book_ids(order_book_ids)
    data = get_client().execute("get_daily_returns",
                                order_book_ids,
                                start_date,
                                end_date,
                                market=market)
    if not data:
        return None
    df = pd.DataFrame(data)

    if len(order_book_ids) == 1 and not expect_df:
        df = df.set_index("date")
        series = df["daily_return"]
        series.name = order_book_ids[0]
        return series
    df = df.pivot(index="date", columns="order_book_id", values="daily_return")
    return df.sort_index()
示例#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
示例#3
0
def get_descriptor_exposure(order_book_ids,
                            start_date,
                            end_date,
                            descriptors=None,
                            market="cn"):
    """获取个股细分因子暴露度

    :param order_book_ids: 证券代码(例如:‘600705.XSHG’)
    :param start_date: 开始日期(例如:‘2017-03-03’)
    :param end_date: 结束日期(例如:‘2017-03-20’)
    :param descriptors: 细分风格因子。默认调用全部因子的暴露度('all')。
        具体细分因子名称见说明文档 (Default value = None)
    :param market:  (Default value = "cn")
    :returns: MultiIndex DataFrame. index 第一个 level 为 order_book_id,第 二个 level 为 date,column 为细分风格因子字段名称。
    """
    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date)
    if descriptors is not None:
        if descriptors == "all":
            descriptors = None
        else:
            descriptors = ensure_list_of_string(descriptors)
            check_items_in_container(descriptors, _DESCRIPTORS, "descriptors")

    df = get_client().execute("get_descriptor_exposure",
                              order_book_ids,
                              start_date,
                              end_date,
                              descriptors,
                              market=market)
    if not df:
        return
    return pd.DataFrame(df).set_index(["order_book_id",
                                       "date"]).sort_index(level=1)
示例#4
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
示例#5
0
def get_block_trade(order_book_ids,
                    start_date=None,
                    end_date=None,
                    market='cn'):
    """获取大宗交易信息
    :param order_book_ids: 股票代码
    :param start_date: 起始日期,默认为前三个月
    :param end_date: 截止日期,默认为今天
    :param market: (default value = 'cn')
    :return: pd.DataFrame or None
    """

    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date)

    data = get_client().execute('get_block_trade',
                                order_book_ids,
                                start_date,
                                end_date,
                                market=market)
    if not data:
        return
    df = pd.DataFrame(data)[[
        'order_book_id', 'trade_date', 'price', 'volume', 'total_turnover',
        'buyer', 'seller'
    ]]
    df.set_index(["order_book_id", "trade_date"], inplace=True)
    df.sort_index(inplace=True)
    return df
示例#6
0
def get_factor_return(
    start_date,
    end_date,
    factors=None,
    universe="whole_market",
    method="implicit",
    industry_mapping=True,
    market="cn",
):
    """获取因子收益率数据

    :param start_date: 开始日期(例如:‘2017-03-03’)
    :param end_date: 结束日期(例如:‘2017-03-20’)
    :param factors: 因子。默认获取全部因子的因子收益率
        当 method 参数取值为'implicit' ,可返回全部因子(风格、行业、市场联动)的隐式因子收益率;
        当 method 参数取值为'explicit' , 只返回风格因子的显式因子收益率。具体因子名称见说明文档 (Default value = None)
    :param universe: 股票池。默认调用全市场收益率。可选沪深300(‘000300.XSHG’)、中证500('000905.XSHG')
        、以及中证800('000906.XSHG') (Default value = "whole_market")
    :param method: 计算方法。默认为'implicit'(隐式因子收益率),可选'explicit'(显式风格因子收益率) (Default value = "implicit")
    :param market: 地区代码, 现在仅支持 'cn' (Default value = "cn")
    :param industry_mapping(bool): 是否按 2014 年后的申万行业分类标 准计算行业收益率.默认为 True.
        若取值为 False,则 2014 年前的行业 收益率按旧行业分类标准计算
    :returns: pd.DataFrame. index 为日期,column 为因子字段名称。

    Usage example::
        # 获取介于2017-03-03 到 2017-03-20到隐式因子收益率数据
        get_factor_return('2017-03-03', '2017-03-20')

    """
    start_date, end_date = ensure_date_range(start_date, end_date)

    if factors:
        factors = ensure_list_of_string(factors)

    method = ensure_string(method)
    if method not in _METHOD_MAPPING:
        raise ValueError(
            "invalid method: {!r}, valid: explicit, implicit".format(method))
    method = _METHOD_MAPPING[method]

    if universe not in _UNIVERSE_MAPPING:
        raise ValueError("invalid universe: {!r}, valid: {}".format(
            universe, list(_UNIVERSE_MAPPING.keys())))
    universe = _UNIVERSE_MAPPING[universe]

    df = get_client().execute("get_factor_return",
                              start_date,
                              end_date,
                              factors,
                              universe,
                              method,
                              market=market,
                              industry_mapping=industry_mapping)
    if not df:
        return None
    df = pd.DataFrame(df)
    # convert to required format.
    df = df.pivot(index="date", columns="factor")[universe]
    df.sort_index(inplace=True)
    return df
示例#7
0
def get_capital_flow(order_book_ids,
                     start_date=None,
                     end_date=None,
                     frequency="1d",
                     market="cn"):
    """获取资金流入流出数据
    :param order_book_ids: 股票代码or股票代码列表, 如'000001.XSHE'
    :param start_date: 开始日期
    :param end_date: 结束日期
    :param frequency: 默认为日线。日线使用 '1d', 分钟线 '1m'  快照 'tick' (Default value = "1d"),
    :param market:  (Default value = "cn")
    :returns: pandas.DataFrame or None
    """
    ensure_string_in(frequency, ("1d", "1m", "tick"), "frequency")
    if frequency == "tick":
        return get_capital_flow_tickbar(order_book_ids, start_date, end_date,
                                        TICKBAR_FIELDS, market)

    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date)
    if frequency == "1d":
        return get_capital_flow_daybar(order_book_ids, start_date, end_date,
                                       DAYBAR_FIELDS, 1, market)

    return get_capital_flow_minbar(order_book_ids, start_date, end_date,
                                   MINBAR_FIELDS, 1, market)
示例#8
0
def get_style_factor_exposure(order_book_ids,
                              start_date,
                              end_date,
                              factors=None,
                              market="cn"):
    """获取个股风格因子暴露度

    :param order_book_ids: 证券代码(例如:‘600705.XSHG’)
    :param start_date: 开始日期(例如:‘2017-03-03’)
    :param end_date: 结束日期(例如:‘2017-03-20’)
    :param factors: 风格因子。默认调用全部因子的暴露度('all')。
        具体因子名称见说明文档 (Default value = None)
    :param market:  (Default value = "cn")

    """
    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date)
    if factors is not None:
        factors = ensure_list_of_string(factors)
        check_items_in_container(factors, _STYLE_FACTORS, "factors")

    df = get_client().execute("get_style_factor_exposure",
                              order_book_ids,
                              start_date,
                              end_date,
                              factors,
                              market=market)
    if not df:
        return
    return pd.DataFrame(df).set_index(["order_book_id",
                                       "date"]).sort_index(level=1)
示例#9
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
示例#10
0
def index_indicator(order_book_ids, start_date=None, end_date=None, fields=None, market="cn"):
    """获取指数指标

    :param order_book_ids: 如'000016.XSHG'
    :param start_date: 如'2016-01-01' (Default value = None)
    :param end_date: 如'2017-01-01' (Default value = None)
    :param fields: 如'pb', 默认返回全部 fields (Default value = None)
    :param market:  (Default value = "cn")
    :returns: pd.DataFrame 或 None

    """
    all_fields = ("pe_ttm", "pe_lyr", "pb_ttm", "pb_lyr", "pb_lf")
    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date)
    if fields is not None:
        fields = ensure_list_of_string(fields)
        for f in fields:
            if f not in all_fields:
                raise ValueError("invalid field: {}".format(f))
    else:
        fields = all_fields

    df = get_client().execute(
        "index_indicator", order_book_ids, start_date, end_date, fields, market=market
    )
    if not df:
        return
    df = pd.DataFrame(df)
    df.set_index(["order_book_id", "trade_date"], inplace=True)
    return df
示例#11
0
def get_reserve_ratio(reserve_type="all",
                      start_date=None,
                      end_date=None,
                      market="cn"):
    """获取存款准备金率

    :param reserve_type: 存款准备金详细类别,默认为'all',目前仅支持'all'、'major'、'other'类别的查询
    :param start_date: 开始查找时间,如'20180501',默认为上一年的当天
    :param end_date: 截止查找时间,如'20180501',默认为当天
    :param market:  (Default value = "cn")
    :return: pd.DataFrame

    """
    check_items_in_container(reserve_type, ["all", "major", "other"],
                             "reserve_type")

    start_date, end_date = ensure_date_range(start_date,
                                             end_date,
                                             delta=relativedelta(years=1))

    ret = get_client().execute("econ.get_reserve_ratio", reserve_type,
                               start_date, end_date, market)
    if not ret:
        return
    columns = [
        "info_date", "effective_date", "reserve_type", "ratio_floor",
        "ratio_ceiling"
    ]
    df = pd.DataFrame(
        ret, columns=columns).set_index("info_date").sort_index(ascending=True)
    return df
示例#12
0
def get_money_supply(start_date=None, end_date=None, market="cn"):
    """获取货币供应量信息

    :param start_date: 开始日期,默认为一年前
    :param end_date: 结束日期,默认为今天
    :param market:  (Default value = "cn")

    """
    check_items_in_container("info_date", ["info_date", "effective_date"],
                             "date_type")
    start_date, end_date = ensure_date_range(start_date,
                                             end_date,
                                             delta=relativedelta(years=1))

    data = get_client().execute("econ.get_money_supply",
                                start_date,
                                end_date,
                                market=market)
    if not data:
        return
    columns = [
        "info_date",
        "effective_date",
        "m2",
        "m1",
        "m0",
        "m2_growth_yoy",
        "m1_growth_yoy",
        "m0_growth_yoy",
    ]
    df = pd.DataFrame(
        data,
        columns=columns).set_index("info_date").sort_index(ascending=True)
    return df
示例#13
0
def get_warehouse_stocks(underlying_symbols,
                         start_date=None,
                         end_date=None,
                         market="cn"):
    """获取时间区间内期货的注册仓单

    :param underlying_symbols: 期货品种, 支持列表查询
    :param start_date: 如'2015-01-01', 如果不填写则为去年的当日日期
    :param end_date: 如'2015-01-01', 如果不填写则为当日日期
    :param market: 市场, 默认为"cn"
    :return: pd.DataFrame

    """
    underlying_symbols = ensure_list_of_string(underlying_symbols,
                                               name="underlying_symbols")
    start_date, end_date = ensure_date_range(start_date,
                                             end_date,
                                             delta=relativedelta(years=1))

    ret = get_client().execute("futures.get_warehouse_stocks",
                               underlying_symbols,
                               start_date,
                               end_date,
                               market=market)
    if not ret:
        return

    columns = ["date", "underlying_symbol", "on_warrant", "exchange"]
    df = pd.DataFrame(ret, columns=columns)
    df.set_index(['date', 'underlying_symbol'], inplace=True)
    return df.sort_index()
示例#14
0
def get_ksh_tickbar(order_book_id, start_date, end_date, fields, market):
    order_book_id = ensure_order_book_id(order_book_id)
    start_date, end_date = ensure_date_range(start_date, end_date, datetime.timedelta(days=3))
    data = get_client().execute(
        "get_ksh_tickbar", order_book_id, start_date, end_date, fields, market
    )
    today = today_int()
    if data:
        data = [(obid, {k: np.frombuffer(*v) for k, v in d.items()}) for obid, d in data]
        df_list = []
        for obid, d in data:
            df = pd.DataFrame(d)
            df_list.append(df)

        df = pd.concat(df_list)  # type: pd.DataFrame
        df["datetime"] = int17_to_datetime_v(df["datetime"].values)
        history_latest_date = date_to_int8(df.iloc[-1]["datetime"])
        df.set_index("datetime", inplace=True)
    else:
        df = None
        history_latest_date = date_to_int8(get_previous_trading_date(today, market=market))

    if history_latest_date >= end_date or start_date > today or history_latest_date >= today:
        return df

    live_df = get_today_ksh_tick(order_book_id, today, fields, market=market)
    if live_df is None:
        return df
    if df is None:
        return live_df
    return pd.concat([df, live_df])
示例#15
0
def get_stock_connect(order_book_ids, start_date=None, end_date=None, fields=None, expect_df=False):
    """获取"陆股通"的持股、持股比例

    :param order_book_ids: 股票列表
    :param start_date: 开始日期: 如'2017-03-17' (Default value = None)
    :param end_date: 结束日期: 如'2018-03-16' (Default value = None)
    :param fields: 默认为所有字段,可输入shares_holding或者holding_ratio (Default value = None)
    :param expect_df: 返回 MultiIndex DataFrame (Default value = False)
    :returns: 返回pandas.DataFrame or pandas.Panel

    """
    if order_book_ids not in ("shanghai_connect", "shenzhen_connect", "all_connect"):
        order_book_ids = ensure_order_book_ids(order_book_ids, type="CS")
    start_date, end_date = ensure_date_range(start_date, end_date)
    if fields is not None:
        fields = ensure_list_of_string(fields)
        for f in fields:
            if f not in ("shares_holding", "holding_ratio"):
                raise ValueError("invalid field: {}".format(f))
    else:
        fields = ["shares_holding", "holding_ratio"]
    data = get_client().execute("get_stock_connect", order_book_ids, start_date, end_date, fields)
    if not data:
        return None
    df = pd.DataFrame(data, columns=["trading_date", "order_book_id"] + fields)

    if not expect_df and not is_panel_removed:
        df = df.set_index(["trading_date", "order_book_id"])
        df = df.to_panel()
        df.major_axis.name = None
        df.minor_axis.name = None
        if len(order_book_ids) == 1:
            df = df.minor_xs(order_book_ids[0])
        if len(fields) == 1:
            df = df[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 df
    else:
        df.sort_values(["order_book_id", "trading_date"], inplace=True)
        df.set_index(["order_book_id", "trading_date"], inplace=True)
        if expect_df:
            return df

        if len(order_book_ids) != 1 and len(fields) != 1:
            raise_for_no_panel()

        if len(order_book_ids) == 1:
            df.reset_index(level=0, drop=True, inplace=True)
            if len(fields) == 1:
                df = df[fields[0]]
            return df
        else:
            df = df.unstack(0)[fields[0]]
            df.index.name = None
            df.columns.name = None
            return df
示例#16
0
def get_capital_flow_tickbar(order_book_id, start_date, end_date, fields,
                             market):
    ensure_string(order_book_id, "order_book_id")
    start_date, end_date = ensure_date_range(start_date, end_date,
                                             datetime.timedelta(days=3))
    history_permission_denied = realtime_permission_denied = False
    try:
        data = get_client().execute("get_capital_flow_tickbar",
                                    order_book_id,
                                    start_date,
                                    end_date,
                                    fields,
                                    market=market)
    except PermissionDenied:
        data = []
        history_permission_denied = True
    today = today_int()

    if data:
        data = [(obid, {k: np.frombuffer(*v)
                        for k, v in d.items()}) for obid, d in data]
        df_list = []
        for obid, d in data:
            df = pd.DataFrame(d)
            df_list.append(df)

        df = pd.concat(df_list)  # type: pd.DataFrame
        df["datetime"] = int17_to_datetime_v(df["datetime"].values)
        history_latest_date = date_to_int8(df.iloc[-1]["datetime"])
        df.set_index("datetime", inplace=True)
    else:
        df = None
        history_latest_date = date_to_int8(
            get_previous_trading_date(today, market=market))

    if history_latest_date >= end_date or start_date > today or history_latest_date >= today:
        return df

    try:
        live_df = get_today_capital_flow_tick(order_book_id,
                                              today,
                                              market=market)
    except PermissionDenied:
        live_df = None
        realtime_permission_denied = True
    except MarketNotSupportError:
        live_df = None

    if history_permission_denied and realtime_permission_denied:
        raise PermissionDenied("get_capital_flow_tick")

    if live_df is None:
        return df
    if df is None:
        return live_df
    return pd.concat([df, live_df])
示例#17
0
def get_open_auction_info(order_book_ids, start_date=None, end_date=None, market="cn"):
    """获取盘前集合竞价数据
    :param order_book_ids: 股票代码
    :param start_date: 起始日期,默认为今天
    :param end_date: 截止日期,默认为今天
    :param market:  (Default value = "cn")
    :returns: pd.DataFrame or None
    """
    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date, datetime.timedelta(days=0))

    history_permission_denied = realtime_permission_denied = False
    try:
        # obid add prefix 'OA_'
        data = get_client().execute("get_open_auction_info_daybar", ["OA_" + obid for obid in order_book_ids],
                                    start_date, end_date, OA_FIELDS + ["datetime", "date"], market=market)
    except PermissionDenied:
        data = []
        history_permission_denied = True

    today = today_int()
    prev_trading_date = date_to_int8(get_previous_trading_date(today, market=market))
    if data:
        data = [(obid[3:], {k: np.frombuffer(*v) for k, v in d.items()}) for obid, d in data]
        df = convert_bar_to_multi_df(data, 'datetime', OA_FIELDS + ["date"], int17_to_datetime_v, default=0.0)
        if df is None:
            history_latest_date = prev_trading_date
        else:
            history_latest_date = df["date"].max()
            del df["date"]
    else:
        df = None
        history_latest_date = prev_trading_date
    if history_latest_date >= end_date or start_date > today or history_latest_date >= today or end_date < today:
        return df

    try:
        live_df = get_today_open_auction(order_book_ids, today, market=market)
    except PermissionDenied:
        live_df = None
        realtime_permission_denied = True

    if history_permission_denied and realtime_permission_denied:
        raise PermissionDenied("get_open_auction_info")

    if live_df is None:
        return df
    if df is None:
        return live_df
    df = pd.concat([df, live_df])
    df.sort_index(inplace=True)
    return df
示例#18
0
def get_private_placement(order_book_ids,
                          start_date=None,
                          end_date=None,
                          progress="complete",
                          market="cn"):
    """获取定增数据
    :param order_book_ids: 合约代码
    :param start_date: 开始日期,默认为None
    :param end_date: 结束日期,默认为None
    :param progress: 是否已完成定增,默认为complete。可选参数["complete", "incomplete", "all"]
    :param market: (Default value = "cn")
    :return:
    """
    order_book_ids = ensure_order_book_ids(order_book_ids, market=market)
    if start_date and end_date:
        start_date, end_date = ensure_date_range(start_date, end_date)
    elif start_date:
        start_date = ensure_date_int(start_date)
    elif end_date:
        end_date = ensure_date_int(end_date)
    ensure_string_in(progress, ["complete", "incomplete", "all"], "progress")
    data = get_client().execute("get_private_placement",
                                order_book_ids,
                                start_date,
                                end_date,
                                progress,
                                market=market)
    if not data:
        return
    progress_map = {
        10: "董事会预案",
        20: "股东大会通过",
        21: "国资委通过",
        22: "发审委通过",
        23: "证监会通过",
        29: "实施中",
        30: "实施完成",
        40: "国资委否决",
        41: "股东大会否决",
        42: "证监会否决",
        43: "发审委否决",
        50: "延期实施",
        60: "停止实施",
        70: "暂缓发行"
    }
    issue_type_map = {21: "非公开发行", 23: "非公开发行配套融资"}
    df = pd.DataFrame(data)
    df["progress"] = df["progress"].map(progress_map)
    df["issue_type"] = df["issue_type"].map(issue_type_map)
    df.set_index(["order_book_id", "initial_info_date"], inplace=True)
    return df
示例#19
0
def get_yield_curve(start_date=None, end_date=None, tenor=None, market="cn"):
    """获取国债收益率曲线

    :param market: 地区代码, 如'cn', 'us' (Default value = "cn")
    :param start_date: 开始日期 (Default value = "2013-01-04")
    :param end_date: 结束日期 (Default value = "2014-01-04")
    :param tenor: 类别, 如 OS, 1M, 3M, 1Y (Default value = None)

    """
    start_date, end_date = ensure_date_range(start_date, end_date)
    all_tenor = (
        "0S",
        "1M",
        "2M",
        "3M",
        "6M",
        "9M",
        "1Y",
        "2Y",
        "3Y",
        "4Y",
        "5Y",
        "6Y",
        "7Y",
        "8Y",
        "9Y",
        "10Y",
        "15Y",
        "20Y",
        "30Y",
        "40Y",
        "50Y",
    )
    if tenor:
        tenor = ensure_list_of_string(tenor, "tenor")
        check_items_in_container(tenor, all_tenor, "tenor")
        tenor = ensure_order(tenor, all_tenor)
    df = get_client().execute("get_yield_curve",
                              start_date,
                              end_date,
                              tenor,
                              market=market)
    if not df:
        return
    columns = ["trading_date"]
    columns.extend(tenor or all_tenor)
    df = pd.DataFrame(df, columns=columns)
    df.set_index("trading_date", inplace=True)
    return df.sort_index()
示例#20
0
def index_components(order_book_id,
                     date=None,
                     start_date=None,
                     end_date=None,
                     market="cn"):
    """获取指数成分
    :param order_book_id: 指数 id
    :param date: 指定日期;如不指定,返回最近一个交易日的数据
    :param start_date: 指定开始日期,不能和date同时指定
    :param end_date: 指定结束日期, 需和start_date同时指定并且应当不小于开始日期
    :param market:  (Default value = "cn")
    :returns list or dict
    """
    order_book_id = ensure_order_book_id(order_book_id)

    if date and (start_date or end_date):
        raise ValueError(
            "date cannot be input together with start_date or end_date")
    elif (start_date and not end_date) or (end_date and not start_date):
        raise ValueError("start_date and end_date need to be applied together")

    if start_date:
        start_date, end_date = ensure_date_range(start_date, end_date)
        trading_dates = get_trading_dates_in_type(start_date,
                                                  end_date,
                                                  expect_type="int")
        if not trading_dates:
            return
        data = get_client().execute("index_components_v2",
                                    order_book_id,
                                    trading_dates[0],
                                    trading_dates[-1],
                                    market=market)
        if not data:
            return
        data = {d["trade_date"]: d["component_ids"] for d in data}
        dates = sorted(data.keys())
        for trading_date in trading_dates:
            if trading_date not in data:
                position = bisect.bisect_left(dates, trading_date) - 1
                data[trading_date] = data[dates[position]]
        return {int8_to_datetime(i): data[i] for i in trading_dates}

    if date:
        date = ensure_date_int(date)
    return get_client().execute("index_components",
                                order_book_id,
                                date,
                                market=market)
示例#21
0
def get_factors(factors, start_date, end_date, market="cn"):
    start_date, end_date = ensure_date_range(start_date, end_date)
    factors = ensure_list_of_string(factors, "factors")
    data = get_client().execute("econ.get_factors",
                                factors,
                                start_date,
                                end_date,
                                market=market)
    if not data:
        return
    df = pd.DataFrame(data)
    df = df.reindex(
        columns=["factor", "info_date", "start_date", "end_date", "value"])
    df.set_index(["factor", "info_date"], inplace=True)
    return df
示例#22
0
def history(
    order_book_ids,
    start_date="2015-05-21",
    end_date="2016-05-21",
    frequency="1d",
    fields=None,
    market="cn",
):
    """获取雪球历史舆情数据

    :param order_book_ids: 股票代码或代码列表
    :param start_date: 如 '2015-05-21', 必须在2015年4月23日之后 (Default value = "2015-05-21")
    :param end_date: 如 '2016-05-21' (Default value = "2016-05-21")
    :param frequency: 如 '1d' (Default value = "1d")
    :param fields: 如 'new_comments', 'total_comments', 'new_followers',
                 'total_followers', 'sell_actions', 'buy_actions' (Default value = None)
    :param market: 地区代码, 如 'cn' (Default value = "cn")
    :returns: 返回pd.Panel或pd.DataFrame或pd.Series

    """
    order_book_ids = ensure_order_book_ids(order_book_ids, market=market)
    if fields:
        fields = ensure_list_of_string(fields, "fields")
        check_items_in_container(fields, FIELDS, "fields")
    else:
        fields = FIELDS
    frequency = ensure_string(frequency, "frequency")
    check_items_in_container([frequency], {"1d"}, "frequency")
    start_date, end_date = ensure_date_range(start_date, end_date)

    if start_date < 20150423:
        raise ValueError("date out of range, start_date "
                         "cannot be earlier than 2015-04-23")
    data = get_client().execute("xueqiu.history", order_book_ids, start_date,
                                end_date, fields, market)
    if not data:
        return
    df = pd.DataFrame(data)
    df = df.set_index(["date", "order_book_id"])
    df.sort_index(inplace=True)
    pl = df.to_panel()
    if len(pl.minor_axis) == 1:
        pl = pl.minor_xs(pl.minor_axis[0])
    if len(fields) == 1:
        pl = pl[fields[0]]
    return pl
示例#23
0
def get_irr_sensitivity(order_book_ids, start_date=None, end_date=None, market="cn"):
    """获取基金利率风险敏感性分析数据

    :param order_book_ids: 基金代码(str), 仅支持查询一个基金合约
    :param start_date: 开始日期, 如'2013-01-04'
    :param end_date: 结束日期, 如'2014-01-04';在 start_date 和 end_date 都不指定的情况下,默认为最近6个月
    :param market:  (Default value = "cn")
    :returns: DataFrame

    """
    order_book_ids = ensure_string(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date,delta=relativedelta(months=6))
    result = get_client().execute("fund.get_irr_sensitivity", order_book_ids, start_date, end_date, market=market)
    if not result:
        return

    df = pd.DataFrame(result).set_index(keys=['date'])
    df.sort_index(inplace=True)
    return df
示例#24
0
def _ensure_date(start_date, end_date, stocks, funds, indexes, futures, spots, options, convertibles, repos):
    default_start_date, default_end_date = ensure_date_range(start_date, end_date)

    only_futures = futures and (not stocks) and (not funds) and (not indexes) and (not spots) and (
        not options) and (not convertibles) and (not repos)
    if only_futures and len(futures) == 1:
        # 如果只有一只期货, 则给 start_date 和 end_date 合适的默认值
        # 连续合约的listed_date和de_listed_date都为0, 因此需要特殊处理
        if futures[0].listed_date != "0000-00-00":
            default_start_date = to_date_int(futures[0].listed_date)
        if futures[0].de_listed_date != "0000-00-00":
            default_end_date = to_date_int(futures[0].de_listed_date)

    start_date = to_date_int(start_date) if start_date else default_start_date
    end_date = to_date_int(end_date) if end_date else default_end_date
    if start_date < 20000104:
        warnings.warn("start_date is earlier than 2000-01-04, adjusted to 2000-01-04")
        start_date = 20000104
    return start_date, end_date
示例#25
0
def get_cross_sectional_bias(start_date, end_date, type='factor'):
    """ 获取横截面偏差系数

    :param order_book_ids	str or [list of str]	证券代码(例如:‘600705.XSHG’)
    :param start_date	    str                 	开始日期(例如:‘2017-03-03’)
    :param end_date	        str	                    结束日期(例如:‘2017-03-20’)
    :param type	            str	                    默认为 'factor',可选 'specific'

    :return: pandas.DataFrame,其中 index 为date, column 包含 'daily'、'monthly'  和 'quarterly' 三个字段。
    """
    start_date, end_date = ensure_date_range(start_date, end_date)
    ensure_string_in(type, ['factor', 'specific'], 'horizon')

    df = get_client().execute('get_cross_sectional_bias', start_date, end_date,
                              type)
    if not df:
        return
    df = pd.DataFrame(df)
    df = df.pivot(index='date', columns='horizon', values="bias").sort_index()
    return df
示例#26
0
def get_specific_return(order_book_ids, start_date, end_date):
    """ 获取个股特异收益率

    :param order_book_ids	str or [list of str]	证券代码(例如:‘600705.XSHG’)
    :param start_date	    str                 	开始日期(例如:‘2017-03-03’)
    :param end_date	        str	                    结束日期(例如:‘2017-03-20’)

    :return: pandas.DataFrame,其中 index 为date, column 为 order_book_ids。
    """
    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date)

    df = get_client().execute('get_specific_return', order_book_ids,
                              start_date, end_date)
    if not df:
        return
    df = pd.DataFrame(df)
    df = df.pivot(index='date',
                  columns='order_book_id',
                  values="specific_return").sort_index()
    return df
示例#27
0
def get_specific_risk(order_book_ids, start_date, end_date, horizon='daily'):
    """ 获取个股特异方差

    :param order_book_ids	str or [list of str]	证券代码(例如:‘600705.XSHG’)
    :param start_date	    str                 	开始日期(例如:‘2017-03-03’)
    :param end_date	        str	                    结束日期(例如:‘2017-03-20’)
    :param horizon	        str	    预测期限。默认为日度('daily'),可选月度(‘monthly’)或季度('quarterly')

    :return: pandas.DataFrame,其中 index 为date, column 为 order_book_ids。
    """
    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date)
    ensure_string_in(horizon, HORIZON_CONTAINER, 'horizon')

    df = get_client().execute('get_specific_risk', order_book_ids, start_date,
                              end_date, horizon)
    if not df:
        return
    df = pd.DataFrame(df)
    df = df.pivot(index="date",
                  columns="order_book_id",
                  values="specific_risk").sort_index()
    return df
示例#28
0
def get_main_shareholder(order_book_id,
                         start_date=None,
                         end_date=None,
                         is_total=False,
                         market="cn"):
    """获取十大股东信息

    :param order_book_id: 股票代码
    :param start_date: 开始日期,默认为一年前
    :param end_date: 结束日期,默认为今天
    :param is_total: 是否十大股东, True 和 False,默认为False
    :param market:  (Default value = "cn")

    """
    check_items_in_container(is_total, [True, False], "is_total")
    start_date, end_date = ensure_date_range(start_date,
                                             end_date,
                                             delta=relativedelta(years=1))

    ret = get_client().execute("get_main_shareholder",
                               order_book_id,
                               start_date,
                               end_date,
                               is_total,
                               market=market)
    if not ret:
        return
    columns = [
        'info_date', 'end_date', 'rank', 'shareholder_name',
        'shareholder_attr', 'shareholder_kind', 'shareholder_type',
        'hold_percent_total', 'hold_percent_float', 'share_pledge',
        'share_freeze'
    ]
    df = pd.DataFrame(ret, columns=columns).sort_values(
        by=['info_date', 'rank']).set_index('info_date')
    return df
示例#29
0
def get_stock_beta(order_book_ids,
                   start_date,
                   end_date,
                   benchmark="000300.XSHG",
                   market="cn"):
    """获取个股相对于基准的贝塔

    :param order_book_ids: 证券代码(例如:‘600705.XSHG’)
    :param start_date: 开始日期(例如:‘2017-03-03’)
    :param end_date: 结束日期(例如:‘2017-03-20’)
    :param benchmark: 基准指数。默认为沪深300(‘000300.XSHG’)
        可选上证50('000016.XSHG')、中证500('000905.XSHG')、
        中证800('000906.XSHG')以及中证全指('000985.XSHG') (Default value = "000300.XSHG")
    :param market:  (Default value = "cn")
    :returns: pandas.DataFrame,index 为日期,column 为个股的 order_book_id
    """
    order_book_ids = ensure_order_book_ids(order_book_ids)
    start_date, end_date = ensure_date_range(start_date, end_date)

    all_benchmark = ("000300.XSHG", "000016.XSHG", "000905.XSHG",
                     "000906.XSHG", "000985.XSHG")
    benchmark = ensure_string(benchmark, "benchmark")
    check_items_in_container(benchmark, all_benchmark, "benchmark")
    benchmark = benchmark.replace(".", "_")
    df = get_client().execute("get_stock_beta",
                              order_book_ids,
                              start_date,
                              end_date,
                              benchmark,
                              market=market)
    if not df:
        return
    df = pd.DataFrame(df)
    df = df.pivot(index="date", columns="order_book_id",
                  values=benchmark).sort_index()
    return df
示例#30
0
def get_index_factor_exposure(order_book_ids,
                              start_date=None,
                              end_date=None,
                              factors=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 factors: 如'yield', 'beta', 'volatility' (Default value = None)
    :param market: 地区代码, 如'cn' (Default value = "cn")
    """
    try:
        order_book_ids = ensure_order_book_ids(order_book_ids, type="INDX")
    except ValueError:
        return

    start_date, end_date = ensure_date_range(start_date, end_date)

    if factors is not None:
        factors = ensure_list_of_string(factors)
        check_items_in_container(factors, exposure_factors, "factors")

    results = get_client().execute("get_index_factor_exposure",
                                   order_book_ids,
                                   start_date,
                                   end_date,
                                   factors,
                                   market=market)

    if not results:
        return None
    df = pd.DataFrame.from_records(results, index=['date', 'order_book_id'])
    df.sort_index(inplace=True)
    return df