0

I'm a Python and Numpy newbie...and I'm stuck. I'm trying to create a new numpy array from the log returns of elements in an existing numpy array (i.e. new array = old array(with ln(x/x-1)). I was not using Pandas dataframe because I plan to incorporate the correlations of the returns (i.e. "new array) into a large monte carlo simulation. Open to suggestions if this is not the right path.

This is the closest result I found in stackflow search, but it is not working: What is the most efficient way to get log returns in numpy

My guess is that I need to pass in the elements of the existing array but I thought using arrays and functions within Numpy was the whole benefit of moving away from Pandas series and Python base code. Appreciate help and feedback!

code link(I'm new so stackflow won't let me embed images): https://i.sstatic.net/wkf56.png

1 Answer 1

1

Numpy as log function, you can apply it directly to an array. The return value will be a new array of the same shape. Keep in mind that the input should be an array of positive values with dtype == float.

import numpy
old_array = numpy.random.random(5.) * 10.

new_array = numpy.log(old_array / (old_array - 1.))

print type(old_array)
# <type 'numpy.ndarray'>
print old_array.dtype
# float64
print old_array
# [ 8.56610175  6.40508542  2.00956942  3.33666968  8.90183905]
print new_array
# [ 0.12413478  0.16975202  0.68839656  0.35624651  0.11916237]
Sign up to request clarification or add additional context in comments.

4 Comments

I receive an output that looks like when I used your recommendation:array([[-inf], [-inf], [-inf], [-inf], [-inf], [-inf],
log(0.) == -inf, the output makes me think old_array is full of zeros.
Please see the link in my first post to a picture of the code I am using. I am seeing values for "old array" (aka cl_1_array).
@tdubya123, I've updated my answer a little. Your link is not that useful because there is no way to check the type of dtype of the array you're using. It sounds like you just need to debug your code. numpy functions take arrays as inputs and return arrays, so you should have no issues "creating new numpy arrays". If you're still having problems consider posting a MCVE. I've found 80% of problems are solved in the process of creating an MCVE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.