Define limitation on generated random numbers

Asked

Viewed 45 times

2

I need to create a random investment portfolio with certain benchmarks. I initialized it with all 0.

structure(list(Benchmarks = structure(c(2L, 7L, 6L, 10L, 12L, 
11L, 13L, 14L, 15L, 16L, 17L, 1L, 4L, 3L, 9L, 5L, 8L), .Label = c("ALOCACAO", 
"DI", "DÓLAR", "IBOV", "IDA - GERAL", "IDKA_IPCA2", "IDKA_PRE2", 
"IFIX", "IHFA", "IMA-GERAL", "IMAB", "IMAB - 5", "IMAB - 5 +", 
"IRFM", "IRFM - 1", "IRFM - 1 +", "VÉRTICE"), class = "factor"), 
    percentual = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
    0, 0, 0)), class = "data.frame", row.names = c(NA, -17L))

But I have the following conditions:

  • The obligation, sum of benchmarks = 100%, cannot be left over or missing.
  • Not all benchmarks need to be filled, some may be empty

Abaxio follows the generation of one of the benchs that I made

distribuicaoBenchmark[distribuicaoBenchmark$Benchmarks == "DI", 2] <- runif(1, min = 0, max = 100)

I couldn’t think of two limitations. I thought about using one while (totalInvestido < 100), but in my tests, there was money left over or he was on an eternal loop because I could never satisfy the condition of while.

  • Are the two conditions not the same? The sum of the benchmarks == 100%?

  • Rereading now yes, I will do an Edit!

1 answer

4


For each individual weight, simply select a random number from any distribution supported by the non-negative numbers. Then divide each weight by the sum of all weights:

set.seed(1234)
distribuicaoBenchmark <- runif(17, 0, 100)
distribuicaoBenchmark <- distribuicaoBenchmark/sum(distribuicaoBenchmark)
summary(distribuicaoBenchmark)
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## 0.001085 0.032701 0.069609 0.058824 0.076099 0.105501 
sum(distribuicaoBenchmark)
## [1] 1

To get the weights between 0 and 100, simply multiply distribuicaoBenchmark for 100.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.