在numpy中获取日志返回的最有效方法是什么

时间:2022-09-23 17:09:33

What is the fastest and most elegant solution to building a sequence of log returns?

构建一系列日志返回的最快和最优雅的解决方案是什么?

The problem is mainly around mapping a function that takes the i'th and (i+1)'th elements as inputs for every element in the array.

问题主要在于映射一个函数,该函数将第i个和第(i + 1)个元素作为数组中每个元素的输入。

for a function and simple array I can define the log returns as follows:

对于函数和简单数组,我可以定义日志返回如下:

import numpy as np
ar = np.random.rand(10)
f_logR = lambda ri, rf: np.log(rf) - np.log(ri)

logR = np.asarray([f_logR(ar[i], rf) for i,rf in enumerate(ar[1:])])

However, I am building a list from individual numpy elements and then converting it back into a numpy array again.

但是,我正在从单个numpy元素构建一个列表,然后再将它转换回numpy数组。

I am also accessing the elements in a fairly brutish way as I have little experience with generator functions or numpy internals.

我也是以相当野蛮的方式访问这些元素,因为我对生成器函数或numpy内部有很少的经验。

1 个解决方案

#1


f_logR = lambda ri, rf: np.log(rf) - np.log(ri)
logR = np.asarray([f_logR(ar[i], rf) for i,rf in enumerate(ar[1:])])

is equivalent to

相当于

logR = np.diff(np.log(ar))

np.log takes the log of every value in ar, and np.diff takes the difference between every consecutive pair of values.

np.log获取ar中每个值的日志,np.diff取每个连续值对之间的差值。

#1


f_logR = lambda ri, rf: np.log(rf) - np.log(ri)
logR = np.asarray([f_logR(ar[i], rf) for i,rf in enumerate(ar[1:])])

is equivalent to

相当于

logR = np.diff(np.log(ar))

np.log takes the log of every value in ar, and np.diff takes the difference between every consecutive pair of values.

np.log获取ar中每个值的日志,np.diff取每个连续值对之间的差值。