Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Get SPY from yahoo
- getSymbols("SPY",
- from ="2000-01-01",
- to ="2016-06-30",
- src ="yahoo",
- adjust = T)
- # Plot the closing price of SPY
- plot(Cl(SPY))
- # Plot the closing prices of SPY
- plot(Cl(SPY))
- # Add a 200-day SMA using lines()
- lines(SMA(Cl(SPY), n = 200), col ="red")
- # Load the quantstrat package
- library(quantstrat)
- # Create initdate, from, and to strings
- initdate <- "1999-01-01"
- from <- "2003-01-01"
- to <- "2015-12-31"
- # Set the timezone to UTC
- Sys.setenv(TZ="UTC")
- # Set the currency to USD
- currency("USD")
- # Load the quantmod package
- library(quantmod)
- # Retrieve SPY from yahoo
- getSymbols("SPY",from = from, to=to, src="yahoo", adjust = T)
- # Use stock() to initialize SPY and set currency to USD
- stock("SPY",currency="USD")
- # Define your trade size and initial equity
- tradesize <- 100000
- initeq <- 100000
- # Define the names of your strategy, portfolio and account
- strategy.st <- "firststrat"
- portfolio.st <- "firststrat"
- account.st <- "firststrat"
- # Remove the existing strategy if it exists
- rm.strat(strategy.st)
- # Initialize the portfolio
- initPortf(portfolio.st, symbols ="SPY", initDate =initdate, currency ="USD")
- # Initialize the account
- initAcct(account.st, portfolios =portfolio.st, initDate =initdate, currency = "USD", initEq =initeq)
- # Initialize the orders
- initOrders(portfolio.st, initDate =initdate)
- # Store the strategy
- strategy(strategy.st, store = T)
- # Create a 200-day SMA
- spy_sma <- SMA(Cl(SPY),200)
- plot.xts(spy_sma)
- # Create an RSI with a 3-day lookback period
- spy_rsi <- RSI(Cl(SPY),3)
- spy_rsi
- # Plot the closing prices of SPY
- plot(Cl(SPY));lines(SMA(Cl(SPY), n =200), col ="red")
- # Plot the closing price of SPY
- plot(Cl(SPY))
- # Plot the RSI 2
- plot(RSI(Cl(SPY),2))
- # Add a 200-day SMA indicator to strategy.st
- add.indicator(strategy = strategy.st,
- # Add the SMA function
- name = "SMA",
- # Create a lookback period
- arguments = list(x = quote(Cl(mktdata)), n = 200),
- label = "SMA200")
- # Add a 50-day SMA indicator to strategy.st
- add.indicator(strategy = strategy.st,
- # Add the SMA function
- name = "SMA",
- # Create a lookback period
- arguments = list(x =quote(Cl(mktdata)), n = 50),
- label = "SMA50")
- plot.xts(Cl(SPY));lines(SMA(Cl(SPY),200),col="red");lines(SMA(Cl(SPY),50),col="blue")
- # Add an RSI 3 indicator to strategy.st
- add.indicator(strategy = strategy.st,
- # Add the RSI 3 function
- name ="RSI",
- # Create a lookback period
- arguments = list(x=quote(Cl(mktdata)),n=3),
- label ="RSI_3")
- plot.xts(Cl(SPY));lines(SMA(Cl(SPY),200))
- plot.xts(RSI(Cl(SPY),200));lines(SMA(RSI(Cl(SPY),200),50),col="red")
- # Declare the DVO function
- DVO <- function(HLC, navg =2, percentlookback =126) {
- # Compute the ratio between closing prices to the average of high and low
- ratio <- Cl(HLC)/((Hi(HLC) + Lo(HLC))/2)
- # Smooth out the ratio outputs using a moving average
- avgratio <- SMA(ratio, n =navg)
- # Convert ratio into a 0-100 value
- out <- runPercentRank(avgratio, n = percentlookback, exact.multiplier = 1) * 100
- colnames(out) <- "DVO"
- return(out)
- }
- # Add the DVO indicator to the strategy
- add.indicator(strategy = strategy.st, name = "DVO",
- arguments = list(HLC = quote(HLC(mktdata)), navg =2, percentlookback =126),
- label = "DVO_2_126")
- # Use applyIndicators to test indicators
- test <- applyIndicators(strategy =strategy.st, mktdata = OHLC(SPY))
- head(test)
- # Subset data between Sep. 1 and Sep. 5 of 2013
- test_subset <- test["2013-09-1/2013-09-5"]
- plot.xts(Cl(SPY));lines(test)
- plot.xts(test)
- plot.xts(test_subset)
- # A sigComparison which specifies that SMA50 must be greater than SMA200
- add.signal(strategy.st, name = "sigComparison",
- # I'm are interested in the relationship between the SMA50 and the SMA200
- arguments = list(columns = c("SMA50", "SMA200"),
- # Particularly, I'm are interested when the SMA50 is greater than the SMA200
- relationship = "gt"),
- label = "longfilter")
- # Add a sigCrossover which specifies that the SMA50 is less than the SMA200
- add.signal(strategy.st, name = "sigCrossover",
- # We're interested in the relationship between the SMA50 and the SMA200
- arguments = list(columns = c("SMA50", "SMA200"),
- # The relationship is that the SMA50 crosses under the SMA200
- relationship = "lt"),
- label = "filterexit")
- # Implement a sigThreshold which specifies that DVO_2_126 must be less than 2
- add.signal(strategy.st, name = "sigThreshold",
- # Use the DVO_2_126 column
- arguments = list(column = "DVO_2_126",
- # The threshold is 20
- threshold =20,
- # I want the oscillator to be under this value
- relationship = "lt",
- # I'm interested in every instance that the oscillator is less than 20
- cross =F),
- label = "longthreshold")
- # A sigThreshold signal that specifies that DVO_2_126 must cross above 80
- add.signal(strategy.st, name = "sigThreshold",
- # Reference the column of DVO_2_126
- arguments = list(column = "DVO_2_126",
- # Set a threshold of 80
- threshold =80,
- # The oscillator must be greater than 80
- relationship = "gt",
- # We are interested only in the cross
- cross =TRUE),
- label = "thresholdexit")
- # Create dataset: test
- test_init <- applyIndicators(strategy.st, mktdata = OHLC(SPY))
- test <- applySignals(strategy = strategy.st, mktdata =test_init)
- # Add a sigFormula signal
- add.signal(strategy.st, name = "sigFormula",
- arguments = list(formula = "longfilter & longthreshold",
- cross = T),
- label = "longentry")
- add.rule(strategy.st, name = "ruleSignal",
- arguments = list(sigcol = "filterexit", sigval = TRUE, orderqty = "all",
- ordertype = "market", orderside = "long",
- replace = FALSE, prefer = "Open"),
- type = "exit")
- add.rule(strategy.st, name = "ruleSignal",
- arguments = list(sigcol = "thresholdexit", sigval = TRUE, orderqty = "all",
- ordertype = "market", orderside = "long",
- replace = FALSE, prefer = "Open"),
- type = "exit")
- # Create an entry rule of 1 share when all conditions line up to enter into a position
- add.rule(strategy.st, name = "ruleSignal",
- arguments=list(sigcol = "longentry",
- sigval =T,
- orderqty =1,
- ordertype = "market",
- orderside = "long",
- replace =F,
- prefer = "Open"),
- type = "enter")
- # Add a rule that uses an osFUN to size an entry position
- add.rule(strategy = strategy.st, name = "ruleSignal",
- arguments = list(sigcol = "longentry", sigval = TRUE, ordertype = "market", orderside = "long", replace = FALSE, prefer = "Open",
- # Use the osFUN called osMaxDollar
- osFUN =osMaxDollar,
- # The tradeSize argument should be equal to tradesize (defined earlier)
- tradeSize =tradesize,
- # The maxSize argument should be equal to tradesize as well
- maxSize =tradesize),
- type = "enter")
- # Use applyStrategy() to apply the strategy.
- end <- applyStrategy(strategy =strategy.st, portfolios =portfolio.st)
- # Update your portfolio (portfolio.st)
- updatePortf(portfolio.st)
- daterange <- time(getPortfolio(portfolio.st)$summary)[-1]
- # Update your account (account.st)
- updateAcct(account.st, daterange)
- updateEndEq(account.st)
- tradeStats(portfolio.st)
- # Use chart.Posn to view system's performance on SPY
- chart.Posn(Portfolio =portfolio.st, Symbol = "SPY")
- # Compute the SMA50
- sma50 <- SMA(x = Cl(SPY), n =50)
- # Compute the SMA200
- sma200 <- SMA(x = Cl(SPY), n =200)
- # Compute the DVO_2_126 with an navg of 2 and a percentlookback of 126
- dvo <- DVO(HLC = HLC(SPY), navg =2, percentlookback =126)
- # Recreate the chart.Posn of the strategy from the previous exercise
- chart.Posn(Portfolio=portfolio.st,Symbol="SPY")
- # Overlay the SMA50 on your plot as a blue line
- add_TA(sma50, on =1, col = "blue")
- # Overlay the SMA200 on your plot as a red line
- add_TA(sma200, on =1, col = "red")
- # Add the DVO_2_126 to the plot in a new window
- add_TA(dvo,2)
- # Get instrument returns
- instrets <- PortfReturns(account.st)
- # Compute Sharpe ratio from returns
- SharpeRatio.annualized(instrets, geometric = FALSE)
Add Comment
Please, Sign In to add comment