从Interactive Brokers TWS下载数据

时间:2017-10-21 21:01:29

标签: r api quantmod yahoo-finance interactive-brokers

我一直在玩Interactive Brokers TWS和R,我一直在取得不同的成功。

library(IBrokers)
IBConn <- twsConnect(port = xxxx)
currency_df = twsCurrency("NZD",currency = "USD")
test = reqHistoricalData(IBConn, Contract = currency_df, whatToShow ='BID_ASK', useRTH = "0", barSize = '1 min', duration="1 D", endDateTime = paste0(gsub("-","", reqCurrentTime(IBConn))," EST"))
plot(test$NZD.USD.Close)

library(quantmod)
plot(test$NZD.USD.Close)
chartSeries(test$NZD.USD.Close)
addBBands(n = 20, sd = 2, ma = "SMA", draw = 'bands', on = -1)

效果很好,我可以下载当天的1分钟货币数据。

当我试图获取公司的股票数据时会出现问题

tws = twsConnect(port=7497)
symbol = twsSTK("AAPL")
data_AAPL = reqHistoricalData(tws, symbol)
print (data_AAPL)

但是我得到的结果与此blog reqHistoricalData函数 - 大约在页面的中间位置相同)的结果相同。

我使用以下代码请求的其他数据运行了几个小时,我被迫点击&#34;停止&#34;在R控制台中。

tws <- twsConnect()
aapl.csv <- file("AAPL.csv", open="w")

# run an infinite-loop ( <C-c> to break )
reqMktData(tws, twsSTK("AAPL"), 
           eventWrapper=eWrapper.MktData.CSV(1), 
           file=aapl.csv)

close(aapl.csv)
close(tws)

我的问题是,如何使用Interactive Brokers R软件包下载AAPL股票(开盘价,最高价,最低价,收盘价)的前一天1或5分钟数据?我可以使用quantmod包收集每日数据,但我想知道我是否可以使用IBrokers软件包以Open High Low和Close格式收集分钟数据。

注意:我使用的是Interactive Brokers演示交易账户。

1 个答案:

答案 0 :(得分:4)

您没有获得与您提到的博客相同的数据的原因是您指的是historical (i.e. reqHistoricalData(tws, symbol)数据,其中博客中的示例指的是market data ( i.e. reqMktData),这是流式传输不同。要获取股票(AAPL)的历史日内数据,您必须定义contract,如下所示:

contract = twsContract(0,"AAPL","STK","SMART","ISLAND", "","0.0","USD","","","",NULL,NULL,"0”)

示例:

library(IBrokers)
IBConn <- twsConnect(port = 7497)
contract = twsContract(0,"AAPL","STK","SMART","ISLAND", "","0.0","USD","","","",NULL,NULL,"0")
data_AAPL = reqHistoricalData(IBConn, contract, whatToShow ='BID_ASK', useRTH = "0", barSize = '1 min', duration="1 D", endDateTime = paste0(gsub("-","", reqCurrentTime(IBConn))))


> head(data_AAPL)
                    AAPL.Open AAPL.High AAPL.Low AAPL.Close
2017-10-23 10:00:00    156.00    157.20   156.00     156.64
2017-10-23 10:01:00    155.99    156.65   155.95     156.64
2017-10-23 10:02:00    155.95    156.65   155.95     156.65
2017-10-23 10:03:00    155.95    156.65   155.95     156.65
2017-10-23 10:04:00    155.95    156.60   155.95     156.60
2017-10-23 10:05:00    155.95    156.62   155.95     156.60
                    AAPL.Volume AAPL.WAP AAPL.hasGaps AAPL.Count
2017-10-23 10:00:00          -1       -1            0         -1
2017-10-23 10:01:00          -1       -1            0         -1
2017-10-23 10:02:00          -1       -1            0         -1
2017-10-23 10:03:00          -1       -1            0         -1
2017-10-23 10:04:00          -1       -1            0         -1
2017-10-23 10:05:00          -1       -1            0         -1

不要忘记关闭与twsDisconnect(IBConn)的连接: - )