[R] repeat a function

Eric.Pueyo at avivainvestors.com Eric.Pueyo at avivainvestors.com
Thu Nov 2 17:54:29 CET 2017


Hi Petr, 

Many thanks for your response.

Basically I want to create a probability matrix to be used in a trinomial tree going forward. This is the reason why I thought to build the matrix around 0 would be much more efficient. I need to loop through because the probabilities will depend on my node and is not always the same per row (e.g. if N> jmax, jmax being defined in another function)
I found a workaround. Please see below. 
Thereafter I want to optimize this function. Hopefully it works.

Many thanks,
Eric

HWMProb <- function(N) {
  ProbUP<- function( a, j, dt) 1 / 6 + ((j ^ 2 * Mfactor(a, dt) ^ 2 + j * Mfactor(a, dt)) / 2)          ######### Probability X going up
  ProbMID<- function(a, j, dt) 2 / 3 - (j ^ 2 * Mfactor(a, dt) ^ 2)                                     ######## Probability X going middle
  ProbDWN<-function( a, j, dt) 1 / 6 + ((j ^ 2 * Mfactor(a, dt) ^ 2 - j * Mfactor(a, dt)) / 2)          #######  Probability X going down
  TOPProbUP<- function( a, j, dt) 7 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 + 3 * j * Mfactor(a, dt)) / 2     ####### Top branch probability going up
  TOPProbMID<- function(a, j, dt) -1 / 3 - j ^ 2 * Mfactor(a, dt) ^ 2 - 2 * j * Mfactor(a, dt)          ####### Top branch probability going MID
  TOPProbDWN<- function( a, j, dt) 1 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 + j * Mfactor(a, dt)) / 2        ####### Top branch probability going DOWN
  BTTMProbUP<- function( a, j, dt) 1 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 - j * Mfactor(a, dt)) / 2        ####### Bottom branch probability going u
  BTTMProbMID<- function( a, j, dt) -1 / 3 - j ^ 2 * Mfactor(a, dt) ^ 2 + 2 * j * Mfactor(a, dt)        ####### Bottom branch probability going MID
  BTTMProbDWN<- function( a, j, dt) 7 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 - 3 * j * Mfactor(a, dt)) / 2   ####### Bottom branch probability going DOWN

if (N>jmax) N=jmax

for (j in 0:N) {    
  if (j==0) {
    prb["0","1"] <<- ProbUP(a,j,dt)
    prb["0","0"] <<- ProbMID(a,j,dt)
    prb["0","-1"] <<- ProbDWN(a,j,dt)
  }
  else {
    if (j==jmax) {
      prb[paste(j,sep = ""),"1"] <<- TOPProbUP(a,j,dt)
      prb[paste(j,sep = ""),"0"] <<- TOPProbMID(a,j,dt)
      prb[paste(j,sep = ""),"-1"] <<- TOPProbDWN(a,j,dt)
      prb[paste(-j,sep = ""),"1"] <<- BTTMProbUP(a,-j,dt)
      prb[paste(-j,sep = ""),"0"] <<- BTTMProbMID(a,-j,dt)
      prb[paste(-j,sep = ""),"-1"] <<- BTTMProbDWN(a,-j,dt)
    }
    else {
      prb[paste(j,sep = ""),"1"] <<- ProbUP(a,j,dt)
      prb[paste(j,sep = ""),"0"] <<- ProbMID(a,j,dt)
      prb[paste(j,sep = ""),"-1"] <<- ProbDWN(a,j,dt)
      prb[paste(-j,sep = ""),"1"] <<- ProbUP(a,-j,dt)
      prb[paste(-j,sep = ""),"0"] <<- ProbMID(a,-j,dt)
      prb[paste(-j,sep = ""),"-1"] <<- ProbDWN(a,-j,dt)
    } # Close 2nd IF
  } # Close 1st IF
} #end for
}


-----Original Message-----
From: PIKAL Petr [mailto:petr.pikal at precheza.cz] 
Sent: 02 November 2017 15:56
To: Eric Pueyo; r-help at r-project.org
Subject: RE: [R] repeat a function

Hi Eric

I did not see any answer and frankly speaking I cannot provide you with canned help.

AFAIK if a function is defined within another function (which is your case) it cannot be called directly so it is necessary to define it in global environment.

>  fff <- function(x) {
+  myf <- function(a) a+2
+  myf(x)^2}
>
> fff(5)
[1] 49
> myf(5)
Error in myf(5) : could not find function "myf"
>

Your function set is quite complicated but I wonder why would it be necessary to use for cycle for what seems to be simple table. Everything seems quite deterministic.

Basically you have combination of rows (-2,-1,0,1,2) and columns -1,-,1.
expand.grid(u=-2:2, v=-1:1)
for each row you can than use one function with parameters u, v and a and dt.
After you calculate vector of results, you can easily transform it to matrix by setting dim argument to it.

Cheers
Petr

