请求将R语言中AlphaVantage获取标普100股票代码改为循环实现
Hey there, repetitive code is the worst—let's clean this up with a loop that handles all your S&P100 symbols efficiently, while respecting AlphaVantage's API rate limits. Here's how to do it:
Step 1: Prepare your S&P100 symbols list
First, create a vector with all the S&P100 tickers. I've included your existing symbols as an example; you can replace this with the full list of S&P100 codes (you can grab the full list from financial data sites or Wikipedia if you don't have it already).
Step 2: Loop through symbols and fetch data
This loop will iterate over each ticker, pull the daily data, add a column to track which stock it is, store everything in a list, and pause between calls to avoid hitting AlphaVantage's API limits.
library(alphavantager) av_api_key("YOUR_API_KEY") # Replace with your actual API key # Define your full list of S&P100 symbols sp100_symbols <- c("AAPL", "ABBV", "ABT", "ACN", "AGN", "AIG", "ALL") # Initialize an empty list to store each stock's data stock_data <- list() # Loop through each symbol for (ticker in sp100_symbols) { # Fetch the daily time series data daily_data <- av_get( av_fun = "TIME_SERIES_DAILY", symbol = ticker, outputsize = "full" ) # Add a column to identify the stock ticker (critical for merging later) daily_data$ticker <- ticker # Store the data in our list stock_data[[ticker]] <- daily_data # Pause for 20 seconds between calls to comply with AlphaVantage's rate limits Sys.sleep(20) } # Combine all individual stock data frames into one big data frame all_sp100_prices <- do.call(rbind, stock_data)
Key improvements over your original code:
- No repetition: You only need to update the
sp100_symbolsvector if you add/remove stocks, instead of writing a new line for each ticker. - Trackable data: The
tickercolumn ensures you can always tell which stock each row of data belongs to when you combine everything. - Rate limiting compliance: The
Sys.sleep(20)ensures you don't exceed AlphaVantage's call limits (free tier typically allows 5 calls per minute, so 20 seconds between calls keeps you safe).
Optional: Use purrr for a more concise approach
If you're comfortable with the tidyverse, you can use purrr::map instead of a for loop for a cleaner look:
library(tidyverse) library(alphavantager) av_api_key("YOUR_API_KEY") sp100_symbols <- c("AAPL", "ABBV", "ABT", "ACN", "AGN", "AIG", "ALL") all_sp100_prices <- sp100_symbols %>% map(function(ticker) { av_get(av_fun = "TIME_SERIES_DAILY", symbol = ticker, outputsize = "full") %>% mutate(ticker = ticker) Sys.sleep(20) # Keep the delay to respect rate limits }) %>% bind_rows()
内容的提问来源于stack exchange,提问作者Emil Elholm

