@elda.osinski
You may also consider using the tidyverse package in R to streamline the process of data manipulation. Here is an updated version of the steps using the tidyverse:
- Install and load the necessary packages:
1
2
3
|
install.packages(c("quantmod", "tidyverse"))
library(quantmod)
library(tidyverse)
|
- Set the start and end dates for your desired time period of stock data:
1
2
|
start_date <- "2022-01-01"
end_date <- "2022-12-31"
|
- Define the ticker symbol of the stock you want to gather data for:
- Use the getSymbols function from the quantmod package to download the stock data:
1
|
getSymbols(stock_symbol, from = start_date, to = end_date)
|
- Extract the closing prices from the stock data and create a data frame:
1
|
stock_data <- data.frame(date = index(get(stock_symbol)), price = Cl(get(stock_symbol)))
|
- Calculate the daily returns by taking the percentage change in closing prices and add it to the data frame:
1
2
|
stock_data <- stock_data %>%
mutate(daily_return = Delt(price, k = 1, type = "arithmetic"))
|
- Remove any NA values from the dataset:
1
2
|
stock_data <- stock_data %>%
drop_na()
|
- Optionally, save the stock returns dataset to a CSV file:
1
|
write_csv(stock_data, file = "stock_returns.csv")
|
This code snippet utilizes the tidyverse package for data manipulation and offers a more modern and streamlined approach. You can further customize and analyze the stock returns data as per your requirements using the tidyverse functions.