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:

  1. Write the .pyx file.

    First, we need to import the C log function from the libc namespace. Second, we will apply this function to numbers in a for loop. Finally, we will use the NumPy diff 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.

  2. Plot the log returns.

    Let's download stock price data with matplotlib, again. Apply the Cython logrets function that we just created on the prices and plot the result.

    from matplotlib.finance import quotes_historical_yahoo
    from datetime import date
    import numpy
    import sys
    from log_returns import logrets
    import matplotlib.pyplot
    
    today = date.today()
    start = (today.year - 1, today.month, today.day)
    
    quotes = quotes_historical_yahoo(sys.argv[1], start, today)
    close = numpy.array([q[4] for q in quotes])
    matplotlib.pyplot.plot(logrets(close))
    matplotlib.pyplot.show()

    The resulting plot of the log returns for AAPL is shown in the following screenshot:

    How to do it...

How it works...

We called the C log function from Cython code. The function together with NumPy functions was used to calculate log returns of stocks. This way, we can create our own specialized API containing convenience functions. The nice thing is that our code should perform at or near the speed of C code, while looking more or less like Python code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset