Truedata的官方Python包
truedata-ws的Python项目详细描述
这是TrueData的官方python(websocket)repo
到目前为止我们已经讨论了什么?
- Websocket API
- 实时数据
- 历史数据
如何使用它?
适合初学者
- 从PyPi安装
python3.7 -m pip install truedata_ws
- 运行测试以确保一切正常
- 连接
fromtruedata_ws.websocket.TDimportTDtd_obj=TD('<enter_your_login_id>','<enter_your_password>')
- 使用可选的broker_token参数连接
Truedata还与经纪人合作,为客户提供最佳的交易体验。
如果您是使用此服务的客户,请确保在登录他们的服务后也提供代理令牌
td_obj=TD('<enter_your_login_id>','<enter_your_password>',broker_token='<enter_broker_token>')
- 启动实时数据
对于单个符号
req_ids=td_obj.start_live_data(['<enter_symbol>'])# Example:# req_id = start_live_data(['CRUDEOIL-I'])# This returns an single element list that can be used later to reference the data
对于多个符号
在
req_ids=td_obj.start_live_data(['<symbol_1>','<symbol_2>','<symbol_3>',...])# Example:# req_ids = td_obj.start_live_data(['CRUDEOIL-I', 'BANKNIFTY-I', 'RELIANCE', 'ITC'])# This returns a list that can be used to reference data later
- 访问接触线数据
importtimetime.sleep(1)forreq_idinreq_ids:print(td_obj.touchline_data[req_id])# You MAY have to wait until for 1 sec for all of the touchline data to populate
- 测试市场数据的示例代码
fromcopyimportdeepcopylive_data_objs={}forreq_idinreq_ids:live_data_objs[req_id]=deepcopy(td_obj.live_data[req_id])whileTrue:forreq_idinreq_ids:iflive_data_objs[req_id]!=td_obj.live_data[req_id]:print(td_obj.live_data[req_id])live_data_objs[req_id]=deepcopy(td_obj.live_data[req_id])
- 停止实时数据
td_obj.stop_live_data(['<symbol_1>','<symbol_2>','<symbol_3>',...])
您也可以提供自己的req_id列表(但是,它们的长度必须与符号的数量相同)。。。
或者,您可以提供单个req_id作为整数,我们将通过对提供的每个符号递增来返回一个列表。。。
- 获取历史数据
不使用参数
hist_data_1=td_obj.get_historic_data('BANKNIFTY-I')# This returns 1 minute bars from the start of the present day until current time
使用给定的结束时间
fromdatetimeimportdatetimehist_data_2=td_obj.get_historic_data('BANKNIFTY-I',end_time=datetime(2020,5,5,12,30))# Any time can be given here
使用给定的持续时间(有关可用的持续时间选项,请阅读“限制”部分)
hist_data_3=td_obj.get_historic_data('BANKNIFTY-I',duration='3 D')
使用指定的条形图大小(有关可用的条形图大小选项,请阅读“限制”部分)
hist_data_4=td_obj.get_historic_data('BANKNIFTY-I',bar_size='30 mins')
使用开始时间而不是持续时间
fromdateutil.relativedeltaimportrelativedeltahist_data_5=td_obj.get_historic_data('BANKNIFTY-I',start_time=datetime.now()-relativedelta(days=3))
重要提示: 既然我们已经介绍了基本参数,您可以随意混合和匹配参数。。。如果未指定参数,默认值如下
end_time=datetime.now()duration="1 D"bar_size="1 min"
搭配搭配
hist_data_6=td_obj.get_historic_data('BANKNIFTY-I',duration='3 D',bar_size='15 mins')
附带说明:您可以用一行代码将历史数据转换为Pandas数据帧
importpandasaspddf=pd.DataFrame(hist_data_1)
- 断开与服务的连接
td_obj.disconnect()
- 历史数据的限制和注意事项
- 如果同时提供持续时间和开始时间,则将使用持续时间,并且忽略开始时间。。。在
- 如果既没有提供持续时间也没有提供开始时间,则将使用duration=“1 D”
- 在
只有以下规格的酒吧可用
- 滴答声
- 1分钟
- 5分钟
- 15分钟
- 30分钟
- 爆炸物排放
- 在
以下注释可用于持续时间
- D=天
- W=周
- M=月
- Y=年
示例代码
fromtruedata_ws.websocket.TDimportTDfromcopyimportdeepcopyfromtimeimportsleepimportpandasaspdfromdatetimeimportdatetimefromdateutil.relativedeltaimportrelativedeltafromcoloramaimportStyle,Foreusername='<enter_your_username>'password='<enter_your_password>'broker_token='<enter_your_broker>'symbols=['<symbol_1>','<symbol_2>','<symbol_3>',...]# ------- In this sample, we use the first of the above given symbols for historical datasymbol=symbols[0]test_time=datetime.today()td_obj=TD(username,password,broker_token=broker_token)# ------- Beginning historical data test...hist_data_1=td_obj.get_historic_data(f'{symbol}')hist_data_2=td_obj.get_historic_data(f'{symbol}',duration='3 D')hist_data_3=td_obj.get_historic_data(f'{symbol}',duration='3 D',bar_size='15 mins')hist_data_4=td_obj.get_historic_data(f'{symbol}',bar_size='30 mins')hist_data_5=td_obj.get_historic_data(f'{symbol}',bar_size='30 mins',start_time=test_time-relativedelta(days=3))hist_data_6=td_obj.get_historic_data(f'{symbol}',bar_size='EOD',duration='1 M')# Testing tick historical datatick_hist_data_1=td_obj.get_historic_data(f'{symbol}',bar_size='tick')tick_hist_data_2=td_obj.get_historic_data(f'{symbol}',bar_size='tick',duration='3 D')tick_hist_data_3=td_obj.get_historic_data(f'{symbol}',bar_size='tick',start_time=test_time-relativedelta(days=3))# Printing out the resultsprint(f'{Style.BRIGHT}{Fore.BLUE}------------- HIST BAR DATA TEST RESULTS -------------{Style.RESET_ALL}')print()print(f"{Style.BRIGHT}{Fore.BLUE}HISTDATA 1...\n"f"\tCommand used -> hist_data_1 = td_app.get_historic_data('{symbol}')\n"f"\tLENGTH OF RESULT = {len(hist_data_1)}{Style.RESET_ALL}")forhist_pointinhist_data_1[-20:]:print(hist_point)print()print(f"{Style.BRIGHT}{Fore.BLUE}HISTDATA 2...\n"f"\tCommand used -> hist_data_2 = td_app.get_historic_data('{symbol}', duration='3 D')\n"f"\tLENGTH OF RESULT = {len(hist_data_2)}{Style.RESET_ALL}")forhist_pointinhist_data_2[-20:]:print(hist_point)print()print(f"{Style.BRIGHT}{Fore.BLUE}HISTDATA 3...\n"f"\tCommand used -> hist_data_3 = td_app.get_historic_data('{symbol}', duration='3 D', bar_size='15 mins')\n"f"\tLENGTH OF RESULT = {len(hist_data_3)}{Style.RESET_ALL}")forhist_pointinhist_data_3[-20:]:print(hist_point)print()print(f"{Style.BRIGHT}{Fore.BLUE}HISTDATA 4...\n"f"\tCommand used -> hist_data_4 = td_app.get_historic_data('{symbol}', bar_size='30 mins')\n"f"\tLENGTH OF RESULT = {len(hist_data_4)}{Style.RESET_ALL}")forhist_pointinhist_data_4[-20:]:print(hist_point)print()print(f"{Style.BRIGHT}{Fore.BLUE}HISTDATA 5...\n"f"\tCommand used -> hist_data_5 = td_app.get_historic_data('{symbol}', bar_size='30 mins', start_time=datetime({(test_time-relativedelta(days=3)).strftime('%Y, %m, %d, %H, %M, %S').replace(' 0',' ')}))\n"f"\tLENGTH OF RESULT = {len(hist_data_5)}{Style.RESET_ALL}")forhist_pointinhist_data_5[-20:]:print(hist_point)print()print(f"{Style.BRIGHT}{Fore.BLUE}HISTDATA 6...\n"f"\tCommand used -> hist_data_6 = td_obj.get_historic_data(f'{symbol}', bar_size='EOD', duration='1 M'))\n"f"\tLENGTH OF RESULT = {len(hist_data_6)}{Style.RESET_ALL}")forhist_pointinhist_data_6[-20:]:print(hist_point)print()print()print(f'{Style.BRIGHT}{Fore.BLUE}------------- HIST TICK DATA TEST RESULTS -------------{Style.RESET_ALL}')print()print(f"{Style.BRIGHT}{Fore.BLUE}TICKDATA 1...\n"f"\tCommand used -> tick_data_1 = td_app.get_historic_data('{symbol}', bar_size='tick')\n"f"\tLENGTH OF RESULT = {len(tick_hist_data_1)}{Style.RESET_ALL}")forhist_pointintick_hist_data_1[-20:]:print(hist_point)print()print(f"{Style.BRIGHT}{Fore.BLUE}TICKDATA 2...\n"f"\tCommand used -> tick_data_2 = td_app.get_historic_data('{symbol}', bar_size='tick', duration='3 D')\n"f"\tLENGTH OF RESULT = {len(tick_hist_data_2)}{Style.RESET_ALL}")forhist_pointintick_hist_data_2[-20:]:print(hist_point)print()print(f"{Style.BRIGHT}{Fore.BLUE}TICKDATA 3...\n"f"\tCommand used -> tick_data_3 = td_app.get_historic_data('{symbol}', bar_size='tick', start_time=datetime({(test_time-relativedelta(days=3)).strftime('%Y, %m, %d, %H, %M, %S').replace(' 0',' ')}))\n"f"\tLENGTH OF RESULT = {len(tick_hist_data_3)}{Style.RESET_ALL}")forhist_pointintick_hist_data_3[-20:]:print(hist_point)# Testing conversion to pandas dataframeprint(f'{Style.BRIGHT}{Fore.BLUE}Converting HISTDATA 1 to a Pandas DataFrame{Style.RESET_ALL}')print(f'Command used -> df = pd.DataFrame(hist_data_1)')df=pd.DataFrame(hist_data_1)print(df)print(f'{Style.BRIGHT}{Fore.BLUE}Converting TICKDATA 1 to a Pandas DataFrame{Style.RESET_ALL}')print(f'Command used -> df = pd.DataFrame(tick_hist_data_1)')df=pd.DataFrame(tick_hist_data_1)print(df)# ------- Beginning live data test...req_ids=td_obj.start_live_data(symbols)sleep(3)# This is here just to give the touchline data some time to populate... (Generally takes less than 1 sec)print(f"{Style.BRIGHT}{Fore.BLUE}Here's the touchline data...{Style.RESET_ALL}")forreq_idinreq_ids:print(td_obj.touchline_data[req_id])print()print(f"{Style.BRIGHT}{Fore.BLUE}Here's the LIVE stream... Use Ctrl+C to stop and exit...{Style.RESET_ALL}")sleep(2)# This is here just to give the user time to read the instructions...live_data_objs={}forreq_idinreq_ids:live_data_objs[req_id]=deepcopy(td_obj.live_data[req_id])whileTrue:try:forreq_idinreq_ids:iflive_data_objs[req_id]!=td_obj.live_data[req_id]:print(td_obj.live_data[req_id])live_data_objs[req_id]=deepcopy(td_obj.live_data[req_id])exceptKeyboardInterrupt:td_obj.stop_live_data(symbols)td_obj.disconnect()exit()
发行说明
第0.3.11版
- 在
td_obj.get_historic_data()
函数中将query_time
重构为end_time
。在 - 将
truedata_id
重构为td_obj.touchline_data
对象中的symbol_id
。在 - 添加了
td_obj.get_touchline()
作为实验特征函数。在 - 初始化时填充
td_obj.live_data
对象中缺少的值。在 - 为错误报告添加了更好的调试信息。在
- 清理了代码库。在
是的,我们意识到自述文件.md我们正在积极清理源代码,并在github上发布wiki页面。
:天
- 项目
标签: