I need to implement the following in python: For a given discrete time series Zt (t=0 to T), find smallest t such that:
$c\sum_{s=0}^t e^{[k(Zt-Zs)+m(t-s)]} >= \frac{p*}{1-p*} $
where c,k,m are constants and P* is given by
$\int_0^{0.5} \frac{(1-2y)e^{-d/y}}{(1-y)^{1+d}y^{1-d}}dy=\int_{0.5}^{p*} \frac{(2y-1)e^{-d/y}}{(1-y)^{1+d}y^{1-d}}dy $
where d is another constant(something to be optimized)
I need to implement this for each row of an array Z = input 2d array of shape (N,w) I implemented a loop version:
i implemented the sum in equation 1 above utilizing the fact
$ e^{[k(Zt-Zs)+m(t-s)]} = \frac{e^{kZt+mt}}{e^{kZs+ms}} $
hence
$\sum_{s=0}^t e^{[k(Zt-Zs)+m(t-s)]} =e^{kZt+mt}*\sum_{s=0}^t\frac{1}{e^{kZs+ms}} $ which is reflected in use of cumsum in code below
def f(z):
return ((1-2*z)*np.exp(-d/z))/(((1-z)**(1+d))*(z**(1-d)))
lhs=integrate.quad(f,0,0.5)
def rhs(p):
return integrate.quad(-f,0.5, p)
p_star= fsolve(rhs-lhs,0.75) # will depend on time series only indrectly when d will be optimized
for i in np.arange(N):
z=Z[i,:]
main = np.exp (kz+m*np.arange(w))
cumsum_t=np.cumsum(1/main)
final_sum= main*cumsum_t
t_solution= # index i where final_sum[i]> p_star/(1-p_star)) # not implemented yet
Is there any way I can vectorize this for Z? In this case N is ~400,000 so vectorization would really help. The function f(z) will be fine with vector inputs but I dont think the function rhs will be fine as it uses integration.