Qncy
Qncy

Reputation: 57

Createa loop for new values in new df in R

I have a df with 1500 obs. and 100 variables. These are shares and I would like to calculate the EMA50 for all 100 shares and have them in a new df. I would like to put this in a loop, because I want to plot each share + result after that. But the plot is not important for now. To show the whole process better I have made an example: (Probably there is an easier way to code this example, but I am in the middle of my studies and still learning to code in R.)

library(tidyverse)
library(quantmod)
library(fPortfolio)
library(PerformanceAnalytics)
#
DStart <-  "2016-01-01" 
DEnd <-  "2020-12-31" 
#
#loading DAX and MDAX Index data from Yahoo Finance
TSLA <-  getSymbols("TSLA", src="yahoo", from=DStart, to=DEnd,  auto.assign=FALSE) 
AAPL <- getSymbols("AAPL", src="yahoo", from=DStart, to=DEnd,  auto.assign=FALSE)
AMZN <- getSymbols("AMZN", src="yahoo", from=DStart, to=DEnd,  auto.assign=FALSE)
#
Closing <- merge(TSLA, AAPL, AMZN)
#
write.zoo(Closing, file="Closing.csv", sep=",", dec="." )
#
df_Closing <- Closing[,-c(1,2,3,5,6,7,8,9,11,12,13,14,15,17,18)]

I now have all closing prices in a df like in my real df. For the individual calculation of the EMA I use:

df_Closing$TSLA_EMA50 = EMA(df_Closing$TSLA.Close,50)

During my search I came across several solutions, which all ended in error messages until now. My last attempt looked like this:

df_EMA50 <- df_Closing
for (i in names(df_Closing)) {
  j <- EMA(df_Closing$i,50)
  new_df[i] <- j$EMA50
}

Upvotes: 1

Views: 59

Answers (1)

manotheshark
manotheshark

Reputation: 4357

It's typically easier to iterate by position instead of by name. The output data.frame should be initialized empty to make it easier to identify problems and ensure expected output.

df_EMA50 <- df_Closing[0, ]
for (i in seq_len(ncol(df_Closing))) {
  j <- EMA(df_Closing[, i], 50)
  colnames(j) <- colnames(df_Closing[, i])
  df_EMA50 <- cbind(df_EMA50, j)
}

Upvotes: 1

Related Questions