我有一个可变长度的数组D,
我想创建一个循环,根据循环次数对应的D值执行求和
即。第5次循环运行将使用我的数组中的第5个值。
我的代码是:
period = 63 # can be edited to an input() command for variable periods.
Mrgn_dec = .10 # decimal value of 10%, can be manipulated to produce a 10% increase/decrease
rtn_annual = np.arange(0.00,0.15,0.05) # creates an array ??? not sure if helpful
sig_annual = np.arange(0.01,0.31,0.01) #use .31 as python doesnt include the upper range value.
#functions for variables of daily return and risk.
rtn_daily = (1/252)*rtn_annual
sig_daily = (1/(np.sqrt(252)))*sig_annual
D=np.random.normal(size=period) # unsure of range to use for standard distribution
for i in range(period):
r=(rtn_daily+sig_daily*D)
我试图这样做,所以我的for循环乘以每一步的D值。
因此D对于句点的每个值都有一个随机值,其中句点代表一天。
因此,对于第8天,我希望r的循环值乘以数组中的第8个值,是否有办法选择特定值?
numpy.cumprod命令是否提供任何帮助,我不确定它是如何工作的,但有人建议它可以帮助解决问题。
答案 0 :(得分:-1)
现在,D只是一个标量。
我建议您阅读https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.normal.html以了解参数。
如果您将其更改为:
D=np.random.normal(mean,stdev,period)
您将获得 1D数组 期间样本数,其中mean和stdev是分布的均值和标准差。然后将循环更改为:
for i in range(period):
r=(rtn_daily+sig_daily*D[i])
编辑:当我第一次阅读代码时,我不知道自己在想什么。这对我来说是一个非常糟糕的读物。
回顾代码,需要做一些事情来使它工作。
第一:
rtn_annual = np.arange(0.00,0.15,0.05)
sig_annual = np.arange(0.01,0.31,0.01)
这两条线需要固定,以便得到的基质的尺寸相同。
然后:
rtn_daily = (1/252)*rtn_annual
需要进行更改,以免将所有内容归零 - 更改1到1.0或浮动(1)
最后:
r=(rtn_daily+sig_daily*D)
需要更改为:
r=(rtn_daily+sig_daily*D[i])
我不确定原始代码的意图,但似乎循环是不必要的,您可以将循环更改为:
r=(rtn_daily+sig_daily*D[day])
哪天是你试图孤立的日子。
答案 1 :(得分:-1)
您可以通过选择索引来选择迭代对象中的元素(例如代码中的D)。如:
for i in range(period):
print D[i]
但是在你的代码中,rtn_daily和sig_daily的形状不同,我假设你想在rtn的每个位置添加sig_daily乘以D [i]。所以试试这个:
# -*- coding:utf-8 -*-
import numpy as np
period = 63 # can be edited to an input() command for variable periods.
Mrgn_dec = .10 # decimal value of 10%, can be manipulated to produce a 10% increase/decrease
rtn_annual = np.repeat(np.arange(0.00,0.15,0.05), 31) # creates an array ??? not sure if helpful
sig_annual = np.repeat(np.arange(0.01,0.31,0.01), 3) #use .31 as python doesnt include the upper range value.
#functions for variables of daily return and risk.
rtn_daily = (float(1)/252)*rtn_annual
sig_daily = (1/(np.sqrt(252)))*sig_annual
D=np.random.normal(size=period) # unsure of range to use for standard distribution
print D
for i in range(period):
r=(rtn_daily[i]+sig_daily[i]*D[i])
print r
最后,如果你使用的是python2,则除法方法是整数,所以这意味着1/252会给你零结果。
a = 1/252 >-- 0
要解决此问题,您可以尝试使其浮动:
rtn_daily = (float(1)/252)*rtn_annual