且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是以numpy方式获取日志返回的最有效的方式

更新时间:2023-11-25 15:03:16

  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:])])

相当于

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

np.log 将每个值的日志记录在 ar np.diff 取每个连续的值之间的差异。


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.

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.

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

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.