> -----Original Message-----
> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of 
> Eric.Pueyo at avivainvestors.com
> Sent: Wednesday, November 1, 2017 1:31 PM
> To: r-help at r-project.org
> Subject: [R] repeat a function
>
> I want to populate the matrix prb through the function HWMProb <- 
> function
> (a,j,dt) that encapsulates different functions (please see code 
> below), using j=
> 0:2 for each j.
>
> It only populates prb if I specify each function independently in the 
> global environment and then run the loop with the iF statement, as per below.
> for (j in 0:2) {
>   if (j==0) {
>     prb["0","1"] <- ProbUP(a,j,dt)
>     prb["0","0"] <- ProbMID(a,j,dt)
>     prb["0","-1"] <- ProbDWN(a,j,dt)
>   }
>   else {
>     if (j==jmax) {
>       prb[paste(j,sep = ""),"1"] <- TOPProbUP(a,j,dt)
>       prb[paste(j,sep = ""),"0"] <- TOPProbMID(a,j,dt)
>       prb[paste(j,sep = ""),"-1"] <- TOPProbDWN(a,j,dt)
>       prb[paste(-j,sep = ""),"1"] <- BTTMProbUP(a,-j,dt)
>       prb[paste(-j,sep = ""),"0"] <- BTTMProbMID(a,-j,dt)
>       prb[paste(-j,sep = ""),"-1"] <- BTTMProbDWN(a,-j,dt)
>     }
>     else {
>       prb[paste(j,sep = ""),"1"] <- ProbUP(a,j,dt)
>       prb[paste(j,sep = ""),"0"] <- ProbMID(a,j,dt)
>       prb[paste(j,sep = ""),"-1"] <- ProbDWN(a,j,dt)
>       prb[paste(-j,sep = ""),"1"] <- ProbUP(a,-j,dt)
>       prb[paste(-j,sep = ""),"0"] <- ProbMID(a,-j,dt)
>       prb[paste(-j,sep = ""),"-1"] <- ProbDWN(a,-j,dt)
>     } # Close 2nd IF
>   } # Close 1st IF
> }
>
> Many thanks in advance.
> Kind regards,
>
> Eric Pueyo
> Investment Risk Analyst
> Email:
> Eric.Pueyo at avivainvestors.com<mailto:Eric.Pueyo at avivainvestors.com>
> D: +44 (0)20 7809 8070
> No. 1 Undershaft, London EC3P 3DQ
> Web:
> www.avivainvestors.com<https://urldefense.proofpoint.com/v2/url?u=http
> -
> 3A__www.avivainvestors.com_&d=CwMFAg&c=zUO0BtkCe66yJvAZ4cAvZg&r=-
> 34SVFvqwmZvbxD0ShuYglbuijP84lygitjFgiP1fxI&m=kRg3I7ESFxV-
> KaNbYHN6DPupgyEmFCiThNO6oDnpAFs&s=tQa1EuXKNfzRgiR2HgG0H_tW_X-
> BCpgebe5AL9A_GC8&e=>
>
> jmax<-2
> prb <-matrix(0L,nrow=5, ncol=3)
> rownames(prb) <- c(seq(-2,2, by = 1))
> colnames(prb) <- c(-1,0,1)
> a<- 0.1
> dt<-1
>
> ExpX <-function(x,a,dt) {                              ######Defines the Expectation of X
> on t+1 | t
> ExpX <- x*exp(-a*dt)
> ExpX
> }
> Mfactor<-function(a,dt)  {                           #######Factor multiplicative
>   Mfactor<- exp(-a*dt)-1
>   Mfactor
> }
> VarX <-function(sigma,a,dt) {                         #######Defubes the Variance of X
> on t+1 | t
>   VarX <- (sigma^2/(2*a))*(1-exp(-2*a*dt))
>   VarX
> }
> DeltaX <-function(sigma,a,dt) {                       ######Defines the change of X
>   DeltaX<- sqrt(3*VarX(sigma,a,dt))
>   DeltaX<-value(DeltaX)
> }
>
> Mfactor<-function(a,dt)  {                           #######Factor multiplicative
>   Mfactor<- exp(-a*dt)-1
>   Mfactor
> }
>
> KNode<-function(sigma,x,a,j,dt) {                    ######Central Node
>   KNode<- round(ExpX(x,a,dt)/DeltaX(sigma,a,dt))
>   KNode
> }
>
> ####### Probability Calculations taking into account different 
> branches HWMProb <- function (a,j,dt) {
>   ######################### DESCRIPTION 
> #####################################
>   ProbUP<- function( a, j, dt) 1 / 6 + ((j ^ 2 * Mfactor(a, dt) ^ 2 + j * Mfactor(a,
> dt)) / 2)                     ######### Probability X going up
>   ProbMID<- function(a, j, dt) 2 / 3 - (j ^ 2 * Mfactor(a, dt) ^ 2) 
> ######## Probability X going middle
>   ProbDWN<-function( a, j, dt) 1 / 6 + ((j ^ 2 * Mfactor(a, dt) ^ 2 - j * Mfactor(a,
> dt)) / 2)                  #######  Probability X going down
>   TOPProbUP<- function( a, j, dt) 7 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 + 3 * j *
> Mfactor(a, dt)) / 2                 ####### Top branch probability going up
>   TOPProbMID<- function(a, j, dt) -1 / 3 - j ^ 2 * Mfactor(a, dt) ^ 2 - 2 * j *
> Mfactor(a, dt)              ####### Top branch probability going MID
>   TOPProbDWN<- function( a, j, dt) 1 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 + j *
> Mfactor(a, dt)) / 2               ####### Top branch probability going DOWN
>   BTTMProbUP<- function( a, j, dt) 1 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 - j *
> Mfactor(a, dt)) / 2           ####### Bottom branch probability going u
>   BTTMProbMID<- function( a, j, dt) -1 / 3 - j ^ 2 * Mfactor(a, dt) ^ 2 + 2 * j *
> Mfactor(a, dt)               ####### Bottom branch probability going MID
>   BTTMProbDWN<- function( a, j, dt) 7 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 - 3 * j *
> Mfactor(a, dt)) / 2              ####### Bottom branch probability going DOWN
>
>   if (j==0) {
>     prb["0","1"] <- ProbUP(a,j,dt)
>     prb["0","0"] <- ProbMID(a,j,dt)
>     prb["0","-1"] <- ProbDWN(a,j,dt)
>   }
>   else {
>     if (j==jmax) {
>       prb[paste(j,sep = ""),"1"] <- TOPProbUP(a,j,dt)
>       prb[paste(j,sep = ""),"0"] <- TOPProbMID(a,j,dt)
>       prb[paste(j,sep = ""),"-1"] <- TOPProbDWN(a,j,dt)
>       prb[paste(-j,sep = ""),"1"] <- BTTMProbUP(a,-j,dt)
>       prb[paste(-j,sep = ""),"0"] <- BTTMProbMID(a,-j,dt)
>       prb[paste(-j,sep = ""),"-1"] <- BTTMProbDWN(a,-j,dt)
>     }
>     else {
>       prb[paste(j,sep = ""),"1"] <- ProbUP(a,j,dt)
>       prb[paste(j,sep = ""),"0"] <- ProbMID(a,j,dt)
>       prb[paste(j,sep = ""),"-1"] <- ProbDWN(a,j,dt)
>       prb[paste(-j,sep = ""),"1"] <- ProbUP(a,-j,dt)
>      prb[paste(-j,sep = ""),"0"] <- ProbMID(a,-j,dt)
>       prb[paste(-j,sep = ""),"-1"] <- ProbDWN(a,-j,dt)
>     } # Close 2nd IF
>   } # Close 1st IF
> } #Close Formula
>
> for (j in 0:2) {
>   HWMProb(a,j,dt)
>
> }
>
>
>       [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see 
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

________________________________
Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou určeny pouze jeho adresátům.
Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie vymažte ze svého systému.
Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi či zpožděním přenosu e-mailu.

V případě, že je tento e-mail součástí obchodního jednání:
- vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
- a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout; Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany příjemce s dodatkem či odchylkou.
- trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve výslovným dosažením shody na všech jejích náležitostech.
- odesílatel tohoto emailu informuje, že není oprávněn uzavírat za společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich existence je adresátovi či osobě jím zastoupené známá.

This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.

In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.

This email transmission and any attachments may contain confidential or legally privileged information that is intended for the addressee(s) only. Any views or opinions presented are solely those of the author and do not necessarily represent those of Aviva Investors. If you are not the intended recipient or person responsible for delivering this information to the intended recipient you are hereby notified that any disclosure, copying, distribution or reliance upon the contents of this email is strictly prohibited. If you have received this email transmission in error please notify the sender immediately so that we may arrange for its proper delivery and delete the message from your inbox.

Aviva Investors Global Services Limited, registered in England No. 1151805. Entered on the Financial Services Register, No: 119178. Authorised and regulated by the Financial Conduct Authority.

Aviva Investors Pensions Limited, registered in England No. 1059606. Entered on the Financial Services Register, No: 110410. Authorised by the Prudential Regulation Authority and regulated by the Financial Conduct Authority and the Prudential Regulation Authority.

Aviva Investors UK Fund Services Limited, registered in England No. 1973412. Entered on the Financial Services Register, No. 119310. Authorised and regulated by the Financial Conduct Authority. 

Aviva Investors UK Funds Limited, registered in England No. 2503054. Entered on the Financial Services Register, No. 147088. Authorised and regulated by the Financial Conduct Authority. 

Registered Office for all companies: St Helen’s, 1 Undershaft, London EC3P 3DQ. VAT number: 105 4373 00.

Telephone calls to Aviva Investors may be recorded for training or monitoring purposes. We may monitor traffic data of both business and personal emails. By replying to this email, you consent to us monitoring the content of any emails you send to or receive from Aviva Investors.


More information about the R-help mailing list