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)
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
def get_instrument_industry(order_book_ids, source='sws', level=1, date=None, market="cn"): """获取股票对应的行业 :param order_book_ids: 股票列表,如['000001.XSHE', '000002.XSHE'] :param source: 分类来源。sws: 申万, citics: 中信, gildata: 聚源 :param date: 如 '2015-01-07' (Default value = None) :param level: (Default value = 1) :param market: (Default value = "cn") :returns: code, name 返回输入日期最近交易日的股票对应行业 """ order_book_ids = ensure_order_book_ids(order_book_ids) source = ensure_string_in(source, ["sws", "citics", "gildata"], "source") check_items_in_container(level, [0, 1, 2, 3], 'level') date = ensure_date_or_today_int(date) r = get_client().execute("get_instrument_industry", order_book_ids, source, level, date, market=market) if not r: return return pd.DataFrame(r).set_index("order_book_id")
def get_industry_mapping(source="citics", date=None, market="cn"): """获取行业分类列表 :param source: 分类来源,citics。citics: 中信, gildata: 聚源 :param market: (Default value = "cn") :return: DataFrame """ source = ensure_string_in(source, ["sws", "citics", "gildata", "citics_2019"], "source") if date is None: date = datetime.date.today() date = ensure_date_int(date) res = get_client().execute("get_industry_mapping_v2", source, date, market=market) if not res: return df = pd.DataFrame(res) if source == "sws": df.rename(columns=dict(zip(OTHER_COLUMNS, SHENWAN_COLUMNS)), inplace=True) columns = SHENWAN_COLUMNS else: columns = OTHER_COLUMNS df = df.dropna().drop_duplicates() df = df.sort_values(columns[::2]).reset_index(drop=True) return df[columns]
def get_factor_covariance(date, horizon='daily'): """ 获取因子协方差矩阵 :param date: str 日期(例如:‘2017-03-20’) :param horizon: str 预测期限。默认为日度('daily'),可选月度(‘monthly’)或季度('quarterly')。 :return: pandas.DataFrame,其中 index 和 column 均为因子名称。 """ date = get_previous_trading_date(get_next_trading_date(date)) date = ensure_date_int(date) ensure_string_in(horizon, HORIZON_CONTAINER, 'horizon') df = get_client().execute('get_factor_covariance', date, horizon) if not df: return df = pd.DataFrame(df) df.drop("date", axis=1, inplace=True) return df.reindex(columns=df.index)
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
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
def get_instrument_industry(order_book_ids, source='citics', level=1, date=None, market="cn"): """获取股票对应的行业 :param order_book_ids: 股票列表,如['000001.XSHE', '000002.XSHE'] :param source: 分类来源。citics 以及 citics_2019: 中信, gildata: 聚源 :param date: 如 '2015-01-07' (Default value = None) :param level: (Default value = 1) :param market: (Default value = "cn") :returns: code, name 返回输入日期最近交易日的股票对应行业 """ order_book_ids = ensure_order_book_ids(order_book_ids) source = ensure_string_in(source, ["sws", "citics", "gildata", "citics_2019"], "source") if source == "citics_2019": check_items_in_container(level, [0, 1, 2, 3, "citics_sector"], 'level') else: check_items_in_container(level, [0, 1, 2, 3], 'level') date = ensure_date_or_today_int(date) r = get_client().execute("get_instrument_industry", order_book_ids, source, level, date, market=market) if not r: return res = [i['order_book_id'] for i in r] if source == "citics_2019" and level == "citics_sector": # is_special industry是否传入的是风格版块,产业板块和上下游产业版块 from rqdatac.services import basic res_list = basic.instruments(res) date = to_date_str(date) for index, order_book in enumerate(res_list): if order_book.de_listed_date == "0000-00-00" or order_book.de_listed_date is None: order_book.de_listed_date = "2099-12-31" if not order_book.listed_date <= date <= order_book.de_listed_date: r.pop(index) return pd.DataFrame(r).set_index("order_book_id")
def get_industry(industry, source='sws', date=None, market="cn"): """获取行业股票列表 :param industry: 行业名称或代码 :param source: 分类来源。sws: 申万, citics: 中信, gildata: 聚源 :param date: 查询日期,默认为当前最新日期 :param market: (Default value = "cn") :return: 所属目标行业的order_book_id list or None """ industry = ensure_string(industry, "industry") source = ensure_string_in(source, ["sws", "citics", "gildata"], "source") date = ensure_date_or_today_int(date) res = get_client().execute("get_industry", industry, source, date, market=market) return sorted(res)
def get_industry_mapping(source="sws", market="cn"): """获取行业分类列表 :param source: 分类来源,默认为sws。sws: 申万, citics: 中信, gildata: 聚源 :param market: (Default value = "cn") :return: DataFrame """ source = ensure_string_in(source, ["sws", "citics", "gildata"], "source") columns = [ "index_code", "index_name", "second_index_code", "second_index_name", "third_index_code", "third_index_name" ] if source == "sws" else [ "first_industry_code", "first_industry_name", "second_industry_code", "second_industry_name", "third_industry_code", "third_industry_name" ] res = get_client().execute("get_industry_mapping", source, market=market) df = pd.DataFrame(res) df = df.dropna().drop_duplicates() df = df.sort_values(columns[::2]).reset_index(drop=True) return df[columns]
def get_industry(industry, source='citics', date=None, market="cn"): """获取行业股票列表 :param industry: 行业名称或代码 :param source: 分类来源。citics 以及 citics_2019: 中信, gildata: 聚源 :param date: 查询日期,默认为当前最新日期 :param market: (Default value = "cn") :return: 所属目标行业的order_book_id list or None """ industry = ensure_string(industry, "industry") source = ensure_string_in(source, ["sws", "citics", "gildata", "citics_2019"], "source") date = ensure_date_or_today_int(date) res = get_client().execute("get_industry", industry, source, date, market=market) if not res: return res if res[-1] == "have_sector_name": # have_sector_name 代表 industry传入的是风格版块,产业板块或者上下游产业版块 from rqdatac.services import basic res_list = basic.instruments(res[:-1]) res = [] date = to_date_str(date) for order_book in res_list: if order_book.de_listed_date == "0000-00-00" or order_book.de_listed_date is None: order_book.de_listed_date = "2099-12-31" if order_book.listed_date <= date <= order_book.de_listed_date: res.append(order_book.order_book_id) return sorted(res)
def get_trading_hours(order_book_id, date=None, expected_fmt="str", frequency="1m", market="cn"): """获取合约指定日期交易时间 :param order_book_id: 合约代码 :param date: 日期,默认为今天 :param expected_fmt: 返回格式,默认为str, 也支持datetime.time和datetime.datetime格式 :param frequency: 频率,默认为1m, 对应米筐分钟线时间段的起始, tick和1m相比区别在于每个交易时间段开盘往前移一分钟 :param market: (Default value = "cn") :return: trading_hours str or list of datetime.time/datetime.datetime list or None """ date = ensure_date_or_today_int(date) if not is_trading_date(date, market): warnings.warn(" %d is not a trading date" % date) return ensure_string(order_book_id, "order_book_id") ins = instruments(order_book_id) if ins is None: return ensure_string_in(expected_fmt, ("str", "time", "datetime"), "expected_fmt") ensure_string_in(frequency, ("1m", "tick"), "frequency") date_str = to_date_str(date) if ins.listed_date > date_str: return if ins.type in ( "Future", "Option" ) and ins.de_listed_date < date_str and ins.de_listed_date != "0000-00-00": return if ins.type not in ( "Future", "Option" ) and ins.de_listed_date <= date_str and ins.de_listed_date != "0000-00-00": return if ins.type == "Repo": trading_hours = "09:31-11:30,13:01-15:30" elif ins.type == "Spot": if has_night_trading(date, market): trading_hours = "20:01-02:30,09:01-15:30" else: trading_hours = "09:01-15:30" elif ins.type not in ("Future", "Option") or (ins.type == "Option" and ins.exchange in ("XSHG", "XSHE")): trading_hours = "09:31-11:30,13:01-15:00" else: trading_hours = get_client().execute("get_trading_hours", ins.underlying_symbol, date, market=market) if trading_hours is None: return # 前一天放假或者该品种上市首日没有夜盘 no_night_trading = (not has_night_trading(date, market) or get_underlying_listed_date( ins.underlying_symbol, ins.type) == date_str) if no_night_trading and not trading_hours.startswith("09"): trading_hours = trading_hours.split(",", 1)[-1] if frequency == "tick": trading_hours = ",".join([ s[:4] + str(int(s[4]) - 1) + s[5:] for s in trading_hours.split(",") ]) if expected_fmt != "str": trading_hours = [t.split("-", 1) for t in trading_hours.split(",")] for i, (start, end) in enumerate(trading_hours): trading_hours[i][0] = str_to_dt_time(start) trading_hours[i][1] = str_to_dt_time(end) if expected_fmt == "datetime": td = int8_to_date(date) prev_td = get_previous_trading_date(date) prev_td_next = prev_td + datetime.timedelta(days=1) for i, (start, end) in enumerate(trading_hours): if start.hour > 16: start_dt = prev_td end_dt = start_dt if end.hour > 16 else prev_td_next else: start_dt = end_dt = td trading_hours[i][0] = datetime.datetime.combine( start_dt, start) trading_hours[i][1] = datetime.datetime.combine(end_dt, end) return trading_hours
def get_contracts( underlying, option_type=None, maturity=None, strike=None, trading_date=None ): """返回符合条件的期权 :param underlying: 标的合约, 可以填写'M'代表期货品种的字母;也可填写'M1901'这种具体 order_book_id :param option_type: 期权类型, 'C'代表认购期权, 'P'代表认沽期权合约, 默认返回全部 :param maturity: 到期月份, 如'1811'代表期权18年11月到期, 默认返回全部到期月份 :param strike: 行权价, 向左靠档, 默认返回全部行权价 :param trading_date: 查询日期, 仅针对50ETF期权行权有效, 默认返回当前全部 :returns 返回order_book_id list;如果无符合条件期权则返回空list[] """ underlying = ensure_string(underlying, "underlying").upper() instruments_df = all_instruments(type='Option') underlying_symbols = instruments_df.underlying_symbol.unique() underlying_order_book_ids = instruments_df.underlying_order_book_id.unique() if underlying in underlying_symbols: instruments_df = instruments_df[instruments_df.underlying_symbol == underlying] elif underlying in underlying_order_book_ids: instruments_df = instruments_df[instruments_df.underlying_order_book_id == underlying] else: raise ValueError("Unknown underlying") if instruments_df.empty: return [] if instruments_df.iloc[0].underlying_symbol != '510050.XSHG' and trading_date: warnings.warn( "Underlying symbol is not 510050.XSHG, trading_date ignored" ) elif instruments_df.iloc[0].underlying_symbol == '510050.XSHG' and trading_date: instruments_df = all_instruments(type='Option', date=trading_date) instruments_df = instruments_df[instruments_df.underlying_symbol == '510050.XSHG'] if instruments_df.empty: return [] if option_type is not None: option_type = ensure_string(option_type, "option_type").upper() ensure_string_in(option_type, {'P', 'C'}, "option_type") instruments_df = instruments_df[instruments_df.option_type == option_type] if maturity is not None: maturity = int(maturity) month = maturity % 100 if month not in range(1, 13): raise ValueError("Unknown month") year = maturity // 100 + 2000 str_month = str(month) if len(str_month) == 1: str_month = '0' + str_month date_str = str(year) + '-' + str_month # instruments_df.set_index(instruments_df.maturity_date, inplace=True) # instruments_df = instruments_df.filter(like=date_str, axis=0) instruments_df = instruments_df[instruments_df.maturity_date.str.startswith(date_str)] if instruments_df.empty: return [] if strike: order_book_ids = instruments_df.order_book_id.tolist() if instruments_df.iloc[0].underlying_symbol == '510050.XSHG' and trading_date: strikes = get_price(order_book_ids, start_date=trading_date, end_date=trading_date, fields='strike_price') if strikes.empty: return [] instruments_df.set_index(instruments_df.order_book_id, inplace=True) strikes = strikes.T instruments_df['strike_price'] = strikes[strikes.columns[0]] instruments_df = instruments_df[instruments_df.strike_price.notnull()] if instruments_df.empty: return [] l = [] for date in instruments_df.maturity_date.unique(): df = instruments_df[instruments_df.maturity_date == date] df = df[df.strike_price <= strike] if df.empty: continue df = df[df.strike_price.rank(method='min', ascending=False) == 1] l += df.order_book_id.tolist() return l else: return instruments_df.order_book_id.tolist()