Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # cython: language_level=3
- # cython: profile=True
- # cythonize -a -b test_cy.pyx
- # python setup.py build_ext --inplace
- import numpy as np
- cimport cython
- cimport numpy as np
- np.import_array()
- @cython.wraparound(False)
- @cython.boundscheck(False)
- @cython.cdivision(True)
- cdef tp_sl_back_test(double[:, :] data, double tp, double sl):
- cdef double balance = 100
- cdef double balance_copy
- cdef Py_ssize_t i
- cdef int right = 0
- cdef int total = 0
- cdef double entry_price
- cdef double close_price
- cdef double high_price
- cdef double low_price
- cdef double tp_price
- cdef double sl_price
- for i in xrange(data.shape[0]):
- balance_copy = balance
- entry_price = data[i, 0]
- high_price = data[i, 1]
- low_price = data[i, 2]
- close_price = data[i, 3]
- tp_price = entry_price + ((entry_price * 0.01) * tp)
- sl_price = entry_price - ((entry_price * 0.01) * sl)
- if (sl_price < low_price) and (tp_price > high_price):
- pass
- elif sl_price >= low_price:
- close_price = sl_price
- elif tp_price <= high_price:
- close_price = tp_price
- else:
- close_price = sl_price
- balance *= 0.9996
- balance *= close_price / entry_price
- balance *= 0.9996
- if balance_copy < balance:
- right += 1
- total += 1
- else:
- total += 1
- return balance, right, total
- @cython.wraparound(False)
- @cython.boundscheck(False)
- cpdef tp_sl_loop(np.ndarray[np.float64_t, ndim=2] data_np, np.ndarray[np.float64_t, ndim=2] tp_sl_mash, str pair):
- cdef int n = tp_sl_mash.shape[0]
- cdef int i
- cdef int right
- cdef int total
- cdef double[:, ::1] data = np.ascontiguousarray(data_np)
- cdef double tp
- cdef double sl
- cdef double balance
- cdef np.ndarray[np.float64_t, ndim=1] X = np.zeros(n)
- cdef np.ndarray[np.float64_t, ndim=1] Y = np.zeros(n)
- cdef np.ndarray[np.float64_t, ndim=1] Z = np.zeros(n)
- cdef np.ndarray[np.float64_t, ndim=2] tp_sl_list = np.zeros((n, 3))
- for i in xrange(n):
- tp = tp_sl_mash[i, 0]
- sl = tp_sl_mash[i, 1]
- balance, right, total = tp_sl_back_test(data, tp, sl)
- X[i] = tp * 100
- Y[i] = sl * 100
- Z[i] = balance
- tp_sl_list[i, 0] = tp
- tp_sl_list[i, 1] = sl
- tp_sl_list[i, 2] = balance
- return X, Y, Z, tp_sl_list
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement