[R-SIG-Finance] Fisher Transformation quantstrat strategy

Mattonline m@tton||ne1 @end|ng |rom gm@||@com
Sat Mar 28 22:55:16 CET 2020


I have a doubt/question regarding quantstrat (appologies if the mailing
list is not for this purpose).

I thought in order to better understand the quantstrat package that I would
try an implement a known trading strategy. Found here (
https://www.mesasoftware.com/papers/TheInverseFisherTransform.pdf )

The strategy is the following:

-          #1a) Buy when the indicator crosses over -0.5 or

-          #1b) Buy when the indicator crosses over +0.5 if it has not
previously crossed over -0.5

-          #2a) Sell short when the indicator crosses under +0.5 or

-          #2b) Sell short when the indicator crosses under -0.5 if it has
not previously crossed under +0.5

I “believe” I have parts 1a and 2a (correct me if I am wrong). However, I
am finding it a little difficult to implement parts 1b and 2b.

My question is, how can I implement the indicator when it crosses +0.5 but
has not previously crossed over -0.5. I can create the indicator to cross
+0.5 but not sure how to implement the “not previously crossed -0.5” part,
I have made some comments throughout the code where I have my doubts.



CODE with comments:


library(quantstrat)
library(quantmod)
library(PerformanceAnalytics)

currency("USD")
symbols <- c("AAPL", "MSFT", "GOOG", "INTC", "NVDA")

stock(symbols, currency = "USD")

start_date <- "2018-09-01"
end_date <- "2019-12-31"

getSymbols(symbols,
           from = start_date,
           to = end_date
           )

# collect the adjusted closing prices into a single xts model
daily_close <- do.call(merge, lapply(symbols, function(x) Ad(get(x))))

# parameters
init.equity = 100000

suppressWarnings(rm("order_book.FisherTransform", pos=.strategy))
suppressWarnings(rm("account.FisherTransform", "portfolio.FisherTransform",
pos=.blotter))
suppressWarnings(rm("account.st", "port.st", "stock.str", "FisherTransform",
                    "initDate", "initEq", 'start_t', 'end_t'))


# set initial variables
initDate <- "1900-01-01"
initEq <- init.equity
port.st <- "FisherTransform"
account.st <- "FisherTransform"

# initialize quantstrat objects
initPortf(port.st, symbols = symbols, initDate = initDate)
initAcct(account.st, portfolios = port.st, initDate = initDate, initEq =
initEq)
initOrders(portfolio = port.st, initDate = initDate)

# initialize a strategy object
stratFisherTransform <- strategy("FisherTransform")

# Link to basic Fisher strategy:
https://www.mesasoftware.com/papers/TheInverseFisherTransform.pdf
fisherTransformFunction <- function(x, RSI_Period = 5, SMA_Period = 9){
  Value1 = RSI(x, RSI_Period)
  Value1 = Value1 - 50
  Value1 = Value1 * 0.10

  Value2 = SMA(Value1, SMA_Period)

  invFisher = (exp(2*Value2) - 1) / (exp(2*Value2) + 1)

  return(invFisher)
}

# Strategy overview

#1a) Buy when the indicator crosses over -0.5 or
#1b) Buy when the indicator crosses over +0.5 if it has not previously
crossed over -0.5
#2a) Sell short when the indicator crosses under +0.5 or
#2b) Sell short when the indicator crosses under -0.5 if it has not
previously crossed under +0.5

# Stuck on parts 1b and 2b (I think)

# Add indicator
stratFisherTransform <-  add.indicator(
  strategy = stratFisherTransform,
  name = "fisherTransformFunction",
  arguments = list(
    x = quote(Ad(mktdata)[,1]),
    RSI_Period = 6,
    SMA_Period = 10),
  label= "FisherTransform")



# Add signal
#1a)
stratFisherTransform <- add.signal(
  strategy = stratFisherTransform,
  name = "sigThreshold",
  arguments = list(
    threshold = -0.5,
    column = "FisherTransform",
    relationship = "gt",         # creates a signal when the indicator is
gt -0.5 (point 1a)
    cross = TRUE),
  label = "AboveNegative0.5")

#2a)
stratFisherTransform <- add.signal(
  strategy = stratFisherTransform,
  name = "sigThreshold",
  arguments = list(
    threshold = +0.5,
    column = "FisherTransform",
    relationship = "lt",        # creates a signal when the indicator is lt
+0.5 (point 2a)
    cross = TRUE),
  label = "BelowPositive0.5")

# I want to add the signals for 1b and 2b but I am a little lost on how to
incorporate the parts
# of the strategy "if it has not previously crossed over (under) -0.5 (+0.5)

max.size = 1000

# Add buy rule
stratFisherTransform <- add.rule(
  strategy = stratFisherTransform,
  name = 'ruleSignal',
  arguments = list(
    sigcol = "AboveNegative0.5",    # buy when the signal for 1a is true
    sigval = TRUE,
    orderqty = max.size,
    ordertype = 'market',
    orderside = 'long',
    pricemethod = 'market',
    replace = FALSE,
    osFUN = osMaxPos),
  type = 'enter',
  path.dep = TRUE)

# add exit rule
stratFisherTransform <- add.rule(
  strategy = stratFisherTransform,  # exit any positions (when 1a is true
and the indicator is
  name = 'ruleSignal',              # below +0.5) - this is not a short
position just an exit position
  arguments = list(
    sigcol = "BelowPositive0.5",
    sigval = TRUE,
    orderqty = 'all',
    ordertype = 'market',
    orderside = 'long',
    pricemethod = 'market',
    replace = FALSE),
  type = 'exit',
  path.dep = TRUE)

max.levels = 1
for(symbol in symbols){
  addPosLimit(port.st, symbol, initDate, max.size, max.levels)
  }

# apply the strategy to the portfolio

out <- try(applyStrategy(strategy = stratFisherTransform, portfolios =
port.st))


# update Portfolio
updatePortf(Portfolio=port.st, Dates=paste('::', as.Date(Sys.time()),
sep=''))
updateAcct(account.st)
updateEndEq(account.st)

# Below code is a little unnecessary but I keep for completness
eq <- getEndEq(account.st, Sys.Date()) + initEq
order.book <- getOrderBook(port.st)
stats <- tradeStats(port.st)
ret1 <- PortfReturns(port.st)
ret1$total <- rowSums(ret1, na.rm = TRUE)

end.eq = eq
returns = ret1
book = order.book
stats = stats
portfolio = port.st

chart.Posn(Portfolio = portfolio, Symbol = "AAPL")

	[[alternative HTML version deleted]]



More information about the R-SIG-Finance mailing list