From wide to long dataset

Hi, I have downloaded from Yahoo finance some prices of stocks. Now I want to output them in a table. But with me the data are always under each other. Could somebody help me with my code that each stock is separated in each column.

Here is my code:


library(tidyquant)
library(timetk)
library(ggplot2)
library(tibble)
library(select)
library(dplyr)
library(corrplot)
library(tidyr)
library(DT)

# Setting our stock symbols to a variable

tickers <- c("FB", "AMZN", "AAPL", "NFLX", "GOOG")


# Dowload the stock price data

multpl_stocks <- tq_get(tickers,
                        from = "2013-01-01",
                        to = "2018-03-01",
                        get = "stock.prices")

multpl_stocks %>%
ggplot(aes(x = date, y = adjusted, color = symbol)) +
geom_line() +
ggtitle("Price chart for multiple stocks")

multpl_stocks %>%
ggplot(aes(x = date, y = adjusted)) +
geom_line() +
facet_wrap(~symbol, scales = "free_y") + # facet_wrap is used to make diff frames
theme_classic() +       # using a new theme
labs(x = "Date", y = "Price") +
ggtitle("Price chart FAANG stocks")


#Calculating the yearly returns for multiple stocks

multpl_stock_yearly_returns <- multpl_stocks %>%
group_by(symbol) %>%                             # We are grouping the stocks by symbol
tq_transmute(select = adjusted,
               mutate_fun = periodReturn,
               period = 'yearly',
               col_rename = 'returns')
             
             
datatable(multpl_stock_yearly_returns)

Use pivot_wider().

multpl_stock_yearly_returns %>% 
  pivot_wider(date, names_from = symbol, values_from = returns)

# A tibble: 6 x 6
  date           FB   AMZN    AAPL    NFLX    GOOG
  <date>      <dbl>  <dbl>   <dbl>   <dbl>   <dbl>
1 2013-12-31 0.952   0.550  0.0475  3.00    0.550 
2 2014-12-31 0.428  -0.222  0.406  -0.0721 -0.0597
3 2015-12-31 0.341   1.18  -0.0301  1.34    0.446 
4 2016-12-30 0.0993  0.109  0.125   0.0824  0.0171
5 2017-12-29 0.534   0.560  0.485   0.551   0.356 
6 2018-02-28 0.0105  0.293  0.0568  0.518   0.0557

Many thanks, it worked.

I think I found another error. Unfortunately, the data are not sorted chronologically (If I enter a longer period). How can I sort them by date?

Unbenannt

Use arrange() function

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.