对于常见但是获取比较不太方便的数据我们将会写成一系列共享函数方便大家直接复制使用。
本系列将持续更新,标题为 【共享函数】
包含的函数:
换手率
量比
股票股息率
所有商品指数,主力合约,品种代号等
期货合约的基本信息(合约乘数、商品报价的计数单位、最小变动单位)
非实时的换手率数据可以直接通过 val
uation 表拿到,传送门:
https://www.joinquant.com/help/api/help?name=Stock#市值数据
def get_turnover_ratio(stocks,now_time):'''传入股票池,时间,返回实时换手率'''if isinstance(stocks, str):stocks = [stocks]if isinstance(now_time, str):now_time =datetime.datetime.strptime(now_time,'%Y-%m-%d %H:%M:%S')data = get_price(stocks,fields='volume',end_date=now_time,start_date=now_time.date(),frequency ='1m' ).volume.sum()valuation_data = get_fundamentals(query( #财务数据可以一天获取一次,自行更改valuation.code,valuation.circulating_cap ).filter(valuation.code.in_(stocks)),date=now_time).set_index('code')return data/valuation_data.iloc[:,0]/100get_turnover_ratio(['000001.XSHE','000002.XSHE'],datetime.datetime.now())
/opt/conda/lib/python3.6/site-packages/jqresearch/api.py:86: FutureWarning: Panel is deprecated and will be removed in a future version. The recommended way to represent these types of 3-dimensional data are with a MultiIndex on a DataFrame, via the Panel.to_frame() method Alternatively, you can use the xarray package http://xarray.pydata.org/en/stable/. Pandas provides a `.to_xarray()` method to help automate this conversion. pre_factor_ref_date=_get_today())
000001.XSHE 0.844864 000002.XSHE 0.877389 dtype: float64
# 区间换手率from jqdata import *def shuttle_turnover_ratio(code_list,end_date,start_date=None,day=None):'''start_date和day 二选一 , 选取day参数时代表day个交易日的区间换手率'''if not day:day = len(get_trade_days(start_date,end_date))if isinstance(code_list,str):code_list=[code_list]q = query(valuation.turnover_ratio).filter(valuation.code.in_(code_list))data = get_fundamentals_continuously(q,end_date=end_date,count=day).turnover_ratioreturn data.sum()shuttle_turnover_ratio(['000001.XSHE','000002.XSHE'],'2018-11-13',day=10)
code 000001.XSHE 7.0689 000002.XSHE 5.1873 dtype: float64
import pandas as pddef get_v_ratio(security_list,time):'''计算某个时间点股票的量比, 输入:股票池/股票,时间(datetime) 返回:截至当天某一时间点的量比'''if isinstance(security_list,str):security_list = [security_list]d = pd.Series()time2= time-datetime.timedelta(days=1)start_time = datetime.datetime(time.year,time.month,time.day,9,30)for security in security_list:ma5 = get_price(security,end_date=time2,frequency='5d',skip_paused=True,fields='volume',count=1,fq=None).volume/1200n_ma = get_price(security,end_date=time,start_date =start_time ,skip_paused=True,fields='volume', frequency='1m').volume.mean()d[security]=float(n_ma/ma5)return dsecurity_list = ['600016.XSHG','601166.XSHG','000001.XSHE']time = datetime.datetime(2018,9,27,15,30)get_v_ratio(security_list,time)
600016.XSHG 0.810266 601166.XSHG 0.869788 000001.XSHE 0.740555 dtype: float64
股息率(DividendRatio)=公司派现合计/股票市值。其中,公司派现合计是指从年初到该报告期的派现合计累计(整个公司的派现合计)
指数股息率传送门: https://www.joinquant.com/post/16656
from jqdata import *def DividendRatio(security_list,end_date,count=1):'''查询股息率(日更新) 输入:股票池,截止日期,获取数量 输出:panel结构,单位:1'''trade_days = get_trade_days(end_date=end_date,count = count)security_list.sort()secu_list = [x[:6] for x in security_list]code_df = jy.run_query(query( jy.SecuMain.InnerCode,jy.SecuMain.SecuCode,# jy.SecuMain.ChiName,jy.SecuMain.CompanyCode).filter(jy.SecuMain.SecuCode.in_(secu_list),jy.SecuMain.SecuCategory==1).order_by(jy.SecuMain.SecuCode))code_df['code'] = security_listdf = jy.run_query(query(# jy.LC_DIndicesForValuation #得到整表jy.LC_DIndicesForValuation.InnerCode,jy.LC_DIndicesForValuation.TradingDay, jy.LC_DIndicesForValuation.DividendRatio,).filter(jy.LC_DIndicesForValuation.InnerCode.in_(code_df.InnerCode),jy.LC_DIndicesForValuation.TradingDay.in_(trade_days)))f_df = df.merge(code_df,on='InnerCode').set_index(['TradingDay','code']).drop(['InnerCode','SecuCode'],axis=1)# panel = f_df.to_panel()return f_df['DividendRatio'].unstack()securitys =['000001.XSHE','000002.XSHE']date='2019-02-22'DividendRatio(securitys,date,count=5)
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }
code | 000001.XSHE | 000002.XSHE |
---|---|---|
TradingDay | ||
2019-02-18 | 0.011972 | 0.033088 |
2019-02-19 | 0.012067 | 0.033296 |
2019-02-20 | 0.011919 | 0.032573 |
2019-02-21 | 0.011972 | 0.033395 |
2019-02-22 | 0.011785 | 0.033370 |
df = get_all_securities(types=['futures']) #获取期货合约,指定date可以过滤退市合约# dominant_and_idnex = df[df.end_date==datetime.date(2030,1,1)] #商品指数和主力合约dominant_future = df[df.index.str.contains('9999')] #所有品种的主力合约index_future = df[df.index.str.contains('8888')] #所有品种的指数代码code_name = index_future.index.str.slice(start=0,stop=-9).tolist() #获取各个品种代号,使用get_dominant_future时会用到
"""获取期货合约的基本信息(合约乘数、商品报价的计数单位、最小变动单位)本函数由丹阳同学提供数据来源:聚源数据Fut_ContractMain表,https://www.joinquant.com/help/data/data?name=jy#nodeId=23参考帖子:http://bbs.tb18.net/thread-80004-1-1.html输入:合约代码(例如:SC1901.XINE)返回:dict格式合约乘数、商品报价的计数单位、最小变动单位 {'ContractUnit': 1000, 'MinPoint': 0.1, 'PriceScale': 0.1}"""# lru缓存可以不要,加上后查询相同的合约可以避免重复数据库请求from fastcache import clru_cache as lru_cache@lru_cache(maxsize=128)def future_basic_info(future):from jqdata import jyfrom numpy import nanimport reif "9999" in future or "8888" in future:match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", future)if not match:raise ValueError("未知期货标的:{}".format(future))else:future = get_dominant_future(match.groupdict()["underlying_symbol"])q = query(jy.Fut_ContractMain).filter(jy.Fut_ContractMain.ContractCode == future.split(".")[0])result = jy.run_query(query_object=q).to_dict("record")if result:result = result.pop()min_point = re.match("(?P<value>^[0-9]+([.]{1}[0-9]+){0,1})", result["LittlestChangeUnit"]).groupdict(nan)["value"]return {"ContractUnit": result["CMValue"], "PriceScale": float(min_point)/float(result["CMValue"]), "MinPoint": float(min_point)}else:return {"ContractUnit": nan,"PriceScale": nan,"MinPoint": nan}future_basic_info('CU9999.XSGE')
{'ContractUnit': 5, 'MinPoint': 10.0, 'PriceScale': 2.0}
本社区仅针对特定人员开放
查看需注册登录并通过风险意识测评
5秒后跳转登录页面...
移动端课程