Greetings all, I have two series of data: daily raw stock price returns (positive or negative floats) and trade signals (buy=1, sell=-1, no trade=0).
The raw price returns are simply the log of today's price divided by yesterday's price:
log(p_today / p_yesterday)
An example:
raw_return_series = [ 0.0063 -0.0031 0.0024 ..., -0.0221 0.0097 -0.0015]
The trade signal series looks like this:
signal_series = [-1. 0. -1. -1. 0. 0. -1. 0. 0. 0.]
To get the daily returns based on the trade signals:
daily_returns = [raw_return_series[i] * signal_series[i+1] for i in range(0, len(signal_series)-1)]
These daily returns might look like this:
[0.0, 0.00316, -0.0024, 0.0, 0.0, 0.0023, 0.0, 0.0, 0.0] # results in daily_returns; notice the 0s
I need to use the daily_returns series to compute a compounded returns series. However, given that there are 0 values in the daily_returns series, I need to carry over the last non-zero compound return "through time" to the next non-zero compound return.
For example, I compute the compound returns like this (notice I am going "backwards" through time):
compound_returns = [(((1 + compounded[i + 1]) * (1 + daily_returns[i])) - 1) for i in range(len(compounded) - 2, -1, -1)]
and the resulting list:
[0.0, 0.0, 0.0023, 0.0, 0.0, -0.0024, 0.0031, 0.0] # (notice the 0s)
My goal is to carry over the last non-zero return to the accumulate these compound returns. That is, since the return at index i is dependent on the return at index i+1, the return at index i+1 should be non-zero. Every time the list comprehension encounters a zero in the daily_return series, it essentially restarts.