我想以網格方式為兩個以上的資產生成資產權重,以便總和為一。例如,我可以將numpy 的 linespace與兩個資產一起使用,但不確定如何處理超過 2 個資產:
import numpy as np
# get 3 weight configurations for 2 assets, that sum up to one
[np.array([w, 1-w]) for w in np.linspace(0, 1, 3)]
>[array([0., 1.]),
array([0.5, 0.5]),
array([1., 0.])]
# get 4 weight configurations for 2 assets, that sum up to one
[np.array([w, 1-w]) for w in np.linspace(0, 1, 4)]
>[array([0., 1.]),
array([0.33333333, 0.66666667]),
array([0.66666667, 0.33333333]),
array([1., 0.])]
# get 5 weight configurations for 2 assets, that sum up to one
[np.array([w, 1-w]) for w in np.linspace(0, 1, 5)]
> [array([0., 1.]),
array([0.25, 0.75]),
array([0.5, 0.5]),
array([0.75, 0.25]),
array([1., 0.])]
更新: meshgrid 時尚我的意思是權重不是隨機的,而是遵循網格模式,例如,對于 3 個資產,這些將是可能的配置。當然,粒度取決于num此類函式的引數中請求的權重配置數量(相當于numpy#linspace):
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]
[0.333333, 0.333333, 0.333333]
[0.333333, 0.666666, 0]
[0.666666, 0.333333, 0]
[0, 0.333333, 0.666666]
[0, 0.666666, 0.333333]
[0.333333, 0, 0.666666]
[0.666666, 0, 0.333333]
uj5u.com熱心網友回復:
這是一個適合您的示例的解決方案。
使用整數磁區!
from sympy.utilities.iterables import partitions
from more_itertools import distinct_permutations
# if you don't want to install more_itertools:
# set(itertools.permutations( ... ))
# is equivalent but less efficient than
# more_itertools.distinct_permutations( ... )
from collections import Counter # not really needed; just for .elements()
def weights(dim, grid):
for p in partitions(grid, m=dim):
p[0] = dim - sum(p.values())
yield from (distinct_permutations(x / grid for x in Counter(p).elements()))
print( list(weights(2, 2)) )
# [(0.0, 1.0), (1.0, 0.0), (0.5, 0.5)]
print( list(weights(2, 4)) )
# [(0.0, 1.0), (1.0, 0.0), (0.25, 0.75), (0.75, 0.25), (0.5, 0.5)]
print( list(weights(2, 3)) )
# [(0.0, 1.0), (1.0, 0.0), (0.333, 0.667), (0.667, 0.333)]
print( list(weights(3, 2)) )
# [(0.0, 0.0, 1.0), (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (0.0, 0.5, 0.5), (0.5, 0.0, 0.5), (0.5, 0.5, 0.0)]
for x,y,z in weights(3, 3):
print('{:0.2f},{:0.2f},{:0.2f}'.format(x,y,z))
# 0.00,0.00,1.00
# 0.00,1.00,0.00
# 1.00,0.00,0.00
# 0.00,0.33,0.67
# 0.00,0.67,0.33
# 0.33,0.00,0.67
# 0.33,0.67,0.00
# 0.67,0.00,0.33
# 0.67,0.33,0.00
# 0.33,0.33,0.33
相關檔案:
- 關于整數磁區的維基百科;
- sympy.utilities.iterables.partitions ;
- itertools.permutations ;
- more_itertools.distinct_permutations ;
- 集合.計數器.元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377844.html
上一篇:HackerRank:將節點插入已排序的雙向鏈表-Kotlin
下一篇:獲取每個節點的最大樹深度
