I have been puzzling over how to vectorize the following function:
tradeplNonVectorized[signals_, periodPL_] :=
Module[{tradePL = {}, PL = 0},
For[i = 2, i < Length[signals - 1], i++,
If[signals[[i]] == 0,
If[signals[[i - 1]] != 0, PL = PL + periodPL[[i + 1]];
AppendTo[tradePL, PL];
PL = 0;],
If[signals[[i - 1]] == signals[[i]] || signals[[i - 1]] == 0,
PL = PL + periodPL[[i + 1]];, AppendTo[tradePL, PL];
PL = periodPL[[i + 1]];]]];
tradePL]
Which works as follows:
signals = {0, 1, 0, -1, -1, -1, 1, 1, 0, 0};
periodPL = {0, 0, -0.0150, 3.0000, 0.9850, -0.0150, 1.0000,
1.0000, -3.0150, 0};
tradePL = tradeplNonVectorized[signals, periodPL]
{2.985,1.97,-2.015}
What the function is trying to do is group and total the periodic PLs into trades, which span periods of varying lengths.
A trade at period t is triggered by a signal at period t-1, and terminates when the sign of the signal changes. In the given example, there are three (pairs of) sign changes in signals, and therefore three trades. I want to group and add the periodPL values so that the total for each group is the PL for the corresponding trade.
I am actually trying to find a vectorized solution in Matlab and Python too, so bonus points for anyone who can provide those also!
{0, 1 ,0, 1, ...}
? That is, there are zeros in between ones so that the sign doesn't actually change? $\endgroup$signals
? If it's always one zero in between a 1 and a -1 or a -1 and a 1, then this will be pretty easy to do. Otherwise, some post-processing ofsignals
first will be necessary (at least as I'm envisioning the problem). In addition, suppose thatperiodPL
was non-zero in the first two entries. Would we include these as part of the first sum (that resulted in 2.985)? (After trying something, your code says the answer is no, but I want to make sure.) $\endgroup$