发现大家刚开始不太会实现某种方法,其实平时多使用平台完全可以自己解决,但为了尽量避免让大家走弯路.在这里对一些问题进行有限整理,针对大家经常性问到的方法实现。
其实很多问题可以通过社区搜索和共享函数库解决的,这里并不是单纯为大家提供代码,而是选取一些比较有借鉴性的方法供大家参考,重要的不是代码,而是实现代码过程中的思路以及路径,因为方法有千千万万种,需要举一而反三。
今后会持续选取一些比较有代表性的代码进行添加,您也可以将一些初学时碰到的常见问题在下方留言反馈或分享。
获得向前推第T个交易日日期
获取向后推X个交易日的交易日列表
市场每日统计(上涨,下跌,涨停,跌停户数等)
HHV,LLV:过去N日的最高/最低价的时间序列
MACD(多股票,多周期)
国内sma算法(与talib不一致)
剔除上市不满一年的次新股
分时走势图的黄线(均价线)
日内每x分钟运行
时间段内运行/时间点运行
根据大盘指数跌幅进行止损【回测专用】
缠论K线包含关系处理
设置pandas的最大显示行数,列数
将array数据格式转为dataframe
多个dataframe的合并 (数据拼接) 获取多份报表
panel数据可视化(转dataframe)
剔除过去N天停牌超过X日的股票
移动窗口(rolling)和 拓展窗口(expanding)
简单的ema计算
量比
DatetimeIndex 转 strindex (解决绘图非交易时间自动补全) 以及绘图正常显示问题
解决中文显示
查询股息率(近12个月)
期货合约每点价位
查询申万行情( 包含行业pe/pb)
中证指数pe/股息率
获取所有商品指数,主力合约,品种代号等
字典转dataframe/panel
数据库/pandas的模糊查询
研究中进行性能分析
区间换手率
VPT量能指标
ADF 平稳性检验(有点小问题,修改方法):
from statsmodels.tsa.stattools import adfuller import pandas as pd for key,value in enumerate(dftest[4]):
https://www.joinquant.com/algorithm/apishare/get?apiId=1113
和行情软件(同花顺、大智慧、通达信等)一致的KDJ和RSI以及MACD算法
抛物线转向(Stop And Reverse)(注意更改大小写,如Date>date)
s = psar(get_bars('600741.XSHG',count=10,fields=['date','close', 'high', 'low'])); pd.DataFrame(s)
有效前沿计算:https://www.joinquant.com/post/14766
Tradestat 策略常用的一个小工具,非常漂亮的持仓收益日志显示
利用get_trade_days和context对象中的current_dt等获取上上一个交易日等,在此给出示例 使用前: from jqdata import * 当前交易日: now_ = context.current_dt.strftime("%Y-%m-%d") 上上一个交易日: the_day = get_the_day(now,2)
有关时间处理的demo请看这里:
from jqdata import *def get_the_day(date,T):'''输入,当前日期 向前推T天个交易日 比如date为9月13,前几天无节假日,传入T=1,返回上一个交易日的日期'''return get_trade_days(end_date=date,count=T+1)[0]get_the_day('2018-09-13',2)
datetime.date(2018, 9, 11)
import jqdataimport datetimedate = datetime.date(2018,10,1)def get_future_trade_days(date,count):if count>5: all_data = jqdata.get_trade_days(start_date=date,end_date=date+datetime.timedelta(days=count*2))else:all_data = jqdata.get_trade_days(start_date=date,end_date=date+datetime.timedelta(days=count+10))return all_data[:count]date = datetime.date(2018,10,8)get_future_trade_days(date,2)
array([datetime.date(2018, 10, 8), datetime.date(2018, 10, 9)], dtype=object)
def Market_statistics(check_date,filter_st=True):'''check_date: 统计日期, filter_st: 是否过滤st'''info_data = get_all_securities(date=check_date)all_list = info_data.index.tolist()st_df = get_extras('is_st', all_list,end_date=check_date, df=True, count=1).Tst_list = st_df[st_df.iloc[:,0]].index.tolist()print ('st股票有%s只'%len(st_list))print ('未退市的有%s只'%len(all_list))all_data = get_price(all_list,end_date=check_date,count=2,fields=['paused','close','high_limit','low_limit'])paused_data = all_data.paused.iloc[-1]paused_list = paused_data[paused_data==1].index.tolist()print ('停牌%s只'%len(paused_list))new_data = all_data.drop(paused_list,axis=2)if filter_st ==True:filter_list = list(set(st_list)-set(paused_list))new_data = new_data.drop(filter_list,axis=2)pct_data = new_data.close.pct_change().iloc[1]print ('当日新上市股票:%s'%pct_data[np.isnan(pct_data)].index.tolist())print ('上涨%s只(不含当日上市)'%len(pct_data[pct_data>=0]))print ('下跌%s只'%len(pct_data[pct_data<0]))limit_up_data = new_data.iloc[:,-1,:][new_data.iloc[:,-1,:].close==new_data.iloc[:,-1,:].high_limit]print ('涨停%s只'%len(limit_up_data))limit_down_data = new_data.iloc[:,-1,:][new_data.iloc[:,-1,:].close==new_data.iloc[:,-1,:].low_limit]print ('跌停%s只'%len(limit_down_data))now_time = datetime.datetime.now()Market_statistics(now_time,True) #彩蛋:2008-04-24,2008-09-19大盘涨停# 2015-07-08年千股停牌 ,15年停牌股票较多# 2016年开年,熔断机制*,千股跌停
st股票有89只 未退市的有3551只 停牌84只 当日新上市股票:[] 上涨524只(不含当日上市) 下跌2863只 涨停16只 跌停20只
import pandas as pddef HHV(srcuritys,windows,end_date=None,count=20,fq='pre'):'''传入,股票列表,时间窗口,查询日期(包含当天,返回的数量,复权方式'''df = get_price(srcuritys,end_date=end_date,count=count+windows-1,fq=fq,fields='high')return pd.rolling_max(df.high,windows).dropna()###########################################################def LLV(srcuritys,windows,end_date=None,count=20,fq='pre'):'''传入,股票列表,时间窗口,查询日期(包含当天,返回的数量,复权方式'''df = get_price(srcuritys,end_date=end_date,count=count+windows-1,fq=fq,fields='low')return pd.rolling_min(df.low,windows).dropna()# HHV(['600741.XSHG','600507.XSHG'],10,'2018-09-04')LLV(['600741.XSHG','600507.XSHG'],10,'2018-09-04')
600741.XSHG | 600507.XSHG | |
---|---|---|
2018-08-08 | 20.20 | 11.48 |
2018-08-09 | 20.13 | 11.48 |
2018-08-10 | 20.13 | 11.48 |
2018-08-13 | 20.13 | 11.48 |
2018-08-14 | 20.13 | 11.48 |
2018-08-15 | 20.13 | 11.48 |
2018-08-16 | 19.96 | 11.45 |
2018-08-17 | 19.86 | 11.45 |
2018-08-20 | 19.20 | 11.02 |
2018-08-21 | 19.20 | 11.02 |
2018-08-22 | 19.20 | 11.02 |
2018-08-23 | 19.20 | 11.02 |
2018-08-24 | 19.20 | 11.02 |
2018-08-27 | 19.20 | 11.02 |
2018-08-28 | 19.20 | 11.02 |
2018-08-29 | 19.20 | 11.02 |
2018-08-30 | 19.20 | 11.02 |
2018-08-31 | 19.20 | 11.02 |
2018-09-03 | 19.50 | 10.92 |
2018-09-04 | 19.80 | 10.92 |
获取各周期MACD # stock: 股票代码 # period: history支持的周期
import numpy as npimport talib# MACDdef MACD(security_list,period='1d', fastperiod=12, slowperiod=26, signalperiod=9):# 修复传入为单只股票的情况if isinstance(security_list, str):security_list = [security_list]# 计算 MACDsecurity_data = history(slowperiod*3, period, 'close' , security_list, df=False, skip_paused=True)macd_DIF = {}; macd_DEA = {}; macd_HIST = {}for stock in security_list:nan_count = list(np.isnan(security_data[stock])).count(True)if nan_count == len(security_data[stock]):log.info("股票 %s 输入数据全是 NaN,该股票可能已退市或刚上市,返回 NaN 值数据。" %stock)macd_DIF[stock] = array([np.nan])macd_DEA[stock] = array([np.nan])macd_HIST[stock]= array([np.nan])else:macd_DIF[stock], macd_DEA[stock], macd = talib.MACDEXT(security_data[stock], fastperiod=fastperiod, fastmatype=1, slowperiod=slowperiod, slowmatype=1, signalperiod=signalperiod, signalmatype=1)macd_HIST[stock] = macd * 2return macd_DIF, macd_DEA, macd_HISTmacd_DIF, macd_DEA, macd_HIST = MACD(['600741.XSHG','600507.XSHG'],period='5m')
def SMA(security_list, timeperiod=5) :# 修复传入为单只股票的情况if isinstance(security_list, str):security_list = [security_list]# 计算 SMAsecurity_data = history(timeperiod*2, '1d', 'close' , security_list, df=False, skip_paused=True)sma = {}for stock in security_list:close = np.nan_to_num(security_data[stock])sma[stock] = reduce(lambda x, y: ((timeperiod - 1) * x + y) / timeperiod, close)return sma
剔除上市不满一年的次新股(count设置为365天,注意不是交易日,而是自然日)
import datetimedef get_filter_timedelta_stocks(stock_list, date=None,count=365):if isinstance(date,str):date = datetime.datetime.strptime(date, "%Y-%m-%d").date()if isinstance(date,datetime.datetime):date=date.date()the_day = date-datetime.timedelta(days=count)new_list=[s for s in stock_list if get_security_info(s).start_date <the_day]return new_listget_filter_timedelta_stocks(['600741.XSHG'], date='2018-01-01')a =datetime.datetime.now()get_filter_timedelta_stocks(['600741.XSHG'], date=a)
['600741.XSHG']
def get_yellow_line(code,date,w=1):'''输入:股票 , 查询日期 ,每点价值(股票为1,如IF为300)'''p_date = date-datetime.timedelta(days=1)df = get_price(code,end_date=str(date)[:10]+' 15:10:00',start_date=str(p_date)+' 15:10:00', frequency='1m',fields=['volume','money'])cum = df.iloc[:,-2:].cumsum()return cum['money']/cum['volume']/w
code='IF1812.CCFX'date = datetime.date(2018,12,5)*g = get_yellow_line(code,date,300)data = get_price(code,end_date='2018-12-06',count=240 ,frequency='1m',fields='close')data['*g']=*gindex = data.indexpydate_array = index.to_pydatetime()date_only_array = np.vectorize(lambda s: s.strftime('%Y-%m-%d %H:%M:%S'))(pydate_array ) #将datetimeindex转为strdata.index = date_only_arraydata.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x7fa6c81dd950>
每隔x分钟运行一次,用于日内交易,在初始化函数中执行run_time并定义需要定时的函数run_min,*研究可以查看策略截图
def initialize(context):run_time(30)#每30分钟运行一次def run_time(x):datas = get_price('000300.XSHG',count=240,frequency='1m').index.tolist()[:-1]#剔除15:00times = [str(t)[-8:] for t in datas]times.insert(0,'09:30:00')for t in times[::x]:run_daily(run_min, t)def run_min(context):'''需要运行的函数或代码放在这里'''print 'run'
#策略选择分钟频率,在handle_data(或其他定时运行函数)的开始加上下述判断:def handle_data(context, data):now_time = context.current_dt.strftime('%H:%M:%S')'''在10:00:00以后每分钟执行'''if now_time<='10:00:00': #return# '''在10:00以后,11:30之前每分钟执行'''# if now_time<='10:00:00' or now_time>='11:30:00': # return# '''在10:00时执行一次'''# if now_time !='10:00:00':# returnprint '执行'
# 根据大盘指数跌幅进行止损def index_stoploss_diefu(index, context, n=10, zs=0.03):''' 当大盘N日内跌幅超过zs,则清仓止损 '''if len(context.portfolio.positions)>0:hist = attribute_history(index, n, '1d', 'close',df=False)if ((1-float(hist['close'][-1]/hist['close'][0])) >= zs):log.info('大盘触及止损线,清仓!')for stock in context.portfolio.positions.keys():order_target_value(stock, 0)
输入:股票历史数据的dataframe,含有‘high’,‘low’的股票历史数据,聚宽的获取价格的接口得出的数据就OK 输出:增加了label_k,label_high,label_low列信息的股票历史数据dataframe 进行K线的包含关系处理,再原dataframe数据表中增加label列进行是否有效的标记,增加两列记录合并K线后的最值 其中,label_k的值为1时是上升K线,为-1时是下降K线,为0时,是包含关系的K线
def label_k_func(df):#进行K线的包含关系处理,再原dataframe数据表中增加label列进行是否有效的标记,增加两列记录合并K线后的最值h=df['high'].valuesl=df['low'].valuesdf['t']=pd.Series(range(len(df)),index=df.index)t=df['t'].valueslabel=[1]h_jizhi,l_jizhi=h[0],l[0]high_new=[h[0]]low_new=[l[0]]#标记K线的有效性,上升K线为1,下降为-1,无效为0for i in t[1:]:#缠论上升K线的定义if h[i]>h_jizhi and l[i]>l_jizhi:label.append(1)h_jizhi=max(h[i],h[i-1])l_jizhi=max(l[i],l[i-1])#缠论下降K线的定义elif h[i]<h_jizhi and l[i]<l_jizhi:label.append(-1)h_jizhi=min(h[i],h[i-1])l_jizhi=min(l[i],l[i-1])#包涵K线的处理else:label.append(0)#下面的内容主要是进行极值的更新for j in label[::-1]:if j != 0:a=jbreakif a==1:h_jizhi=max(h[i],h_jizhi)l_jizhi=max(l[i],l_jizhi)else:h_jizhi=min(h[i],h_jizhi)l_jizhi=min(l[i],l_jizhi)high_new.append(h_jizhi)low_new.append(l_jizhi)#把结果添加到dfdf['label_k']=pd.Series(label,index=df.index)df['high_k']=pd.Series(high_new,index=df.index)df['low_k']=pd.Series(low_new,index=df.index)return df
import pandas as pd# 设定最大显示行数、列数为10000pd.set_option('display.max_rows', 10000)pd.set_option('display.max_columns', 10000)pd.set_option('display.width', 10000)
import pandas as pdar = get_ticks('000001.XSHE',end_dt='2018-10-08 09:31:00',count=20)df = pd.DataFrame(ar)l = df['time'].values.tolist()s = ['%.2f'%(x) for x in l]t = [o[:4]+'-'+o[4:6]+'-'+o[6:8]+' '+o[8:10]+':'+o[10:12]+':'+o[12:] for o in s]df.time = pd.to_datetime(t)df =df.set_index('time')df
current | high | low | volume | money | |
---|---|---|---|---|---|
time | |||||
2018-10-08 09:25:03 | 10.70 | 10.7 | 10.70 | 36779 | 39353530 |
2018-10-08 09:30:03 | 10.69 | 10.7 | 10.69 | 61944 | 66226210 |
2018-10-08 09:30:06 | 10.69 | 10.7 | 10.69 | 73036 | 78079410 |
2018-10-08 09:30:09 | 10.68 | 10.7 | 10.68 | 75041 | 80222162 |
2018-10-08 09:30:12 | 10.68 | 10.7 | 10.68 | 81014 | 86585682 |
2018-10-08 09:30:15 | 10.68 | 10.7 | 10.68 | 82524 | 88198194 |
2018-10-08 09:30:18 | 10.67 | 10.7 | 10.67 | 85970 | 91865930 |
2018-10-08 09:30:21 | 10.67 | 10.7 | 10.67 | 86688 | 92631786 |
2018-10-08 09:30:24 | 10.67 | 10.7 | 10.67 | 87511 | 93509818 |
2018-10-08 09:30:27 | 10.68 | 10.7 | 10.67 | 89851 | 96006810 |
2018-10-08 09:30:30 | 10.66 | 10.7 | 10.66 | 92148 | 98457394 |
2018-10-08 09:30:33 | 10.67 | 10.7 | 10.66 | 92954 | 99317674 |
2018-10-08 09:30:36 | 10.67 | 10.7 | 10.66 | 97921 | 104614946 |
2018-10-08 09:30:39 | 10.66 | 10.7 | 10.66 | 100357 | 107211642 |
2018-10-08 09:30:42 | 10.65 | 10.7 | 10.65 | 105101 | 112264002 |
2018-10-08 09:30:45 | 10.65 | 10.7 | 10.65 | 109210 | 116640018 |
2018-10-08 09:30:48 | 10.65 | 10.7 | 10.65 | 112644 | 120296442 |
2018-10-08 09:30:51 | 10.66 | 10.7 | 10.65 | 118232 | 126247330 |
2018-10-08 09:30:54 | 10.65 | 10.7 | 10.65 | 120726 | 128905386 |
2018-10-08 09:30:57 | 10.65 | 10.7 | 10.65 | 121949 | 130208594 |
ar = get_bars('600741.XSHG',end_dt='2018-09-14 14:50:00',count=5,fields=['date','close','open'], unit='30m',include_now=True)pd.DataFrame(ar).set_index('date')
close | open | |
---|---|---|
date | ||
2018-09-14 11:30:00 | 20.35 | 20.36 |
2018-09-14 13:30:00 | 20.38 | 20.34 |
2018-09-14 14:00:00 | 20.41 | 20.38 |
2018-09-14 14:30:00 | 20.37 | 20.41 |
2018-09-14 14:50:00 | 20.35 | 20.40 |
#获取多年的季度度数据import pandas as pddef get_more_state_fund(q_object,year_list):df_list = []for year in year_list:rets = [get_fundamentals(q, statDate=str(year)+'q'+str(i)) for i in range(1, 5)]df = pd.concat(rets).set_index('statDate') #个人习惯df_list.append(df)df_ = pd.concat(df_list,keys=year_list,axis=0) #axis=1或axis=0,依据个人习惯return df_q = query(indicator.code, indicator.statDate,indicator.roe,indicator.inc_return,indicator.pubDate, ).filter( income.code.in_(['000001.XSHE','600507.XSHG']))df = get_more_state_fund(q,['2017','2018'])# df.loc[('2014',slice(None))]df
code | roe | inc_return | pubDate | ||
---|---|---|---|---|---|
statDate | |||||
2017 | 2017-03-31 | 000001.XSHE | 3.0319 | 3.0309 | 2017-04-22 |
2017-03-31 | 600507.XSHG | 10.2024 | 10.0997 | 2017-04-22 | |
2017-06-30 | 000001.XSHE | 3.0249 | 3.0058 | 2017-08-11 | |
2017-06-30 | 600507.XSHG | 14.0929 | 14.2133 | 2017-08-19 | |
2017-09-30 | 000001.XSHE | 3.0724 | 3.0813 | 2017-10-21 | |
2017-09-30 | 600507.XSHG | 24.2866 | 23.9243 | 2017-10-24 | |
2017-12-31 | 000001.XSHE | 1.8339 | 1.8320 | 2018-03-15 | |
2017-12-31 | 600507.XSHG | 22.9191 | 19.8184 | 2018-02-09 | |
2018 | 2018-03-31 | 000001.XSHE | 2.9611 | 2.9431 | 2018-04-20 |
2018-03-31 | 600507.XSHG | 13.6345 | 13.6067 | 2018-04-21 | |
2018-06-30 | 000001.XSHE | 3.0018 | 2.9991 | 2018-08-16 | |
2018-06-30 | 600507.XSHG | 19.9856 | 19.7203 | 2018-08-18 |
#h获取多年度财务数据import pandas as pdstock_list=['000001.XSHE','000527.XSHE','600970.XSHG','600875.XSHG','600880.XSHG']years = range(2005,2018)df_list=[]for year in years:df_year= get_fundamentals(query( indicator.code, indicator.inc_return,indicator.roe ).filter( indicator.code.in_(stock_list) ),statDate=year).set_index('code')df_list.append(df_year)name = [str(x) for x in range(2005,2017)]df=pd.concat(df_list,axis=1,keys=name)df
2005 | 2006 | 2007 | 2008 | 2009 | ... | 2012 | 2013 | 2014 | 2015 | 2016 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
inc_return | roe | inc_return | roe | inc_return | roe | inc_return | roe | inc_return | roe | ... | inc_return | roe | inc_return | roe | inc_return | roe | inc_return | roe | inc_return | roe | |
000001.XSHE | 6.8734 | 6.3868 | 21.2849 | 22.6025 | 26.7708 | 27.2057 | 4.2435 | 4.1761 | 26.7942 | 27.2887 | ... | 16.9316 | 16.9537 | 15.4064 | 15.4724 | 16.3280 | 16.2959 | 14.9783 | 14.9530 | 12.4321 | 12.4283 |
000527.XSHE | 13.3490 | 13.3300 | 15.7667 | 16.3908 | 26.3179 | 29.8230 | 24.7264 | 22.3681 | 26.2619 | 26.6314 | ... | 16.2383 | 16.5337 | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
600875.XSHG | 34.1418 | 34.0314 | 22.7201 | 57.1331 | 16.2666 | 47.2531 | 56.7490 | 6.7020 | 30.2382 | 28.6972 | ... | 13.7332 | 14.8649 | 13.4276 | 14.0803 | 6.2436 | 6.8654 | 1.4852 | 2.0616 | -8.9718 | -8.0745 |
600880.XSHG | 18.1740 | 18.5634 | 21.3198 | 12.3548 | 19.8543 | 20.2199 | 18.9755 | 19.9203 | 20.9028 | 22.6681 | ... | 13.1731 | 13.2258 | 11.4463 | 11.7852 | 8.0076 | 7.9088 | 0.7765 | 2.0698 | -0.7119 | 1.6685 |
600970.XSHG | 15.8088 | 17.5163 | 14.8404 | 30.9030 | 25.1281 | 28.2336 | 43.4164 | 30.6846 | 48.4384 | 47.1297 | ... | 16.3465 | 17.0652 | -0.5751 | 2.0248 | 2.2335 | 3.4041 | 8.9119 | 12.2016 | 4.3695 | 7.6902 |
5 rows × 24 columns
panel = get_price(['600741.XSHG','600507.XSHG'],count=10)df = panel.to_frame()df#df转panel用 to_frame 具体参数自行百度
close | high | low | money | open | volume | ||
---|---|---|---|---|---|---|---|
major | minor | ||||||
2015-12-18 | 600741.XSHG | 14.57 | 14.71 | 14.47 | 249894512 | 14.64 | 17143017 |
600507.XSHG | 5.40 | 5.46 | 5.28 | 119299016 | 5.34 | 22172918 | |
2015-12-21 | 600741.XSHG | 15.00 | 15.06 | 14.45 | 561062656 | 14.47 | 37628777 |
600507.XSHG | 5.44 | 5.48 | 5.34 | 120579072 | 5.44 | 22289871 | |
2015-12-22 | 600741.XSHG | 15.05 | 15.12 | 14.82 | 356481920 | 15.01 | 23841678 |
600507.XSHG | 5.55 | 5.55 | 5.37 | 116308071 | 5.44 | 21159089 | |
2015-12-23 | 600741.XSHG | 15.05 | 15.48 | 15.01 | 526013568 | 15.07 | 34589435 |
600507.XSHG | 5.52 | 5.56 | 5.40 | 107255632 | 5.55 | 19548463 | |
2015-12-24 | 600741.XSHG | 15.16 | 15.25 | 14.72 | 336079552 | 15.12 | 22449441 |
600507.XSHG | 5.41 | 5.52 | 5.33 | 55860480 | 5.46 | 10315692 | |
2015-12-25 | 600741.XSHG | 15.18 | 15.30 | 15.00 | 198292693 | 15.19 | 13086915 |
600507.XSHG | 5.51 | 5.53 | 5.34 | 88182432 | 5.40 | 16201856 | |
2015-12-28 | 600741.XSHG | 14.69 | 15.31 | 14.66 | 322978295 | 15.23 | 21620409 |
600507.XSHG | 5.31 | 5.50 | 5.28 | 95083681 | 5.48 | 17572145 | |
2015-12-29 | 600741.XSHG | 14.76 | 14.98 | 14.60 | 240761086 | 14.73 | 16316632 |
600507.XSHG | 5.34 | 5.34 | 5.18 | 54872134 | 5.28 | 10410516 | |
2015-12-30 | 600741.XSHG | 14.77 | 14.92 | 14.62 | 247207723 | 14.81 | 16758734 |
600507.XSHG | 5.34 | 5.36 | 5.27 | 41995759 | 5.34 | 7885443 | |
2015-12-31 | 600741.XSHG | 14.60 | 14.86 | 14.58 | 189099871 | 14.74 | 12879952 |
600507.XSHG | 5.25 | 5.40 | 5.24 | 72433062 | 5.34 | 13627293 |
def set_stock(stock_list,end_date,N=63,X =0):'''默认剔除过去3个月有过停牌的股票'''datas = get_price(stock_list,end_date=end_date,fields=['paused'], skip_paused=False, fq='pre', count=N)f = datas.to_frame()g=f[f.iloc[:,0]==1].unstack()['paused']i =N-g.isnull().sum()t = i[i>X].index.tolist() new_stock_list = list(set(stock_list) ^ set(t))return new_stock_liststocks = get_all_securities().index.tolist()set_stock(stocks,'2018-09-28')[:5]
['002233.XSHE', '603809.XSHG', '002897.XSHE', '002596.XSHE', '600387.XSHG']
注意区分pandas版本,不同版本的用法及参数,目前0.23是兼容0.16的(官网研究默认环境和回测都是0.16,pacver版本为0.23):
rolling 是对窗口进行移动处理,窗口大小自定义,大小不变
expanding是对窗口进行拓展处理,窗口大小不断变大
import pandas as pdc_data = get_price(['600741.XSHG','600507.XSHG','000001.XSHE'],fields='high',end_date='2018-09-26',count=100).high
# 求序列的HHV5pd.rolling_max(c_data,window=5,min_periods=None, freq=None, center=False, how='max')[5:10] #pandas0.16用法 # c_data.rolling(window=5, min_periods=None, freq=None, center=False, win_type=None, on=None, # axis=0, closed=None).max() #pandas 0.23用法
600741.XSHG | 600507.XSHG | 000001.XSHE | |
---|---|---|---|
2018-05-15 | 24.08 | 13.62 | 11.06 |
2018-05-16 | 24.08 | 13.62 | 11.06 |
2018-05-17 | 24.08 | 13.62 | 11.06 |
2018-05-18 | 24.08 | 13.62 | 11.06 |
2018-05-21 | 24.35 | 13.56 | 11.02 |
#求序列过去一段时间所产生的历史最高价序列pd.expanding_max(c_data,min_periods=0, freq=None).head() #pandas0.16用法 # c_data.expanding(min_periods=1, freq=None).max() #pandas 0.23用法
600741.XSHG | 600507.XSHG | 000001.XSHE | |
---|---|---|---|
2018-05-08 | 23.79 | 13.62 | 10.98 |
2018-05-09 | 23.79 | 13.62 | 10.98 |
2018-05-10 | 23.84 | 13.62 | 10.98 |
2018-05-11 | 23.84 | 13.62 | 10.98 |
2018-05-14 | 24.01 | 13.62 | 11.06 |
#求序列的 MA5 序列pd.rolling_mean(c_data,window=5,min_periods=None, freq=None, center=False, how='max')[-5:]
600741.XSHG | 600507.XSHG | 000001.XSHE | |
---|---|---|---|
2018-09-19 | 20.114 | 10.676 | 9.962 |
2018-09-20 | 20.126 | 10.728 | 10.016 |
2018-09-21 | 20.412 | 10.814 | 10.182 |
2018-09-25 | 20.706 | 10.910 | 10.354 |
2018-09-26 | 21.054 | 10.954 | 10.480 |
import pandas as pd#注意ema有用到回溯算法,所以出于指标精度方面考虑建议数据的长度至少为span的2-3倍,且前期数据可能不太准确,如需使用到更多ema数据#需要增加依赖数据的长度c_data = get_price(['600741.XSHG','600507.XSHG','000001.XSHE'],fields='close',end_date='2018-09-26', fq=None,count=10*3).closepd.ewma(c_data,span=5)[-5:]
600741.XSHG | 600507.XSHG | 000001.XSHE | |
---|---|---|---|
2018-09-19 | 20.140727 | 10.752822 | 10.026004 |
2018-09-20 | 20.120484 | 10.781882 | 10.094004 |
2018-09-21 | 20.676996 | 10.867922 | 10.286005 |
2018-09-25 | 20.907999 | 10.891948 | 10.374004 |
2018-09-26 | 21.212001 | 10.961299 | 10.486003 |
#计算结果与行情软件有稍许差异,对比数据没有问题 ,经过验证是由计算精度引起的(交易软件的成交量精度),实际上平台的结果是更准确的def get_v_ratio(security_list,time):'''计算某个时间点股票的量比, 输入:股票池/股票,时间(datetime) 返回:截至当天某一时间点的量比'''if isinstance(security_list,str):security_list = [security_list]d = {}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).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)# print start_time,timereturn dsecurity_list = ['600016.XSHG','601166.XSHG','000001.XSHE']time = datetime.datetime(2018,9,27,15,30)get_v_ratio(security_list,time)
{'000001.XSHE': 0.7405546291120892, '600016.XSHG': 0.8102664114217498, '601166.XSHG': 0.8697879043965755}
#使用新浪数据 000001.XSHE 在 2018年9月27日的数据计算的结果:round((88.04/240)/(594.38/1200),2)
0.74
当用pandas绘图时,当index为datetimeindex时会自动根据横轴(index)进行补全,导致出现非交易时间而出现绘图跳空: 方法1:https://blog.csdn.net/tpoy0099/article/details/49511907 方法2:
import matplotlib.pyplot as plt# plt.rcParams['font.sans-serif']=['SimHei'] # 标签mpl.rcParams['font.family']='serif' #用来正常显示中文plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号
df = get_price('600741.XSHG',end_date='2018-09-27 09:50:00',frequency='1m',count=50,fields='close')df.plot()print type(df.index) #会出现问题的绘图方法:
<class 'pandas.tseries.index.DatetimeIndex'>
将index转为str类型:
import pandas as pdimport numpy as npdf = get_price('600741.XSHG',end_date='2018-09-27 09:50:00',frequency='1m',count=50,fields=['close','volume'],skip_paused=True)index = df.indexpydate_array = index.to_pydatetime()date_only_array = np.vectorize(lambda s: s.strftime('%Y-%m-%d %H:%M:%S'))(pydate_array ) #将datetimeindex转为strdf.index = date_only_arrayprint type(df.index)plt.axhline(21.8, color="black", linestyle="-") #绘制轴线df.volume.plot(secondary_y = True,kind='bar',legend=True) df.close.plot(figsize=(15,5),grid=True,rot =50,fontsize=10,title='正常显示',legend=True, style='r') #通过多次绘制series和secondary_y绘制右刻度,grid显示网格,rot控制标签斜率,fontsize控制字体大小,style控制颜色,legend显示标注
<class 'pandas.core.index.Index'>
<matplotlib.axes._subplots.AxesSubplot at 0x7f04e42e2a50>
luanma = get_all_securities().display_name.values
其实这只是python2的显示问题,只能曲线救国,其实如果只是查看某个list的内容,建议转化成其他形式(如dataframe)而非list, 当然还可以直接切换到python3内核:
import pandas as pdpd.DataFrame(luanma).head()
0 | |
---|---|
0 | 平安银行 |
1 | 万科A |
2 | 国农科技 |
3 | 世纪星源 |
4 | 深振业A |
print luanma #输出显示乱码print type(luanma[0]) #检查为unicode类型print luanma[0] #单个用print输出正常right_str = str(luanma).replace('u\'','\'').decode("unicode-escape") #可以用print输出,但类型变为unicode而非listprint type(right_str)print right_str
[u'\u5e73\u5b89\u94f6\u884c' u'\u4e07\u79d1A' u'\u56fd\u519c\u79d1\u6280' ..., u'\u7ee7\u5cf0\u80a1\u4efd' u'\u65b9\u76db\u5236\u836f' u'\u8bfb\u8005\u4f20\u5a92'] <type 'unicode'> 平安银行 <type 'unicode'> ['平安银行' '万科A' '国农科技' ..., '继峰股份' '方盛制药' '读者传媒']
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 panelsecuritys =get_index_stocks('399015.XSHE')date='2018-01-01'DividendRatio(securitys,date)
<class 'pandas.core.panel.Panel'> Dimensions: 1 (items) x 1 (major_axis) x 500 (minor_axis) Items axis: DividendRatio to DividendRatio Major_axis axis: 2017-12-29 00:00:00 to 2017-12-29 00:00:00 Minor_axis axis: 000007.XSHE to 300735.XSHE
from jqdata import jy#期货合约每点价位 = ContractMulti*PriceUnit 注意统一单位q = query(jy.Fut_FuturesContract ).filter(jy.Fut_FuturesContract.Exchange.in_([10,11,13,15,19,20]),# jy.Fut_FuturesContract.TradingCode=='JD' )jy.run_query(q).tail()
ID | ContractName | ContractOption | Exchange | TradingCode | ContractType | ContractMulti | PriceUnit | LittlestChangeUnit | ChangePCTLim | ... | FinalSettlementPrice | DeliveryMethod | ContractIntroduction | UpdateTime | JSID | ContractInnerCode | NightTradingTime | ContractState | DeliveryUnit | DeliveryUnitValue | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54 | 471516344473 | 玉米淀粉 | 332 | 13 | CS | 1 | 10吨/手 | 元(人民币)/吨 | 1元/吨 | 上一交易日结算价的4%\r\n | ... | 1 | 交易品种\t玉米淀粉\r\n交易单位\t10吨/手\r\n报价单位\t元(人民币)/吨\r\... | 2018-08-02 14:32:52 | 586535573122 | 2005826 | None | 1 | None | None | |
55 | 551911961044 | 原油 | 319 | 11 | SC | 1 | 1000桶/手 | 元(人民币)/桶(交易报价为不含税价格) | 0.1元(人民币)/桶 | 不超过上一交易日结算价±4% | ... | 1 | 交易品种 中质含*原油\r\n交易单位 1000桶/手\r\n报价单位 元(人民币)/... | 2018-08-02 14:32:52 | 586535573123 | 2008596 | 21:00-次日02:30 | 1 | None | None | |
56 | 451415224875 | 早籼稻 | 412 | 15 | RI | 1 | 20吨/手 | 元(人民币)/吨 | 1元/吨 | 上一交易日结算价±4%及《郑州商品交易所期货交易风险控制管理办法》相关规定\r\n | ... | 1 | 交易品种\t早籼稻\r\n交易单位\t20吨/手\r\n报价单位\t元(人民币)/吨\r\n... | 2018-08-02 14:32:52 | 586535573124 | 2005502 | None | 1 | None | None | |
57 | 562352751053 | 中证500指数 | 4978 | 20 | IC | 4 | 每点200元 | 指数点 | 0.2点 | 上一个交易日结算价的±10% | ... | 股指期货交割结算价为最后交易日标的指数最后二小时的算术平均价。交易所有权根据市场情况对股指期... | 2 | 合约标的 \t中证500指数 \r\n合约乘数 \t每点200元 \r\n报价单位 \t指数... | 2018-08-02 14:32:52 | 586535573127 | 2006035 | None | 1 | None | None |
58 | 347714139750 | 棕榈油 | 349 | 13 | P | 1 | 10吨/手 | 元(人民币)/吨 | 2元/吨 | 上一交易日结算价的4% \r\n | ... | 1 | 交易品种\t棕榈油\r\n交易单位\t10吨/手\r\n报价单位\t元(人民币)/吨\r\n... | 2018-08-02 14:32:52 | 586535573128 | 2000026 | 前一自然日21∶00至前一自然日23∶30(周一夜盘交易时段为上周五的21∶00至上周五的2... | 1 | None | None |
5 rows × 30 columns
from jqdata import jyfrom jqdata import *import pandas as pd#注意申万指数在2014年有一次大改,聚源使用的是为改变之前的代码,官网包含更改前和更改后的代码,如果遇到找不到的标的可以根据需求自行查找#如801124 >>801121食品加工IIdef get_sw_quote(code,end_date=None,count=None,start_date=None):'''获取申万指数行情,返回panel结构'''if isinstance(code,str):code=[code]days = get_trade_days(start_date,end_date,count)code_df = jy.run_query(query( jy.SecuMain.InnerCode,jy.SecuMain.SecuCode,jy.SecuMain.ChiName).filter(jy.SecuMain.SecuCode.in_(code)))df = jy.run_query(query( jy.QT_SYWGIndexQuote).filter(jy.QT_SYWGIndexQuote.InnerCode.in_(code_df.InnerCode),jy.QT_SYWGIndexQuote.TradingDay.in_(days),))df2 = pd.merge(code_df, df, on='InnerCode').set_index(['TradingDay','SecuCode'])df2.drop(['InnerCode','ID','UpdateTime','JSID'],axis=1,inplace=True)return df2.to_panel()code = get_industries(name='sw_l2').index[:5]df = get_sw_quote(code,end_date='2018-01-01',count=10)df.to_frame(False).tail()
ChiName | PrevClosePrice | OpenPrice | HighPrice | LowPrice | ClosePrice | TurnoverVolume | TurnoverValue | TurnoverDeals | ChangePCT | RightLevel | IndexPE | IndexPB | TotalMarketValue | AShareTotalMV | ||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
TradingDay | SecuCode | |||||||||||||||
2017-12-29 | 801011 | 申银万国指数-林业 | 1800.092 | 1795.480 | 1845.60 | 1784.41 | 1802.798 | 2853232 | 35547011 | NaN | 0.0015 | 4 | 777.37 | 3.13 | 2036129 | 1121708 |
801012 | 申银万国指数-农产品加工 | 2551.776 | 2546.600 | 2573.80 | 2515.61 | 2556.512 | 93670965 | 1234257297 | NaN | 0.0019 | 4 | 35.58 | 3.12 | 14529320 | 7936090 | |
801013 | 申银万国指数-农业综合 | 2269.610 | 2260.530 | 2278.20 | 2254.30 | 2272.480 | 9084945 | 42341246 | NaN | 0.0013 | 4 | 125.71 | 2.92 | 867493 | 464852 | |
801014 | 申银万国指数-饲料 | 3644.520 | 3646.568 | 3709.26 | 3610.05 | 3685.350 | 133928157 | 1452712964 | NaN | 0.0112 | 4 | 23.78 | 2.71 | 21027565 | 8124732 | |
801015 | 申银万国指数-渔业 | 1540.178 | 1535.748 | 1566.71 | 1528.66 | 1555.760 | 34618204 | 301252413 | NaN | 0.0101 | 4 | 43.95 | 2.52 | 5217722 | 2511131 |
def get_zz_quote(code,end_date=None,count=None,start_date=None):'''获取中证指数行情,返回panel结构'''if isinstance(code,str):code=[code]code.sort()code = [x[:6] for x in code]days = get_trade_days(start_date,end_date,count)code_df = jy.run_query(query( jy.SecuMain.InnerCode,jy.SecuMain.SecuCode,jy.SecuMain.ChiName).filter(jy.SecuMain.SecuCode.in_(code)).order_by(jy.SecuMain.SecuCode))df = jy.run_query(query( jy.QT_CSIIndexQuote).filter(jy.QT_CSIIndexQuote.IndexCode.in_(code_df.InnerCode),jy.QT_CSIIndexQuote.TradingDay.in_(days),))df2 = pd.merge(code_df, df, left_on='InnerCode',right_on='IndexCode').set_index(['TradingDay','SecuCode'])df2.drop(['InnerCode','IndexCode','ID','UpdateTime','JSID','OpenInterest','SettleValue','IndexCSIType'],axis=1,inplace=True)return df2.to_panel()panel = get_zz_quote(['000016.XSHG','000001.XSHG'],end_date='2018-01-01',count=10)panel.ClosePrice.tail()
SecuCode | 000001 | 000016 |
---|---|---|
TradingDay | ||
2017-12-25 | 3280.4610 | 2880.0968 |
2017-12-26 | 3306.1246 | 2894.3358 |
2017-12-27 | 3275.7828 | 2839.6346 |
2017-12-28 | 3296.3847 | 2859.0537 |
2017-12-29 | 3307.1721 | 2860.4363 |
df = get_all_securities(types=['futures']) #获取期货合约# dominant_and_idnex = df[df.end_date==datetime.date(2030,1,1)] #商品指数和主力合约dominant_future = [d for d in df.index if '9999' in d] #所有品种的主力合约index_future = [i for i in df.index if '8888' in i] #所有品种的指数代码code_name = [c[:-9] for c in index_future] #获取各个品种代号,使用get_dominant_future时会用到
#2层的嵌套字典可以转为dataframe,3层的嵌套字典可以转为panel方便后续的数据处理,下边以个股的所属行业数据为例from jqdata import *import pandas as pdstocks = get_index_stocks('000300.XSHG')industry_dict = get_industry(stocks)panel = pd.Panel(industry_dict)panel[:,'industry_code' ]
000001.XSHE | 000002.XSHE | 000060.XSHE | 000063.XSHE | 000069.XSHE | 000100.XSHE | 000157.XSHE | 000166.XSHE | 000333.XSHE | 000338.XSHE | ... | 601992.XSHG | 601997.XSHG | 601998.XSHG | 603160.XSHG | 603260.XSHG | 603288.XSHG | 603799.XSHG | 603833.XSHG | 603858.XSHG | 603993.XSHG | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jq_l1 | HY007 | HY011 | HY002 | HY008 | HY004 | HY004 | HY003 | HY007 | HY004 | HY003 | ... | HY002 | HY007 | HY007 | HY008 | HY002 | HY005 | HY002 | HY004 | HY006 | HY002 |
jq_l2 | HY493 | HY509 | HY414 | HY516 | HY457 | HY446 | HY426 | HY501 | HY449 | HY426 | ... | HY410 | HY494 | HY493 | HY524 | HY405 | HY481 | HY414 | HY447 | HY572 | HY414 |
sw_l1 | 801780 | 801180 | 801050 | 801770 | 801180 | 801110 | 801890 | 801790 | 801110 | 801880 | ... | 801230 | 801780 | 801780 | 801080 | 801050 | 801120 | 801050 | 801140 | 801150 | 801050 |
sw_l2 | 801192 | 801181 | 801055 | 801102 | 801181 | 801112 | 801074 | 801193 | 801111 | 801093 | ... | 801231 | 801192 | 801192 | 801081 | 801051 | 801124 | 801054 | 801142 | 801155 | 801054 |
sw_l3 | 851911 | 851811 | 850553 | 851013 | 851811 | 851121 | 850722 | 851931 | 851112 | 850921 | ... | 852311 | 851911 | 851911 | 850811 | 850523 | 851242 | 850544 | 851432 | 851521 | 850544 |
zjw | J66 | K70 | C32 | C39 | K70 | C39 | C35 | J67 | C38 | C36 | ... | C30 | J66 | J66 | C39 | C26 | C14 | C32 | C21 | C27 | B09 |
6 rows × 300 columns
在获取报告期数据时,因为有些报表是增量性质的,这个季度无法和上个季度进行对比,所以大多数是与上年进行同比,下面以获取中报数据为例:
from jqdata import finance# 获取000001.XSHG每一年的年报 df = finance.run_query(query(finance.FINANCE_INCOME_STATEMENT ).filter(finance.FINANCE_INCOME_STATEMENT.code=='000001.XSHE',finance.FINANCE_INCOME_STATEMENT.end_date.like('%-06-30'),#或end_date.contains('12-31') ,end_date.like('_____12-31'),# finance.FINANCE_INCOME_STATEMENT.pub_date>='2015-01-01',finance.FINANCE_INCOME_STATEMENT.report_type==0 ))df.tail()
id | company_id | company_name | code | a_code | b_code | h_code | pub_date | start_date | end_date | ... | net_profit | np_parent_company_owners | minority_profit | eps | basic_eps | diluted_eps | other_composite_income | total_composite_income | ci_parent_company_owners | ci_minority_owners | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20 | 2539 | 430000001 | 平安银行股份有限公司 | 000001.XSHE | 000001 | None | None | 2014-08-14 | 2014-01-01 | 2014-06-30 | ... | 1.007200e+10 | 1.007200e+10 | NaN | NaN | 0.88 | 0.88 | 3.100000e+08 | 1.038200e+10 | NaN | NaN |
21 | 2547 | 430000001 | 平安银行股份有限公司 | 000001.XSHE | 000001 | None | None | 2015-08-14 | 2015-01-01 | 2015-06-30 | ... | 1.158500e+10 | 1.158500e+10 | NaN | NaN | 0.84 | 0.84 | 3.940000e+08 | 1.197900e+10 | NaN | NaN |
22 | 2555 | 430000001 | 平安银行股份有限公司 | 000001.XSHE | 000001 | None | None | 2016-08-12 | 2016-01-01 | 2016-06-30 | ... | 1.229200e+10 | 1.229200e+10 | NaN | NaN | 0.72 | 0.72 | 1.440000e+08 | 1.243600e+10 | 1.243600e+10 | NaN |
23 | 2562 | 430000001 | 平安银行股份有限公司 | 000001.XSHE | 000001 | None | None | 2017-08-11 | 2017-01-01 | 2017-06-30 | ... | 1.255400e+10 | 1.255400e+10 | NaN | NaN | 0.68 | 0.68 | 3.160000e+08 | 1.287000e+10 | 1.287000e+10 | NaN |
24 | 4321 | 430000001 | 平安银行股份有限公司 | 000001.XSHE | 000001 | None | None | 2018-08-16 | 2018-01-01 | 2018-06-30 | ... | 1.337250e+10 | 1.337250e+10 | NaN | NaN | 0.73 | 0.73 | 4.557387e+08 | 1.382824e+10 | 1.382824e+10 | NaN |
5 rows × 66 columns
df = get_all_securities()df[df.display_name.str.contains('证券',regex=False)] #挑选出display_name中含有'证券'字的行
display_name | name | start_date | end_date | type | |
---|---|---|---|---|---|
000562.XSHE | 宏源证券 | HYZQ | 1994-02-02 | 2015-01-26 | stock |
000686.XSHE | 东北证券 | DBZQ | 1997-02-27 | 2200-01-01 | stock |
000728.XSHE | 国元证券 | GYZQ | 1997-06-16 | 2200-01-01 | stock |
000750.XSHE | 国海证券 | GHZQ | 1997-07-09 | 2200-01-01 | stock |
000776.XSHE | 广发证券 | GFZQ | 1997-06-11 | 2200-01-01 | stock |
000783.XSHE | 长江证券 | CJZQ | 1997-07-31 | 2200-01-01 | stock |
002500.XSHE | 山西证券 | SXZQ | 2010-11-15 | 2200-01-01 | stock |
002673.XSHE | 西部证券 | XBZQ | 2012-05-03 | 2200-01-01 | stock |
002736.XSHE | 国信证券 | GXZQ | 2014-12-29 | 2200-01-01 | stock |
002926.XSHE | 华西证券 | HXZQ | 2018-02-05 | 2200-01-01 | stock |
002939.XSHE | 长城证券 | CCZQ | 2018-10-26 | 2200-01-01 | stock |
600030.XSHG | 中信证券 | ZXZQ | 2003-01-06 | 2200-01-01 | stock |
600109.XSHG | 国金证券 | GJZQ | 1997-08-07 | 2200-01-01 | stock |
600369.XSHG | 西南证券 | XNZQ | 2001-01-09 | 2200-01-01 | stock |
600837.XSHG | 海通证券 | HTZQ | 1994-02-24 | 2200-01-01 | stock |
600909.XSHG | 华安证券 | HAZQ | 2016-12-06 | 2200-01-01 | stock |
600958.XSHG | 东方证券 | DFZQ | 2015-03-23 | 2200-01-01 | stock |
600999.XSHG | 招商证券 | ZSZQ | 2009-11-17 | 2200-01-01 | stock |
601108.XSHG | 财通证券 | CTZQ | 2017-10-24 | 2200-01-01 | stock |
601162.XSHG | 天风证券 | TFZQ | 2018-10-19 | 2200-01-01 | stock |
601198.XSHG | 东兴证券 | DXZQ | 2015-02-26 | 2200-01-01 | stock |
601375.XSHG | 中原证券 | ZYZQ | 2017-01-03 | 2200-01-01 | stock |
601377.XSHG | 兴业证券 | XYZQ | 2010-10-13 | 2200-01-01 | stock |
601555.XSHG | 东吴证券 | DWZQ | 2011-12-12 | 2200-01-01 | stock |
601688.XSHG | 华泰证券 | HTZQ | 2010-02-26 | 2200-01-01 | stock |
601788.XSHG | 光大证券 | GDZQ | 2009-08-18 | 2200-01-01 | stock |
601878.XSHG | 浙商证券 | ZSZQ | 2017-06-26 | 2200-01-01 | stock |
601901.XSHG | 方正证券 | FZZQ | 2011-08-10 | 2200-01-01 | stock |
601990.XSHG | 南京证券 | NJZQ | 2018-06-13 | 2200-01-01 | stock |
from line_profiler import LineProfilerimport randomdef do_stuff(a,b):s = sum(1000)l = [numbers[i]/43 for i in range(len(numbers))]m = ['hello'+str(numbers[i]) for i in range(len(numbers))]numbers = [random.randint(1,100) for i in range(1000)]lp = LineProfiler() lp_wrapper = lp(do_stuff) #函数lp_wrapper(numbers,100) #写入参数运行,如果没有参数括号中就无需内容lp.print_stats() #显示
Timer unit: 1e-06 s Total time: 0.002667 s File: <ipython-input-60-cae2cba1719c> Function: do_stuff at line 4 Line # Hits Time Per Hit % Time Line Contents ============================================================== 4 def do_stuff(a,b): 5 1 89 89.0 3.3 s = sum(1000) 6 1001 1309 1.3 49.1 l = [numbers[i]/43 for i in range(len(numbers))] 7 1001 1269 1.3 47.6 m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
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))return get_fundamentals_continuously(q,end_date=end_date,count=day).turnover_ratio.sum()shuttle_turnover_ratio(['600741.XSHG','000002.XSHE'],'2018-11-13','2018-10-01')
code 000002.XSHE 16.2519 600741.XSHG 10.6901 dtype: float64
本社区仅针对特定人员开放
查看需注册登录并通过风险意识测评
5秒后跳转登录页面...
移动端课程