Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cython Numpy EWA
#1
Hi Everyone,

I'm working on a back testing EWA script based on python and Cython(Still new to it) for speed.
almost all of my code in almost fully in Cython speed but i cannot seem to figure out this section of the code and how to get it fully Cythonic Big Grin :
@cython.boundscheck(False) # turn off bounds-checking for entire function
@cython.wraparound(False)  # turn off negative index wrapping for entire function
def ewma(Gen, winsowSize):
    cdef int n, arr
    cdef int windows = winsowSize
    cdef double alpha
    cdef np.ndarray w0 ,p ,w 
    cdef np.ndarray arrs = np.array([y for y in Gen], dtype=object)
    cdef Py_ssize_t arr_shape = arrs.shape[0]
    cdef np.ndarray allArrays = np.array([], dtype='double')
    try:   
        for arr in range(arr_shape):
            alpha=2/(windows+1)
            # Coerce x to an array
            # arr = np.array(arr)
            n = arrs[arr].size
            
            # Create an initial weight matrix of (1-alpha), and a matrix of powers
            # to raise the weights by
            w0 = np.ones(shape=(n,n)) * (1-alpha)
          
            p = np.vstack([np.arange(i,i-n,-1) for i in range(n)])
            # Create the weight matrix
            w = np.tril(w0**p,0)
            # Calculate the ewma

            allArrays = np.concatenate([allArrays, np.dot(w, arrs[arr][::np.newaxis]) / w.sum(axis=1)])        
        return allArrays
    except ZeroDivisionError:
        pass
This function gets a yielded generator(Gen), this has to do with the overflow error when giving it a big array.

The fact there are still python based numpy's (w0, p, w ) makes the code runs slow.
tried to declare them with cdef np.ndarray w0, p, w but this does not help. Wall

How can i get this code to be fully Cython???
Many thanks in advance!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020