我有一些我在R中编写的代码,我想将其翻译成Python,但我是python的新手,所以需要一些帮助
R代码基本上模拟250个随机法线,然后计算排序的几何平均回报,然后计算最大亏损,它执行10000次然后组合结果,如下所示.
mu <- 0.06
sigma <- 0.20
days <- 250
n <- 10000
v <- do.call(rbind,lapply(seq(n),function(y){
rtns <- rnorm(days,mu/days,sqrt(1/days)*sigma)
p.rtns <- cumprod(rtns+1)
p.rtns.md <- min((p.rtns/cummax(c(1,p.rtns))[-1])-1)
tot.rtn <- p.rtns[days]-1
c(tot.rtn,p.rtns.md)
}))
Run Code Online (Sandbox Code Playgroud)
这是我在Python中的尝试,(如果你可以让它更短/更有说服力/更高效请建议作为答案)
import numpy as np
import pandas as pd
mu = float(0.06)
sigma = float(0.2)
days = float(250)
n = 10000
rtns = np.random.normal(loc=mu/days,scale=(((1/days)**0.5)*sigma),size=days)
rtns1 = rtns+1
prtns = rtns1.cumprod()
totrtn = prtns[len(prtns)-1] -1
h = prtns.tolist()
h.insert(0,float(1))
hdf = pd.DataFrame(prtns)/(pd.DataFrame(h).cummax()[1:len(h)]-1))[1:len(h)]]
Run Code Online (Sandbox Code Playgroud)
这就是我得到的...不太确定是否hdf正确得到p.rtns.md,并且不确定我将如何模拟这10000次.
所有建议将不胜感激......
我不熟悉 R,但我看到可以对 Python 代码进行一些常规改进:
0.06时不带float()around,因为 Python 会推断带小数点的数值是float
h.insert(0,float(1))可以替换为h.insert(0,1.0)[-1],使用 倒数第二项[-2],等等:
totrtn = prtns[-1] -1Python 开发人员通常在单词之间选择下划线或驼峰式。此外,通常最好在变量名称中使用完整的单词,以提高可读性而不是在屏幕上经济。例如,此处的某些变量可以重命名为returnsand total_returnsor totalReturns。
要运行模拟 10000 次,您应该使用for循环:
for i in range(10000):
# code to be repeated 10000 goes in an indented block here
# more lines in the loop should be indented at same level as previous line
# to mark what code runs after the for loop finishes, just un-indent again
h - prtns.tolist()
...
Run Code Online (Sandbox Code Playgroud)