Get startedGet started for free

Adding an indicator to a chart.Posn() chart

One of the more interesting things you can do with the chart.Posn() function is to superimpose indicators on top of it. This can help show what the strategy has actually been doing and why. However, in order to do this, you will need to recalculate the indicators outside the scope of your strategy. Once this is done, you simply add them to the chart.Posn plot.

In this exercise, you will add the three indicators from your strategy to the chart.Posn plot you just created. The two moving averages (SMA50 and SMA200) will be superimposed on the price series, while the DVO_2_126 will have its own window.

This exercise is part of the course

Financial Trading in R

View Course

Exercise instructions

  • Begin by reproducing your SMA50, SMA200, and DVO_2_126 indicators for SPY outside of the strategy.
  • Recreate the chart from the previous exercise using chart.Posn().
  • Use add_TA() to overlay the SMA50 as a blue line on top of the price plot.
  • Use add_TA() to overlay the SMA200 as a red line on top of the price plot.
  • Use add_TA() to add the DVO_2_126 to your plot as a new window.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Compute the SMA50
sma50 <- SMA(x = Cl(__), n = ___)

# Compute the SMA200
sma200 <- SMA(x = Cl(___), n = ___)

# Compute the DVO_2_126 with an navg of 2 and a percentlookback of 126
DVO_2_126 <- DVO(HLC = HLC(___), navg = ___, percentlookback = ___)

# Recreate the chart.Posn of the strategy from the previous exercise
chart.Posn(Portfolio = portfolio.st, Symbol = "___")

# Overlay the SMA50 on your plot as a blue line
add_TA(sma50, on = ___, col = "___")

# Overlay the SMA200 on your plot as a red line
add_TA(sma200, on = ___, col = "___")

# Add the DVO_2_126 to the plot in a new window
add_TA(___)
Edit and Run Code