quantos-org / jaqs Goto Github PK
View Code? Open in Web Editor NEWHome Page: http://www.quantos.org/jaqs/
License: Other
Home Page: http://www.quantos.org/jaqs/
License: Other
以商品期货rb为例,4018.0开多1手,4042.0平仓1手,trading_PnL的计算就是24.0
但螺纹钢每手10吨,PnL应该是240.0
如果init_balance 设为10000.0,这样return的计算是0.24%,而实际应该是2.4%
在JAQS中,日期时间都被分开存储并转换成数字形式。这样就没法方便地利用pandas中的日期时间处理函数了。更麻烦的是,丢失了时区信息,当标地处于不同时区的市场时,没法处理啊。
···
trade_date : int
%YY%mm%dd
date : int
%YY%mm%dd, natural date.
time : int
%HH%mm%ss
···
from jaqs.trade.tradeapi import TradeApi
tapi = TradeApi(addr="tcp://gw.quantos.org:8901")
Exception cannot import name 'createWsUrl'
TradeApi: _on_connected
之前会提示少了jrpc包,安装了jrpd包之后就提示上述问题
环境:max os 10.13 python 3.6 jaqs 0.6.6
感觉文档描述的不是很清楚?
data api的说明中这两个完全一样啊。代码里的说明也几乎完全一样。
既然是一样的东西,为什么要用两个函数?
bar | 提供历史分时数据和实时分时数据 | 支持的范围包括:1分钟、5分钟、15分钟 |
---|---|---|
bar_quote | 提供历史分时数据和实时分时数据 | 支持的范围包括:1分钟、5分钟、15分钟 |
weights_sub_universe, msg = func(**options),长度和self.ctx.universe一样,这也导致#issue46,停牌股票本来在sub_univ中被剔除了,但是接下来的计算没有用sub_universe,还是剔除前的universe
目前数据接口只能一天一天取历史日内的 bar 数据,希望增加一个函数,能够取一段时间的日内的 bar 数据,同时支持复权。
None -1,goal rejected (reject_ratio not defined) because: assertion failed: order[000001.SZ] ref_price[0.0] violates RuleLimit(1,price_diff,<=,0.03,E), l
如果是在你们服务器上的话,是不是就无法利用本地电脑的性能了?
看了一下代码,回测是要在联网的状态下?
1、如何下载ipynb文件呢?
2、已经申请了quantos账号密码,token在哪里可以看到?
在数据api文档中关于输入参数是这样写的:
fields | string | 需要返回字段,多字段以','隔开;为""时返回所有字段
目前只测试了证券基础信息和交易日历的这2个API,发现如果fields参数设置为空字符串的话,并不会按照文档所说的返回所有字段的数据。
1.证券基础信息API只返回list_date,name,symbol这3个字段。
2.交易日历API只返回istradeday,trade_date这2个字段。
API用法如下:
df, msg = qos.api.daily(
symbol='131802.SZ',
start_date=20170425,
end_date=20180427,
fields="",
adjust_mode="post")
得到一个empty df.
请问支持回购数据的获取吗?
输入:api.login("phone", "token")
输出:(None, '-1000,login failure: Map(username -> phone, password -> token)')
不好意思 打搅了 我不是很懂接口的问题 请问这个是怎么回事,该怎样解决
国内商品期货,夜盘时间属于下一个交易日。
所以,对于有夜盘的品种,每个交易日范围开始是上一交易如日的夜盘开盘,到本日下午收盘。tushare的bar()方法返回中用两个字段标识这种区别:date(物理时间)和trade_date(所属交易日)
所以,回测中以1M的bar为例,D日的第一个到达的quote应该是trade_date==D交易日的210100(物理时间date是D-1日的210100),最后一个是trade_date==D交易日的150000。
而现在回测框架中,似乎把两个时间混淆了。回测中第一个到达的quote是trade_date==D日的90000,最后一个是trade_date==D日的夜盘收盘。这样造成了同一个交易日的日盘和夜盘两段时间到达相反了,应该是“先夜后日”,变成了“先日后夜”。
建议直接遵循tushare中bar()方法返回DataFrame的顺序,是按实际发生顺序排列的。
当分析日内交易记录(即同一天有买卖)时,会报错如下。
如:trade.csv文件如下
index,commission,entrust_action,entrust_no,fill_date,fill_no,fill_price,fill_size,fill_time,symbol,task_id,trade_date
0,0.3027,Buy,1,20170614,1,3027.0,1.0,134800,rb1710.SHF,201706140003,20170614
1,0.3073,Sell,2,20170614,2,3073.0,1.0,145700,rb1710.SHF,201706140004,20170614
运行 do_analyze(result_dir=result_dir_path, selected_sec=props['symbol'].split(','))
报错如下:
Traceback (most recent call last):
File "", line 1, in
analyze()
File "", line 214, in analyze
ta.do_analyze(result_dir=result_dir_path, selected_sec=props['symbol'].split(','))
File "/xxx/jaqs/trade/analyze/analyze.py", line 760, in do_analyze
self.get_returns(compound_return = compound_rtn, consider_commission=True)
File "/xxx/jaqs/trade/analyze/analyze.py", line 586, in get_returns
max_dd_start = np.argmax(active_cum[:max_dd_end]) # start of period
File "/xxx/numpy/core/fromnumeric.py", line 1004, in argmax
return _wrapfunc(a, 'argmax', axis=axis, out=out)
File "/xxx/numpy/core/fromnumeric.py", line 52, in _wrapfunc
return getattr(obj, method)(*args, **kwds)
ValueError: attempt to get argmax of an empty sequence
base_insts = pd.read_csv('https://www.quantos.org/downloads/basedata/instrument.csv')
inst_more_data, msg = jaqs_api.query(
view="jz.instrumentInfo",
fields='symbol,name,list_date,delist_date,status',
data_format='pandas'
)
inst_more_data.loc[
~inst_more_data.symbol.isin(base_insts.symbol)
]
前十条数据如下:
delist_date | list_date | name | status | symbol |
---|---|---|---|---|
99999999 | 20140101 | A50指数 | 1 | A50001.JZ |
99999999 | 20140101 | A50+3类基金 | 1 | A50003.JZ |
99999999 | 20140101 | A50+4类基金 | 1 | A50004.JZ |
99999999 | 20151214 | 创业板指 | 1 | S99006.JZ |
99999999 | 20151214 | 沪深300 | 1 | S00300.JZ |
99999999 | 20151214 | 中证500 | 1 | S00905.JZ |
99999999 | 20151214 | 上证50 | 1 | S00016.JZ |
99999999 | 20151214 | 深证100R | 1 | S99004.JZ |
99999999 | 20151214 | 国企改革 | 1 | S99974.JZ |
99999999 | 20151214 | 中证军工 | 1 | S99967.JZ |
我使用的是下面这个代码:
api = DataApi(addr='tcp://data.tushare.org:8910')
api.login("1339006***", "******")
df,_1 = api.bar(
symbol= symbol,
trade_date=int(i_date),
freq=freq,
fields="open,high,low,close,volume,date,time,oi")
比如持有今开的一手空单rb1805.SHF
通过 context.trade_api.place_order('rb1805.SHF','Cover',3915,1),vnpy侧能看到报单,但是会返回据单,因为仓位不足.
通过 context.trade_api.place_order('rb1805.SHF','CoverToday',3915,1),返回timeout,在vnpy侧未能看到报单信息.
Term | Value |
---|---|
Beta | 0.943 |
Maximum Drawdown (%) | 1.413 |
Maximum Drawdown start | 20171218 |
Maximum Drawdown end | 20171206 |
文档有好几个来源,中间还是有一些不统一的地方,所以有一些疑问:
running an example strategy DualThrust.
Current data config file path: E:\jaqs\config\data_config.json
Current trade config file path: E:\jaqs\config\trade_config.json
Begin: DataApi login 17621969269@tcp://data.tushare.org:8910
login success
on_new_day in trade 20170510
on_new_day in trade 20170511
on_new_day in trade 20170512
on_new_day in trade 20170515
on_new_day in trade 20170516
on_new_day in trade 20170517
on_new_day in trade 20170518
on_new_day in trade 20170519
Strategy on trade:
20170519( 90300) Buy [email protected] size = 1
Want Size Filled Size
====================================
Buy 0 1
------------------------------------
Sell 0 0
on_new_day in trade 20170522
on_new_day in trade 20170523
on_new_day in trade 20170524
Strategy on trade:
20170524( 111600) Sell [email protected] size = 2
Want Size Filled Size
====================================
Buy 0 0
------------------------------------
Sell 0 2
on_new_day in trade 20170525
on_new_day in trade 20170526
on_new_day in trade 20170531
on_new_day in trade 20170601
on_new_day in trade 20170602
on_new_day in trade 20170605
Traceback (most recent call last):
File "DualThrust.py", line 189, in <module>
run_strategy()
File "DualThrust.py", line 173, in run_strategy
ins.run()
File "\jaqs\trade\backtest.py", line 660, in run
self._run_bar()
File jaqs\trade\backtest.py", line 589, in _run_bar
self.on_new_day(trade_date)
File "jaqs\trade\backtest.py", line 558, in on_new_day
self.ctx.strategy.initialize()
File "DualThrust.py", line 64, in initialize
self.open_list[-1] = df.open
ValueError: setting an array element with a sequence.
Env: Python3.6 64bit
Thanks a lot for any help.
susp_fields = [
'symbol',
'ann_date',
'susp_date',
'susp_time',
'resu_date',
'resu_time',
'susp_reason'
]
df, msg = jaqs_api.query(
view='lb.secSusp',
symbol="",
start_date="2010-01-01",
end_date='',
fields=','.join(susp_fields),
)
date_pat = re.compile(r'\d{8}')
time_pat = re.compile(r'^\d{1,2}:\d{1,2}(:\d{1,2})?$')
def is_valid_rec(rec):
return bool(
(not rec.ann_date or date_pat.match(rec.ann_date)) and
(not rec.susp_date or date_pat.match(rec.susp_date)) and
(not rec.susp_time or time_pat.match(rec.susp_time)) and
(not rec.resu_date or date_pat.match(rec.resu_date)) and
(not rec.resu_time or time_pat.match(rec.resu_time))
)
nv = df.loc[ ~df.apply(is_valid_rec, axis=1) ]
nv
ann_date | resu_date | resu_time | susp_date | susp_reason | susp_time | symbol | |
---|---|---|---|---|---|---|---|
17725 | 20160927 | 20160928 | 9:30:00 | 20160927 | 刊登重要公告 | 13:00: 00 | 600246.SH |
Note the cell with 13:00: 00
in
df, msg = api.query(
view="lb.income",
fields="",
filter="symbol=002059.SZ",
data_format='pandas')
返回数据没有report_type, 无法区分母公司报表还是合并报表
现在实盘交易,要通过vnpy集成,出了问题也不好查。
很喜欢JAQS轻量化的设计,如果能够直接集成交易接口,就太好了。
clone后什么都没改,就添加了用户名和token,运行示例发现如下错误,do_analyze的时候里面有个对象时空的:
Traceback (most recent call last):
File "/Users/PycharmProjects/JAQS/example/eventdriven/DoubleMA.py", line 237, in
analyze()
File "/Users/PycharmProjects/JAQS/example/eventdriven/DoubleMA.py", line 232, in analyze
ta.do_analyze(result_dir=result_dir_path, selected_sec=[])
File "/Users/PycharmProjects/JAQS/jaqs/trade/analyze/analyze.py", line 1028, in do_analyze
self.get_daily()
File "/Users/PycharmProjects/JAQS/jaqs/trade/analyze/analyze.py", line 702, in get_daily
self._build_holding_data()
File "/Users/PycharmProjects/JAQS/jaqs/trade/analyze/analyze.py", line 743, in _build_holding_data
tmp = self.dataview.get_ts(base_fields, keep_level=True)
AttributeError: 'NoneType' object has no attribute 'get_ts'
Begin: DataApi login 13618*********@tcp://data.tushare.org:8910
Already login as 13618*********, skip init_from_config
process trades...
get daily stats...
calc strategy return...
D:\python_Anaconda3\lib\site-packages\numpy\lib\function_base.py:3167: RuntimeWarning: invalid value encountered in true_divide
c /= stddev[:, None]
D:\python_Anaconda3\lib\site-packages\numpy\lib\function_base.py:3168: RuntimeWarning: invalid value encountered in true_divide
c /= stddev[None, :]
Traceback (most recent call last):
File "D:\python_Anaconda3\lib\site-packages\matplotlib_init_.py", line 880, in setitem
cval = self.validatekey
KeyError: 'axes.titlepad'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/JAQS-master/example/eventdriven/DoubleMA.py", line 230, in
analyze()
File "D:/JAQS-master/example/eventdriven/DoubleMA.py", line 225, in analyze
ta.do_analyze(result_dir=result_dir_path, selected_sec=[])
File "D:\python_Anaconda3\lib\site-packages\jaqs\trade\analyze\analyze.py", line 506, in do_analyze
self.plot_pnl(result_dir)
File "D:\python_Anaconda3\lib\site-packages\jaqs\trade\analyze\analyze.py", line 400, in plot_pnl
mpl.rcParams.update(MPL_RCPARAMS)
File "D:\python_Anaconda3\lib\site-packages\matplotlib_init_.py", line 914, in update
self[k] = v
File "D:\python_Anaconda3\lib\site-packages\matplotlib_init_.py", line 886, in setitem
Plot strategy PnL...
See rcParams.keys() for a list of valid parameters.' % (key,))
KeyError: 'axes.titlepad is not a valid rc parameter.See rcParams.keys() for a list of valid parameters.'
Process finished with exit code 1
执行过: pip install jaqs --upgrade ,各个jaqs依赖的python的包应该都是最新版。
python3.5.2
windows系统。
在两台不同的电脑上,回测结果会不同
本来以为是python 2和python 3的版本问题,后来换了台电脑,都是Python2,结果遇到了同样的问题。
对比发现,trades.csv的结果都是一样的。
但是在生成报告时,生成的daily_position.csv和returns.csv的结果截然不同
在py_expression_eval.py 654行
是否应该是return x.rolling(n).corr(y)
?
衍生品定价是金融工程最重要的组成本分,也是量化交易的基础。建议将quantlib库整合到jaqs中。
我用的是Python 3.6, Windows系统
发现需要进行以下修改 程序才能正常运行
首先,第45、46行:
ic_weight_hd5_path = '../../output/ICCombine', 'ic_weight.hd5'
custom_data_path = '../../output/ICCombine', 'custom_date.json'
我改为了:
ic_weight_hd5_path = '../../output/ICCombine/ic_weight.hd5'
custom_data_path = '../../output/ICCombine/custom_date.json'
第二,在220行之后,还要添加:
dv.load_dataview(folder_path=dataview_dir_path)
需要把dataview重新加载一下,否则亲测get_snapshot函数无法获得通过append_df添加的列。不知道这个算不算bug。如果每次都要重新加载,未免有些蛋疼。
symbols = '603214.SH,300504.SZ,600929.SH,002930.SZ,603733.SH,603876.SH,000585.SZ,002931.SZ,603707.SH,600860.SH'
df, msg = jaqs_api.daily(
symbol=symbols,
start_date='2018-04-23',
end_date='2018-04-23',
fields='symbol,open,close,high,low,trade_date,volume,turnover,vwap',
adjust_mode=None,
)
len(df)
0
(1)无法获取指数成分股数据, df返回为None
df, msg = api.query(
view="lb.indexCons",
fields="",
filter="index_code=399001",
data_format='pandas')
(2)无法获取行业数据,df返回为None
df, msg = api.query(
view="lb.secIndustry",
fields="",
filter="industry1_name=金融&industry2_name=金融&industry_src=中证",
data_format='pandas')
Function rolling_corr
was deprecated since version 0.18. Please update your requirements.txt
or py_expression_eval.py
.
对于中长期的策略,会有symbol换月(比如rb1801换到rb1805)和日期衔接的问题,
现在的机制可以分段测试再连接起来,但是有些情况不方便测试(比如持仓换月),建议是否可以考虑加入换月的机制?
Traceback (most recent call last):
File "/home/ma/Documents/workspace-python/QuantSystem/JAQS/test/my_alpha_test.py", line 100, in
tr,props = do_back_test(dv)
File "/home/ma/Documents/workspace-python/QuantSystem/JAQS/test/my_alpha_test.py", line 76, in do_back_test
bt.run_alpha()
File "/home/ma/Documents/workspace-python/QuantSystem/JAQS/jaqs/trade/backtest.py", line 454, in run_alpha
self.re_balance_plan_after_open()
File "/home/ma/Documents/workspace-python/QuantSystem/JAQS/jaqs/trade/backtest.py", line 408, in re_balance_plan_after_open
suspensions=all_list)
File "/home/ma/Documents/workspace-python/QuantSystem/JAQS/jaqs/trade/strategy.py", line 712, in generate_weights_order
sec, price, w))
ValueError: NaN or Inf encountered!
trade_date=20150520, symbol=600832.SH, price=nan, weight=0.0059713192234979486
600832这个股票在20150520退市了,这种情况没有处理么,只要遇到这种情况就会终止运行么?
试了几次都是反的,如下:
Strategy Risk Metrics
Term | Value |
---|---|
Beta | nan |
Maximum Drawdown (%) | 33.09 |
Maximum Drawdown start | 20160215 |
Maximum Drawdown end | 20150422 |
用api.query读取证券基础信息(view="jz.instrumentInfo",),得到的有些信息有误。比如江南嘉捷(601313)在2018年2月26日被三六零(601360)借壳,但是江南嘉捷的退市日期(delist_date)还是99999999,这是不对的,应该是delist_date=20180226才对。
from jaqs.data.dataservice import RemoteDataService
from jaqs.data.dataview import DataView
import json
ds = RemoteDataService()
with open('./data_config.json', 'r') as f:
data_config = json.load(f)
ds.init_from_config(data_config)
dv = DataView()
secs = '600030.SH,000063.SZ,000001.SZ'
props = {'start_date': 20070406, 'end_date': 20180309, 'symbol': secs,
'fields': 'open,close,high,low,volume,pb,net_assets,eps_basic',
'freq': 1}
dv.init_from_config(props, data_api=ds)
dv.prepare_data()
snap1 = dv.get_snapshot(20170504, symbol='600030.SH,000063.SZ', fields='close,pb')
报错:
In [13]: ---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in ()
----> 1 snap1 = dv.get_snapshot(20170504, symbol='600030.SH,000063.SZ', fields='close,pb')
~/anaconda3/lib/python3.6/site-packages/jaqs-0.6.9.4-py3.6.egg/jaqs/data/dataview.py in get_snapshot(self, snapshot_date, symbol, fields)
1120 # df = self.data_d.T.unstack()
1121 # df = df[snapshot_date].copy()
-> 1122 if snapshot_date not in self._snapshot:
1123 return
1124
AttributeError: 'DataView' object has no attribute '_snapshot'
查了一下,是两天前的改动出的问题。
函数_get_dividend_info()总是会被run()调用,而其实现只是针对股票。如果标的是期货的话,就不行了啊。
def _get_dividend_info(self):
"""
Query dividend information of stocks for use of daily settlement.
"""
if self.ctx.data_api is not None:
symbol_str = ','.join(self.ctx.universe)
df, msg = self.ctx.data_api.query_dividend(symbol_str, start_date=self.start_date, end_date=self.end_date)
df.loc[:, 'shares'] = (df['share_ratio'] + df['share_trans_ratio']) # / 10.0
df.loc[:, 'cash_tax'] = df['cash_tax'] # / 10.0
self.df_dividend = df
else:
# TODO
pass
按示例文档,应该是返回指定标的的持仓(正数为多方,负数为空方)。
测试发现,不论多空,都返回正数。
通过trade_api.query_position()方法查询的持仓情况如下:
position: close_pnl 0
commission 0
cost_price 0
current_size 1
enable_size 1
float_pnl 0
frozen_size 0
holding_pnl 0
init_size 0
pre_size 0
security m1805.DCE
side Short
today_size 1
trading_pnl 0
uncome_size 0
但是通过pm.get_pos()方法,返回1
可以完成JAQS下单,但是成交之后on_trade()方法未触发。
不知道是在这里问是否合适,还是应该在vnpy项目问……
when I try to use Vnpy to achieve promote trade by setting the address as 127.0.0.1:8901,but I found that I could't connect the Vnpy JaqsSerive and the output is login failed and the failed reason is that timeout, dose someone know the reason?
File "C:\Users\meng\Anaconda3\lib\site-packages\numpy\core_internal.py", line 30, in _makenames_list
n = len(obj)
TypeError: object of type 'type' has no len()
是否实盘的时候的数据,必须自己配置 DataCore,默认的 DataService(tushare的那个)是不能实现订阅及回调的?
如果我想实现每分钟查询数据,并产生信号,目前使用 tushare 的那个 DataSerivie 是否可以通过 JAQS 的策略模板实现?还是说必须自己配置一个本地 DataCore?
交易是否可以通过 ctp 直接下单,目前是否已经集成了 ctp 下单的模块?
以下有几个问题,望关注,谢谢!
# /jaqs/data/dataapi/data_api.py
def _convert_quote_ind(self, quote_ind):
"""Convert original quote_ind to a map.
The original quote_ind contains field index instead of field name!
"""
if quote_ind['schema_id'] != self._schema_id:
return None
indicators = quote_ind['indicators']
values = quote_ind['values']
max_index = len(self._schema)
quote = {}
for i in range(len(indicators)):
if indicators[i] < max_index: # 此处应改为小于等于 <=
quote[self._schema_map[indicators[i]]['name']] = values[i]
else:
quote[str(indicators[i])] = values[i]
return quote
接上一个问题, 用quote接口也是获取不到vwap字段的。这个字段在dataserver中好像是被注释掉了,有什么特别的原因吗?(DataCore/dataserver/server/src/main/scala/org/quantos/jads/services/jsq/QueryActor.scala)
另外,行情中也没有包含基金的iopv字段(文档中有写),在dataserver中的行情查询和推送流程中也没有看到iopv。
交易日大于1天,Holding PNL 计算错误,原因应该是Trade数据加载之后顺序出错了
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.