I am facing a problem with the amount of time my code takes to run. I have a data frame that gives me buying and selling moments of different stocks and I want to create a new data frame with my holdings. Below there is a reproducible example:
AAPL <- c(0,1,0,0,0,-1,0,0,0,1)
MSFT <- c(0,1,-1,0,0,1,0,0,0,-1)
buy <- data.frame (AAPL,MSFT)
Where 1 indicates it is a buy and -1 that it is a sell.
What I would like is between the 1 and -1 to replace the 0 by 1 to signal that I hold the stock.
I have done it in the following way
for (i in 1:10){
for (j in 1:2) {
buy [i,j] <- ifelse (buy[i,j]==1,1,ifelse(buy[i,j]==-1,0,ifelse(buy[i,j]==0,ifelse(sum(buy[1:(i-1),j])==0,0,1),0)))
}
}
Is there an easier way to achieve this? Because as is, in a big data frame, it is taking almost a day to run.
Thank you in advance for your help.
Aucun commentaire:
Enregistrer un commentaire