I simply cannot retrieve data from Interactive Brokers in R Studio using the IBrokers package. TraderWorkstation is open, connected and running in the background and the global API settings should be fine as well.
My aim is to download historical data from Interactive Brokers for a portfolio and calculate the log return differences and then play around with them but it seems that IB is not letting me download them.
# Load necessary packages
library(IBrokers)
library(corpcor)
library(tseries)
library(tidyverse)
# Inputs
lookback_period <- 90 # Time-frame in days
# Input tickers
tickers <- c("AAPL")
# Connect to Interactive Brokers
tws <- twsConnect()
if (is.null(tws)) {
stop("Failed to connect to Interactive Brokers TWS.")
} else {
cat("Connected to Interactive Brokers TWS successfully.n")
}
# Function to retrieve historical data for a ticker
get_ib_stock_data <- function(ticker, con, lookback_period) {
duration <- paste0(lookback_period, " D")
cat("Requesting data for", ticker, "with duration:", duration, "n")
# Request historical data
data <- tryCatch({
reqHistoricalData(
con, # A tws connection object
Contract = twsEquity(ticker),
#endDateTime = format(Sys.time(), "%Y%m%d %H:%M:%S"),
duration = "1 D",
barSize = "1 day", # Bar size to retrieve
whatToShow = "TRADES", # Type of data to be extracted (TRADES, MIDPOINT, BID, ASK, BID_ASK)
useRTH = 1 # Limited to regular trading hours
)
}, error = function(e) {
warning("Error retrieving data for ticker: ", ticker, "n", e)
return(NULL)
})
# Check if data is retrieved successfully
if (is.null(data) || nrow(data) == 0 || !("close" %in% colnames(data))) {
warning("Failed to retrieve valid data for ticker: ", ticker)
return(NULL)
}
# Convert the data to a data frame
df <- data.frame(date = as.Date(index(data)), close = coredata(data)[, "close"])
return(df)
}
# Function to calculate log returns
calculate_log_returns <- function(data) {
data$close <- as.numeric(data$close)
# Handle missing values
cat("Number of missing values in 'close' column:", sum(is.na(data$close)), "n")
data <- na.omit(data)
# Ensure there are enough rows after removing NAs
if (nrow(data) < 2) {
warning("Not enough data after removing NAs for ticker with data: ", head(data))
return(NULL)
}
return(diff(log(data$close), 1))
}
# Get historical data for each ticker
stock_data_list <- lapply(tickers, get_ib_stock_data, con = tws, lookback_period = lookback_period)
# Print results
print(stock_data_list)
# Disconnect from TWS
twsDisconnect(tws)
Every time it returns:
Warning message:
In FUN(X[[i]], …) : Failed to retrieve valid data for ticker: AAPL
Print results
print(stock_data_list)
[[1]]
NULL
Mathematica123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.