This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.

How To Get Historical S&P 500 Constituents Data For Free

Robot Wealth

Contributor:
Robot Wealth
Visit: Robot Wealth

Excerpt

Getting Current S&P 500 Constituents for Free

Wikipedia publishes current S&P 500 component stocks here.

If we use the chrome inspector we can see that the S&P 500 stock constituents are in an HTML table with id #constituents

So let’s use the rvest R package to scrape that data into a data frame.

# Load dependencies
if (!require(“pacman”)) install.packages(“pacman”)
pacman::p_load(tidyverse, rvest)
wikispx <- read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
currentconstituents <- wikispx %>%
html_node(‘#constituents’) %>%
html_table(header = TRUE)
currentconstituents

How To Get Historical S&P 500 Constituents Data For Free

Getting S&P 500 Changes for Free

Wikipedia also publishes “Selected Changes to the list of S&P 500 components” on the same page.

This lists stocks that have been added or removed from the index as a result of acquisitions, or as the companies grow and shrink in market capitalisation.

I’ve checked this against our data set and it’s relatively accurate and complete up to about the year 2000. It gets less complete and accurate before then.

But we don’t need perfection here… so let’s scrape these changes.

The Chrome Inspector shows us they live in a table with id #changes.

spxchanges <- wikispx %>%
html_node(‘#changes’) %>%
html_table(header = FALSE, fill = TRUE) %>%
filter(row_number() > 2) %>% # First two rows are headers
`colnames<-`(c('Date','AddTicker','AddName','RemovedTicker','RemovedName','Reason')) %>%
mutate(Date = as.Date(Date, format = ‘%B %d, %Y’),
year = year(Date),
month = month(Date))
spxchanges

Create Monthly Snapshot of S&P 500 Index Constituents

Now we’re going to use this data to create monthly snapshots of what the SPX index used to look like.

To do this we:

  • start at the current S&P 500 index constituents
  • iterate backwards a month at a time and:
    • add back the stocks that were removed
    • remove the stocks that were added

If that sounds back to front, it’s because we are working backwards in time through the data!

# Start at the current constituents…
currentmonth <- as.Date(format(Sys.Date(), '%Y-%m-01'))
monthseq <- seq.Date(as.Date('1990-01-01'), currentmonth, by = 'month') %>% rev()

spxstocks <- currentconstituents %>% mutate(Date = currentmonth) %>% select(Date, Ticker = Symbol, Name = Security)
lastrunstocks <- spxstocks

# Iterate through months, working backwards
for (i in 2:length(monthseq)) {
d <- monthseq[i]
y <- year(d)
m <- month(d)
changes <- spxchanges %>%
filter(year == year(d), month == month(d))

# Remove added tickers (we’re working backwards in time, remember)
tickerstokeep <- lastrunstocks %>%
anti_join(changes, by = c(‘Ticker’ = ‘AddTicker’)) %>%
mutate(Date = d)

# Add back the removed tickers…
tickerstoadd <- changes %>%
filter(!RemovedTicker == ”) %>%
transmute(Date = d,
Ticker = RemovedTicker,
Name = RemovedName)

thismonth <- tickerstokeep %>% bind_rows(tickerstoadd)
spxstocks <- spxstocks %>% bind_rows(thismonth)

lastrunstocks <- thismonth
}
spxstocks

Visit RobotWealth to read the full article and download the code:
https://robotwealth.com/how-to-get-historical-spx-constituents-data-for-free/

Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from Robot Wealth and is being posted with permission from Robot Wealth. The views expressed in this material are solely those of the author and/or Robot Wealth and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

trading top