1

Let's say I have a list of countries that I am investing in:

Angola  Croatia  Denmark  Germany ...

How can I randomize weights to these countries that all add up to 100%, essentially - I am looking to run an optimization test on my investments:

Angola  Croatia  Denmark  Germany ...
1.3%    3.8%     4.6%     7.5%    ... (sum equals 100%)

The logic behind randomization is quite simple, but I was wondering if there is an easy way to do it? My current logic being, assign a random number to all of them, take the sum of all randoms, take the number assigned divided by total.

How would I calculate these weights properly and add a new row with these weights using Pandas DataFrame? How would I set up a for-all statement?

sgerbhctim
  • 3,420
  • 7
  • 38
  • 60

1 Answers1

2

It's possible to achieve this without using numpy or pandas. You can simply generate N random numbers using the random package and then normalize them (divide each number by the sum of all generated numbers). This will generate a list of numbers in the [0, 1] interval. If you need to scale them to the [0, 100] interval, just multiply the numbers by 100.

Example:

>>> import random
>>> n = 10
>>> weights = [random.random() for _ in range(n)]
>>> sum_weights = sum(weights)
>>> weights = [100*w/sum_weights for w in weights]
>>> print(weights)
[9.341865975454088,
 12.351871555212776,
 11.613836128975514,
 9.37242716105095,
 7.74809967908834,
 9.239611881353285,
 5.432249328415935,
 11.384334820466387,
 13.436859772362507,
 10.07884369762022]
Matheus Portela
  • 2,420
  • 1
  • 21
  • 32