# [R-SIG-Finance] Are there genetic algorithm for trading strategy evolution in R?

Roupell, Darko Darko.Roupell at cba.com.au
Thu Mar 8 23:23:10 CET 2012

```To contribute to this discussion with a more concrete example of genetic algorithm usage for trading purpose I have disclosed simple code snippet how to implement it using DEoptim. GALGO is alternative to DEoptim in R.

Micheal, generally I do not provide complete examples so for this exception thank to Patrick Burns as he helped me in the past with PortfolioProbe Optimizer. Hope it helps.

******Disclaimer this is just example for learning purposes but no warranty is made as to accuracy and no liability is accepted if used for commercial purposes****

require(quantmod)
require(PerformanceAnalytics)
require(blotter)
require(DEoptim)
################ MACD TEST
z =as.xts(z, as.POSIXct(z\$Date))
#force columns into numeric values
z\$sum=as.numeric(z\$INTC)+as.numeric(z\$IEF)
z = z[,c("INTC", "IEF")]
# Ra is the log return for a buy-and-hold strategy, Rb the 'benchmark.'
# We will extensively use these log-return series in the sequel.

z\$Ra = Return.calculate(z\$INTC)
z\$Rb = Return.calculate(z\$IEF)
# we will optimise over in sample data
insample=z['2008:']

#the fitness function must obtain the data
MACDFitness  <- function(params) {
fast  <- params[1]
slow  <- params[2]
sig  <- params[3]
if ((fast <= slow - 1) & (slow >= 4) & (fast >=4) & ((sig >= fast) & (sig <= slow))) { #certain conditions does not make sense
params = paste("F: ",fast," slow: ",slow,sep="")
x <- MACD(parent\$INTC, nFast=fast, nSlow=slow, nSig=sig,maType="EMA")
position <- sign(x[,1]-x[,2])
s <- xts(position,order.by=index(parent))
s\$Ra <- parent\$Ra
s\$Rb <- parent\$Rb
s\$rts <- (s\$Ra*(s\$macd>0)) + (s\$Rb*(s\$macd<=0))
Dt <- na.omit(s\$rts-s\$Rb)
sharpe = (mean(Dt)*252)/(sd(Dt)*sqrt(252))
} else {
sharpe = -100
}
#have to return negative sharpe because DEoptim minimises the fitness function
return(-sharpe)
}

lower = c(4,4,4)
upper = c(63,63,63)

set.seed(1234)
parent=z

#perform optimizaztion, set value to reach at -6 (i.e. sharpe ratio of 6 in this example) and maximum interations = 100
outDEoptim = DEoptim(MACDFitness,lower,upper, DEoptim.control(VTR=-6,itermax=100,))
summary(outDEoptim)

__________________________________________________
Commonwealth Bank
Darko Roupell
Associate Quantitative Analyst
Institutional Banking & Markets
Equities Research
Darling Park Tower 1
Level 23, 201 Sussex Street
Sydney, NSW 2000
P:  +61 2 9117 1254
F:  +61 2 9118 1000
M: +61 400 170 515
E: Darko.Roupell at cba.com.au
Our vision is to be Australia's finest financial services organisation through excelling in customer service.

Email Security
This email is sent solely for informational purposes. Hoax emails, commonly referred to as phishing, can appear to be from the Commonwealth Bank and ask you to update or confirm details such as client numbers, passwords, personal identification questions, contact details or account numbers. The Commonwealth Bank will never send you an email asking you to confirm, update or reveal your confidential banking information.
Important Information
Produced by Global Markets Research, a business unit of Commonwealth Bank of Australia ABN 48 123 123 124 - AFSL 234945 (Commonwealth Bank). This publication is based on information available at the time of publishing.  We believe that the information in this communication is correct and any opinions, conclusions or recommendations are reasonably held or made as at the time of its compilation, but no warranty is made as to accuracy, reliability or completeness.  To the extent permitted by law, neither Commonwealth Bank nor any of its subsidiaries accept liability to any person for loss or damage arising from the use of this communication. This communication does not purport to be a complete statement or summary.
The information provided has been prepared without considering your objectives, financial situation or needs, and before acting on the information, you should consider its appropriateness to your circumstances. No person should act on the basis of this report without considering and if necessary taking appropriate professional advice upon their own particular circumstances.
Commonwealth Bank of Australia, as a provider of investment, borrowing and other financial services undertakes financial transactions with many corporate entities in Australia. This may include any corporate issuer referred to in this communication. Commonwealth Bank and its subsidiaries have effected or may effect transactions for their own account in any investments or related investments referred to herein. In the case of certain securities Commonwealth Bank is or may be the only market maker.

-----Original Message-----
From: r-sig-finance-bounces at r-project.org [mailto:r-sig-finance-bounces at r-project.org] On Behalf Of Patrick Burns
Sent: Friday, 9 March 2012 6:24 AM
To: Daniel Cegiełka
Cc: r-sig-finance at r-project.org
Subject: Re: [R-SIG-Finance] Are there genetic algorithm for trading strategy evolution in R?

Yes, serious chance of doing it poorly
without years of intense work.

On 08/03/2012 19:14, Daniel Cegiełka wrote:
> Let me add my two cents. Old Max Dama blog (mirror):
>
> http://smartdatacollective.com/maxdama/22571/voodoo-spectrum-machine-learning-and-data-sets
>
>
> Optimization is good to examine the sensitivity of the model and the
> selection of appropriate parameters - this is useful. But playing with
> the evolutionary strategy, what you Michael ask, is very risky.
>
> regards,
> Daniel
>
>
>
> 2012/3/8 Patrick Burns <patrick at burns-stat.com
> <mailto:patrick at burns-stat.com>>
>
>
>
>     On 08/03/2012 18:16, Michael wrote:
>
>         Thanks folks!
>
>         After digging further on the Internet, I have the following
>         questions:
>
>         Q1: I read the following article:
>
>         http://cran.r-project.org/web/__packages/DEoptim/vignettes/__DEoptimPortfolioOptimization.__pdf
>         <http://cran.r-project.org/web/packages/DEoptim/vignettes/DEoptimPortfolioOptimization.pdf>
>
>         It seems that there are a bunch of parameters in this optimizer
>         and the
>         results are sensitive to these parameters.
>
>         So there is another layer of optimization with respect to these
>         optimizer
>         parameters.
>
>         Is the "tweaking" of these optimizer parameters data-mining,
>         which will
>
>
>     I wouldn't think so, but there might be
>     a way to manage it.
>
>
>
>         Q2: Due to the random nature of the optimizer, each time you run the
>         backtest, you will have different performance.
>
>         What do you do in that case?
>
>
>     That may be a good thing, if you are
>     willing to use it.
>
>     In what I've done on backtesting:
>
>     http://www.portfolioprobe.com/__2010/11/05/backtesting-almost-__wordless/
>     <http://www.portfolioprobe.com/2010/11/05/backtesting-almost-wordless/>
>
>     I show how to assess whether the strategy
>     is better than luck by using random trades.
>
>     The standard thing to assume (as I do in
>     that piece) is that the optimization is
>     noiseless.  But really the optimization
>     depends on a multitude of subtle influences.
>     Even if you always got the exact global
>     optimum, if a variance or expected return
>     were slightly different, you could get a
>     very different path.  The "optimal" path
>     is fuzzy in actuality.
>
>
>
>
>
>     Yes.  But the inputs are random so even
>     non-stochastic optimizers give you a
>     random strategy in a sense.
>
>
>
>         Q3: It's pretty easy to understand using Genetic Algorithms to
>         serve as a
>         replacement for regular optimizers;
>
>         but using Genetic Algorithms to evolve trading strategies seem to be
>         different. Anywhere we could find such an example in R?
>
>
>     Yes, that is different.
>
>     In
>     https://stat.ethz.ch/__pipermail/r-sig-finance/__2010q4/007033.html
>     <https://stat.ethz.ch/pipermail/r-sig-finance/2010q4/007033.html>
>     you can find Josh quoting me quoting Lao-Tzu
>     on why you are unlikely to find much useful
>     on that subject.
>
>     Pat
>
>
>
>
>
>
>         On Thu, Mar 8, 2012 at 8:25 AM, Zachary
>         Mayer<zach.mayer at gmail.com <mailto:zach.mayer at gmail.com>>  wrote:
>
>             There is the
>             DEoptim<http://cran.r-project.__org/web/packages/DEoptim/__index.html
>             <http://cran.r-project.org/web/packages/DEoptim/index.html>>library
>             in r, which is an excellent library for differential
>             evolution.  If
>             you can define your trading strategy in terms of a bunch of
>             parameters to
>             adjust and an objective function (i.e. turn it into an
>             optimization
>
>             DEoptim works well on non-differentiable problems with many
>             local minima.
>               Here is an example of using it to solve a portfolio
>             optimization problem:
>
>             http://cran.r-project.org/web/__packages/DEoptim/vignettes/__DEoptimPortfolioOptimization.__pdf
>             <http://cran.r-project.org/web/packages/DEoptim/vignettes/DEoptimPortfolioOptimization.pdf>
>
>
>
>             On Thu, Mar 8, 2012 at 12:43 AM, Sofian
>             <mailto:reztinpeace at gmail.com>>wrote:
>
>
>                 On Wed, Mar 7, 2012 at 10:30 PM,
>                 Michael<comtech.usa at gmail.com
>                 <mailto:comtech.usa at gmail.com>>  wrote:
>
>                     Hi all, Good morning, good afternoon and good evening!
>
>                     Could anybody please kindly point me to resources in
>                     how to use Genetic algorithm to evolve trading
>                     strategies?
>
>                     I did a lot search on Google these days and
>                     certainly it's a
>
>                 well-covered
>
>                     and popular topic, but I don't see anywhere in R...
>
>                     Thanks a lot!
>
>                             [[alternative HTML version deleted]]
>
>                     _________________________________________________
>                     R-SIG-Finance at r-project.org
>                     <mailto:R-SIG-Finance at r-project.org> mailing list
>                     https://stat.ethz.ch/mailman/__listinfo/r-sig-finance <https://stat.ethz.ch/mailman/listinfo/r-sig-finance>
>                     -- Subscriber-posting only. If you want to post,
>                     subscribe first.
>                     -- Also note that this is not the r-help list where
>                     general R questions
>                     should go.
>
>
>                         [[alternative HTML version deleted]]
>
>                 _________________________________________________
>                 R-SIG-Finance at r-project.org
>                 <mailto:R-SIG-Finance at r-project.org> mailing list
>                 https://stat.ethz.ch/mailman/__listinfo/r-sig-finance
>                 <https://stat.ethz.ch/mailman/listinfo/r-sig-finance>
>                 -- Subscriber-posting only. If you want to post,
>                 subscribe first.
>                 -- Also note that this is not the r-help list where
>                 general R questions
>                 should go.
>
>
>
>
>                 [[alternative HTML version deleted]]
>
>         _________________________________________________
>         R-SIG-Finance at r-project.org <mailto:R-SIG-Finance at r-project.org>
>         mailing list
>         https://stat.ethz.ch/mailman/__listinfo/r-sig-finance
>         <https://stat.ethz.ch/mailman/listinfo/r-sig-finance>
>         -- Subscriber-posting only. If you want to post, subscribe first.
>         -- Also note that this is not the r-help list where general R
>         questions should go.
>
>
>     --
>     Patrick Burns
>     patrick at burns-stat.com <mailto:patrick at burns-stat.com>
>     http://www.burns-stat.com
>     http://www.portfolioprobe.com/__blog
>     <http://www.portfolioprobe.com/blog>
>
>
>     _________________________________________________
>     R-SIG-Finance at r-project.org <mailto:R-SIG-Finance at r-project.org>
>     mailing list
>     https://stat.ethz.ch/mailman/__listinfo/r-sig-finance
>     <https://stat.ethz.ch/mailman/listinfo/r-sig-finance>
>     -- Subscriber-posting only. If you want to post, subscribe first.
>     -- Also note that this is not the r-help list where general R
>     questions should go.
>
>

--
Patrick Burns
patrick at burns-stat.com
http://www.burns-stat.com
http://www.portfolioprobe.com/blog

_______________________________________________
R-SIG-Finance at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-sig-finance
-- Subscriber-posting only. If you want to post, subscribe first.
-- Also note that this is not the r-help list where general R questions should go.

************** IMPORTANT MESSAGE *****************************
This e-mail message is intended only for the addressee(s) and contains information which may be
confidential.
If you are not the intended recipient please advise the sender by return email, do not use or
disclose the contents, and delete the message and any attachments from your system. Unless
specifically indicated, this email does not constitute formal advice or commitment by the sender
or the Commonwealth Bank of Australia (ABN 48 123 123 124) or its subsidiaries.
We can be contacted through our web site: commbank.com.au.