rggplot2tidyquant

Moving averages appear to be calculating from the most recent date backwards using geom_ma


Moving averages appear to be plotting from right to left on my timeseries. Here is my code:

library(Quandl)
library(ggplot2)
#  Get Historical Futures Prices: Crude Oil Futures from Quandl. Contract Code is CL

CME_CL_Data <- Quandl('CHRIS/CME_CL1', start_date = '2021-01-01') 

# Plot the OHLC Barchart of the Crude Oil Futures Historical Prices

ggplot(CME_CL_Data, aes(x = Date, y = Last)) +
  geom_barchart(aes(open = Open, high = High, low = Low, close = Last)) + 
  xlab('') + ylab('Daily Prices') + 
  ggtitle('Future Daily Prices: WTI Crude') + 
  geom_ma(ma_fun = SMA, n=20, linetype = 1, size = .75) + 
  geom_ma(ma_fun = SMA, n=50, color = 'red', size = 1.25) +
  theme_light()

And here is the output chart: Chart of CL with Moving Averages

I can't seem to pinpoint what I am doing to cause this.


Solution

  • Quandl returns data sorted in decreasing date:

    > head(CME_CL_Data)
            Date  Open  High   Low  Last Change Settle Volume
    1 2021-06-28 73.99 74.45 72.62 72.77  -1.14  72.91 351101
    2 2021-06-25 73.32 74.18 72.85 74.00   0.75  74.05 357898
    3 2021-06-24 73.28 73.61 72.32 73.33   0.22  73.30 331826
    4 2021-06-23 72.91 74.25 72.82 73.28   0.23  73.08 422226
    5 2021-06-22 73.41 73.95 72.94 73.09  -0.60  73.06  18977
    6 2021-06-21 71.52 73.96 71.15 73.53   2.02  73.66 113253
      Previous Day Open Interest
    1                     416743
    2                     427257
    3                     426977
    4                     426766
    5                      21423
    6                      59274
    

    Hence, geom_ma is taking moving average in reverse. You need to reorder your data:

    library(Quandl)
    library(ggplot2)
    library(tidyquant)
    #  Get Historical Futures Prices: Crude Oil Futures from Quandl. Contract Code is CL
    
    CME_CL_Data <- Quandl('CHRIS/CME_CL1', start_date = '2021-01-01')
    
    # Reoder data
    CME_CL_Data <- CME_CL_Data[order(CME_CL_Data$Date),]
    
    # Plot the OHLC Barchart of the Crude Oil Futures Historical Prices
    
    ggplot(CME_CL_Data, aes(x = Date, y = Last)) +
      geom_barchart(aes(open = Open, high = High, low = Low, close = Last)) +
      xlab('') + ylab('Daily Prices') + 
      ggtitle('Future Daily Prices: WTI Crude') + 
      geom_ma(ma_fun = SMA, n=20, linetype = 1, size = .75) + 
      geom_ma(ma_fun = SMA, n=50, color = 'red', size = 1.25) +
      theme_light()
    
    

    enter image description here