Return simulated pricing result

Dear community,

I am quite new to R and try to do a pricing simulation. The goal is to have a vector with length n, that gives a percentage for the coupon that will be received. When I use print, I get exactly the result I want. However, for my subsequent calculations I cannot proceed with results in print format. I tried replacing it with return but this just gives me one result.

Any input is appreciated.
Thank you very much for your help!

(package used for rgpd is POT)

bond_coupon <- function(n, l) {
    events <- rpois(n, l) #simulates the rate of arrival according to a Poisson process
    for (i in 1:length(events)){
        cat <- rgpd(events[i], loc=1000, scale=100, shape=1) #simulates the severance of each event
        if(events[i]>1){
            coupon <- prod(1-((cat-1000)/cat))
        } else if(events[i]==1){
            coupon<- 1-((cat-1000)/cat)
        } else{
            coupon<- 1.00
        }
        print(coupon)
    }
}

Hi @jfelb,
Welcome to the RStudio Community Forum.

If I understand correctly, you need to return() the function result, and within the for() loop you need to fill an indexed vector of results (coupon).

library(POT)
bond_coupon <- function(n, l) {
    set.seed(1984)
    events <- rpois(n, l) #simulates the rate of arrival according to a Poisson process
    coupon <- vector(mode="numeric", length=length(events))
    for (i in 1:length(events)){
        cat <- rgpd(events[i], loc=1000, scale=100, shape=1) #simulates the severance of each event
        if(events[i]>1){
            coupon[i] <- prod(1-((cat-1000)/cat))
        } else if(events[i]==1){
            coupon[i] <- 1-((cat-1000)/cat)
        } else{
            coupon[i] <- 1.00
        }
        #print(coupon)
    }
    return(coupon)
}

bond_coupon(5,3)
#> [1] 0.21558089 0.07809604 0.92409025 0.13531589 0.55189125
bond_coupon(5,3)
#> [1] 0.21558089 0.07809604 0.92409025 0.13531589 0.55189125
bond_coupon(10,5)
#>  [1] 0.01333999 0.55189125 0.02604796 0.58235869 0.64922247 0.04307997
#>  [7] 0.79360934 0.59315766 0.26696339 0.33828484
keep <- bond_coupon(10,5)

mapply(bond_coupon, n=c(5:8), l=c(2:5))
#> [[1]]
#> [1] 0.24713574 0.87231774 0.73204329 0.98688297 0.09989437
#> 
#> [[2]]
#> [1] 0.1603281 0.1024222 0.6905634 0.1528380 0.6402925 0.0176090
#> 
#> [[3]]
#> [1] 0.06812456 0.12504410 0.76491904 0.02030816 0.57773584 0.62272458 0.97252312
#> 
#> [[4]]
#> [1] 0.07071801 0.10438610 0.02013688 0.58816654 0.66212291 0.05233179 0.74847231
#> [8] 0.49875285

<sup>Created on 2021-03-01 by the [reprex package](https://reprex.tidyverse.org) (v1.0.0)</sup>

I leave you to determine if the results are sensible!
HTH

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.