Calling C functions
We can call C functions from Cython. For instance, in this example, we will call the C log
function. This function works on a single number only. Remember that the NumPy
log
function can also work with arrays. We will compute the so-called log returns of stock prices.
How to do it...
We will start by writing some Cython code:
Write the
.pyx
file.First, we need to import the C
log
function from thelibc
namespace. Second, we will apply this function to numbers in afor
loop. Finally, we will use the NumPydiff
function to get the first order difference between the log values in the second step.from libc.math cimport log import numpy def logrets(numbers): logs = [log(x) for x in numbers] return numpy.diff(logs)
Building has been covered in the previous recipes already. We only need to change some values in the
setup.py
file.Plot the log returns.
Let's download stock price data with matplotlib, again. Apply the Cython
logrets
function that we just created on the...