什么是以numpy方式获取日志返回的最有效的方式 [英] What is the most efficient way to get log returns in numpy

查看:174
本文介绍了什么是以numpy方式获取日志返回的最有效的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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



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

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

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



我也以相当粗暴的方式访问元素,因为我对生成器函数或numpy内部没有经验。

解决方案

  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.

这篇关于什么是以numpy方式获取日志返回的最有效的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