Guest User

Untitled

a guest
Jun 18th, 2018
1,227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.03 KB | None | 0 0
  1. # Get SPY from yahoo
  2. getSymbols("SPY",
  3. from ="2000-01-01",
  4. to ="2016-06-30",
  5. src ="yahoo",
  6. adjust = T)
  7. # Plot the closing price of SPY
  8. plot(Cl(SPY))
  9.  
  10. # Plot the closing prices of SPY
  11. plot(Cl(SPY))
  12. # Add a 200-day SMA using lines()
  13. lines(SMA(Cl(SPY), n = 200), col ="red")
  14.  
  15. # Load the quantstrat package
  16. library(quantstrat)
  17. # Create initdate, from, and to strings
  18. initdate <- "1999-01-01"
  19. from <- "2003-01-01"
  20. to <- "2015-12-31"
  21. # Set the timezone to UTC
  22. Sys.setenv(TZ="UTC")
  23. # Set the currency to USD
  24. currency("USD")
  25.  
  26. # Load the quantmod package
  27. library(quantmod)
  28. # Retrieve SPY from yahoo
  29. getSymbols("SPY",from = from, to=to, src="yahoo", adjust = T)
  30. # Use stock() to initialize SPY and set currency to USD
  31. stock("SPY",currency="USD")
  32.  
  33. # Define your trade size and initial equity
  34. tradesize <- 100000
  35. initeq <- 100000
  36. # Define the names of your strategy, portfolio and account
  37. strategy.st <- "firststrat"
  38. portfolio.st <- "firststrat"
  39. account.st <- "firststrat"
  40. # Remove the existing strategy if it exists
  41. rm.strat(strategy.st)
  42.  
  43. # Initialize the portfolio
  44. initPortf(portfolio.st, symbols ="SPY", initDate =initdate, currency ="USD")
  45. # Initialize the account
  46. initAcct(account.st, portfolios =portfolio.st, initDate =initdate, currency = "USD", initEq =initeq)
  47. # Initialize the orders
  48. initOrders(portfolio.st, initDate =initdate)
  49. # Store the strategy
  50. strategy(strategy.st, store = T)
  51.  
  52. # Create a 200-day SMA
  53. spy_sma <- SMA(Cl(SPY),200)
  54. plot.xts(spy_sma)
  55. # Create an RSI with a 3-day lookback period
  56. spy_rsi <- RSI(Cl(SPY),3)
  57. spy_rsi
  58.  
  59. # Plot the closing prices of SPY
  60. plot(Cl(SPY));lines(SMA(Cl(SPY), n =200), col ="red")
  61.  
  62. # Plot the closing price of SPY
  63. plot(Cl(SPY))
  64. # Plot the RSI 2
  65. plot(RSI(Cl(SPY),2))
  66.  
  67. # Add a 200-day SMA indicator to strategy.st
  68. add.indicator(strategy = strategy.st,
  69. # Add the SMA function
  70. name = "SMA",
  71. # Create a lookback period
  72. arguments = list(x = quote(Cl(mktdata)), n = 200),
  73. label = "SMA200")
  74.  
  75. # Add a 50-day SMA indicator to strategy.st
  76. add.indicator(strategy = strategy.st,
  77. # Add the SMA function
  78. name = "SMA",
  79. # Create a lookback period
  80. arguments = list(x =quote(Cl(mktdata)), n = 50),
  81. label = "SMA50")
  82.  
  83. plot.xts(Cl(SPY));lines(SMA(Cl(SPY),200),col="red");lines(SMA(Cl(SPY),50),col="blue")
  84.  
  85. # Add an RSI 3 indicator to strategy.st
  86. add.indicator(strategy = strategy.st,
  87. # Add the RSI 3 function
  88. name ="RSI",
  89. # Create a lookback period
  90. arguments = list(x=quote(Cl(mktdata)),n=3),
  91. label ="RSI_3")
  92.  
  93. plot.xts(Cl(SPY));lines(SMA(Cl(SPY),200))
  94. plot.xts(RSI(Cl(SPY),200));lines(SMA(RSI(Cl(SPY),200),50),col="red")
  95.  
  96. # Declare the DVO function
  97. DVO <- function(HLC, navg =2, percentlookback =126) {
  98. # Compute the ratio between closing prices to the average of high and low
  99. ratio <- Cl(HLC)/((Hi(HLC) + Lo(HLC))/2)
  100. # Smooth out the ratio outputs using a moving average
  101. avgratio <- SMA(ratio, n =navg)
  102. # Convert ratio into a 0-100 value
  103. out <- runPercentRank(avgratio, n = percentlookback, exact.multiplier = 1) * 100
  104. colnames(out) <- "DVO"
  105. return(out)
  106. }
  107.  
  108. # Add the DVO indicator to the strategy
  109. add.indicator(strategy = strategy.st, name = "DVO",
  110. arguments = list(HLC = quote(HLC(mktdata)), navg =2, percentlookback =126),
  111. label = "DVO_2_126")
  112.  
  113. # Use applyIndicators to test indicators
  114. test <- applyIndicators(strategy =strategy.st, mktdata = OHLC(SPY))
  115. head(test)
  116. # Subset data between Sep. 1 and Sep. 5 of 2013
  117. test_subset <- test["2013-09-1/2013-09-5"]
  118.  
  119. plot.xts(Cl(SPY));lines(test)
  120. plot.xts(test)
  121. plot.xts(test_subset)
  122.  
  123. # A sigComparison which specifies that SMA50 must be greater than SMA200
  124. add.signal(strategy.st, name = "sigComparison",
  125. # I'm are interested in the relationship between the SMA50 and the SMA200
  126. arguments = list(columns = c("SMA50", "SMA200"),
  127. # Particularly, I'm are interested when the SMA50 is greater than the SMA200
  128. relationship = "gt"),
  129. label = "longfilter")
  130.  
  131. # Add a sigCrossover which specifies that the SMA50 is less than the SMA200
  132. add.signal(strategy.st, name = "sigCrossover",
  133. # We're interested in the relationship between the SMA50 and the SMA200
  134. arguments = list(columns = c("SMA50", "SMA200"),
  135. # The relationship is that the SMA50 crosses under the SMA200
  136. relationship = "lt"),
  137. label = "filterexit")
  138.  
  139. # Implement a sigThreshold which specifies that DVO_2_126 must be less than 2
  140. add.signal(strategy.st, name = "sigThreshold",
  141. # Use the DVO_2_126 column
  142. arguments = list(column = "DVO_2_126",
  143. # The threshold is 20
  144. threshold =20,
  145. # I want the oscillator to be under this value
  146. relationship = "lt",
  147. # I'm interested in every instance that the oscillator is less than 20
  148. cross =F),
  149. label = "longthreshold")
  150.  
  151. # A sigThreshold signal that specifies that DVO_2_126 must cross above 80
  152. add.signal(strategy.st, name = "sigThreshold",
  153. # Reference the column of DVO_2_126
  154. arguments = list(column = "DVO_2_126",
  155. # Set a threshold of 80
  156. threshold =80,
  157. # The oscillator must be greater than 80
  158. relationship = "gt",
  159. # We are interested only in the cross
  160. cross =TRUE),
  161. label = "thresholdexit")
  162.  
  163. # Create dataset: test
  164. test_init <- applyIndicators(strategy.st, mktdata = OHLC(SPY))
  165. test <- applySignals(strategy = strategy.st, mktdata =test_init)
  166.  
  167. # Add a sigFormula signal
  168. add.signal(strategy.st, name = "sigFormula",
  169. arguments = list(formula = "longfilter & longthreshold",
  170. cross = T),
  171. label = "longentry")
  172.  
  173. add.rule(strategy.st, name = "ruleSignal",
  174. arguments = list(sigcol = "filterexit", sigval = TRUE, orderqty = "all",
  175. ordertype = "market", orderside = "long",
  176. replace = FALSE, prefer = "Open"),
  177. type = "exit")
  178.  
  179. add.rule(strategy.st, name = "ruleSignal",
  180. arguments = list(sigcol = "thresholdexit", sigval = TRUE, orderqty = "all",
  181. ordertype = "market", orderside = "long",
  182. replace = FALSE, prefer = "Open"),
  183. type = "exit")
  184.  
  185. # Create an entry rule of 1 share when all conditions line up to enter into a position
  186. add.rule(strategy.st, name = "ruleSignal",
  187. arguments=list(sigcol = "longentry",
  188. sigval =T,
  189. orderqty =1,
  190. ordertype = "market",
  191. orderside = "long",
  192. replace =F,
  193. prefer = "Open"),
  194. type = "enter")
  195.  
  196. # Add a rule that uses an osFUN to size an entry position
  197. add.rule(strategy = strategy.st, name = "ruleSignal",
  198. arguments = list(sigcol = "longentry", sigval = TRUE, ordertype = "market", orderside = "long", replace = FALSE, prefer = "Open",
  199. # Use the osFUN called osMaxDollar
  200. osFUN =osMaxDollar,
  201. # The tradeSize argument should be equal to tradesize (defined earlier)
  202. tradeSize =tradesize,
  203. # The maxSize argument should be equal to tradesize as well
  204. maxSize =tradesize),
  205. type = "enter")
  206.  
  207. # Use applyStrategy() to apply the strategy.
  208. end <- applyStrategy(strategy =strategy.st, portfolios =portfolio.st)
  209. # Update your portfolio (portfolio.st)
  210. updatePortf(portfolio.st)
  211. daterange <- time(getPortfolio(portfolio.st)$summary)[-1]
  212. # Update your account (account.st)
  213. updateAcct(account.st, daterange)
  214. updateEndEq(account.st)
  215. tradeStats(portfolio.st)
  216.  
  217. # Use chart.Posn to view system's performance on SPY
  218. chart.Posn(Portfolio =portfolio.st, Symbol = "SPY")
  219.  
  220. # Compute the SMA50
  221. sma50 <- SMA(x = Cl(SPY), n =50)
  222. # Compute the SMA200
  223. sma200 <- SMA(x = Cl(SPY), n =200)
  224. # Compute the DVO_2_126 with an navg of 2 and a percentlookback of 126
  225. dvo <- DVO(HLC = HLC(SPY), navg =2, percentlookback =126)
  226. # Recreate the chart.Posn of the strategy from the previous exercise
  227. chart.Posn(Portfolio=portfolio.st,Symbol="SPY")
  228. # Overlay the SMA50 on your plot as a blue line
  229. add_TA(sma50, on =1, col = "blue")
  230. # Overlay the SMA200 on your plot as a red line
  231. add_TA(sma200, on =1, col = "red")
  232. # Add the DVO_2_126 to the plot in a new window
  233. add_TA(dvo,2)
  234.  
  235. # Get instrument returns
  236. instrets <- PortfReturns(account.st)
  237. # Compute Sharpe ratio from returns
  238. SharpeRatio.annualized(instrets, geometric = FALSE)
Add Comment
Please, Sign In to add comment