We can integrate Cython and NumPy code in the same way that we can integrate Cython and Python code. Let's go through an example that analyzes the ratio of up days (days on which a stock closes higher than the previous day) for a stock. We will apply the formula for binomial proportion confidence. You can refer to http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval for more information. This indicates how significant the ratio is.
This section describes how we can use Cython with NumPy. To demonstrate this, perform the following steps:
.pyx
file.Let's write a .pyx
file that contains a function to calculate the ratio of up days and associated confidence. First, this function computes the differences of the prices. Then, we count the number of positive differences, giving us a ratio for the proportion of up days. Finally, we apply the formula for the confidence from the Wikipedia page in the introduction.
import numpy def pos_confidence(numbers): diffs = numpy.diff(numbers) n = float(len(diffs)) p = len(diffs[diffs > 0])/n confidence = numpy.sqrt(p * (1 - p)/ n) return (p, confidence)
setup.py
file.We will use the setup.py
file
from the previous example, as the template. There are some obvious things that need to be changed, such as the name of the .pyx
file.
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [Extension("binomial_proportion", ["binomial_proportion.pyx"])] setup( name = 'Binomial proportion app', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
After building, we can use the
Cython module from the previous step by importing. We will write a Python program that downloads stock price data with matplotlib. Then, we will apply the confidence
function to the close prices.
from matplotlib.finance import quotes_historical_yahoo from datetime import date import numpy import sys from binomial_proportion import pos_confidence #1. Get close prices. 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]) print pos_confidence(close)
The output of the program for AAPL is shown as follows:
(0.56746031746031744, 0.031209043355655924)