0

I have two list of dates I would like to apply to my code ( first date in xx and first date in yy, then second date in xx and second date in yy, etc). (I have a short list of dates for the example). trade1 is empty so I am approaching this wrong.

xx= c('2018-06-28','2018-07-27')
yy= c('2018-07-12','2018-08-13')

for (xx in seq_along(yy)) 
{
entry_trades = filter(aa2, Date == xx )%>%
          rename(entry_price = Price, entry_date = Date)
exit_trades = filter(aa2, Date == yy)%>%
         rename(exit_price = Price, exit_date = Date)
trade1 = merge(entry_trades, exit_trades,by='ticker')
trade1 = mutate(trade1, Chg = exit_price - entry_price,
            Chg_pct = round((Chg / entry_price)*100 ,1))%>%
arrange(desc(Chg_pct))
}
  • Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Oct 26 '18 at 04:42
  • 1
    You have a vector of dates `xx`, but then you call your loop variable `xx` - now `xx` is just a number like 1 or 2 and you aren't accessing your original date vector at all within the loop. Use a different name for the loop variable. – Marius Oct 26 '18 at 04:51

1 Answers1

0
for (i in seq_along(yy)) 
{
entry_trades = filter(aa2, Date == xx[i] )%>%
          rename(entry_price = Price, entry_date = Date)
exit_trades = filter(aa2, Date == yy[i])%>%
         rename(exit_price = Price, exit_date = Date)
trade1 = merge(entry_trades, exit_trades,by='ticker')
trade1 = mutate(trade1, Chg = exit_price - entry_price,
            Chg_pct = round((Chg / entry_price)*100 ,1))%>%
arrange(desc(Chg_pct))
}

There's probably a better way of doing whatever you're trying to do, but I'm not sure what that is, and you didn't give us aa2 so it's kind of hard to figure it out

iod
  • 7,412
  • 2
  • 17
  • 36