'Generate the feasible list of combinations
I have used the following function to generate fund combinations in a portfolio. For example, I have four funds in the portfolio. The incremental change of each fund is 5. The range of allocations for each fund is between 0 and 100.
import itertools
from collections import Counter
def sums(n,r):
solutions = []
c = {k: v for k, v in zip(range(r), [0]* r)}
for tpl in itertools.combinations_with_replacement(range(r), n-1):
d = c.copy()
d.update(Counter(tpl))
solutions.append(tuple(map(lambda x: x*INCR, d.values()) ))
return solutions
funds = 4
INCR = 5
Comb = [t for t in sums(int(100//INCR), funds) if min(t) >= 0]
len(Comb)
It works fine until the number of funds get larger. It takes forever to get results for 15 funds because the number of combinations become huge. For a portfolio of 15 funds, I actually have range limitations for each fund. For example, the range for the first 10 is between 0 and 25. The range for the last 5 is between 0 and 10.
How can I apply the range of each fund into the function to avoid generating the huge number of total combinations? Thanks for any inputs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|