python-3.x 条件For循环

xj3cbfub  于 2023-03-04  发布在  Python
关注(0)|答案(1)|浏览(164)

我正在用Python创建一个for循环来生成随机数(权重)。但是,我想确保我对某些股票有一个最小的敞口。例如,我想确保股票B和C将占投资组合的至少80%。也就是说,我需要为投资组合生成一组随机权重,这样股票B和C将占投资组合的至少80%。C将占投资组合的至少80%。
我的代码如下,但它似乎并没有真正生成权重〉80%的随机投资组合

ar = np.array([0,1,1,0])

number_of_portfolios = 5

tickers = ['A','B','C','D'] 

portfolio_weights = []

for portfolio in range (number_of_portfolios):
   weights = np.random.random_sample(len(tickers))
    weights = np.round((weights / np.sum(weights)),3)
    if sum(ar * weights) > 0.8:
        portfolio_weights.append(weights)

谢谢大家!
我期望得到5个不同权重的投资组合,股票代码C和C至少占投资组合的80%。

qv7cva1a

qv7cva1a1#

你的代码有一个小问题,那就是它相信它每次都有输出,但实际上没有。
为了更精确的概率得到0.8或更多的2个变量是严重的偏差与非常小的概率。所以你可以反复调用猜测随机获得输出。我相信它需要平均70 - 92猜测,在最坏的情况下,它可以上升到130+尝试。
希望我解释清楚。
验证码:

import numpy as np
ar = np.array([0,1,1,0])
number_of_portfolios = 5

tickers = ['A','B','C','D'] 

portfolio_weights = []
found=0
count=0
while count<5:
    weights = np.random.random_sample(len(tickers))
    weights = np.round(weights / np.sum(weights),3)
    if sum(ar * weights) > 0.8:
        portfolio_weights.append(weights)
        count+=1
print("obtained output is :",portfolio_weights)

如果你有兴趣知道平均需要多少次尝试,运行这个来查看尝试的次数。

import numpy as np
ar = np.array([0,1,1,0])
number_of_portfolios = 5

tickers = ['A','B','C','D'] 

portfolio_weights = []
found=0
count=0
tries=0

while count<5:
    weights = np.random.random_sample(len(tickers))
    weights = np.round(weights / np.sum(weights),3)
    tries+=1
    if sum(ar * weights) > 0.8:
        portfolio_weights.append(weights)
        count+=1
print("obtained output is :",portfolio_weights)
print("number of tries it took to yeild result :",tries)

如果这有助于留下一个赞成票是赞赏的。

相关问题