I want to create a simple trading system signal table with a dataframe such as:
Close buy sell
2011-01-31 50 0 0
2011-02-28 40 1 0
2011-03-31 50 0 0
2011-04-30 80 0 -1
2011-05-31 60 1 0
2011-06-30 50 1 0
2011-07-31 20 0 0
2011-08-31 30 0 -1
The signals are generated in a following fashion:
df['buy'] = np.where( <condition> , 1, 0 )
The sell
column is created in the same way.
The issue is the double buy signal on 2011-06-30, right after a previous one on 2011-05-31.
2011-05-31 60 1 0
2011-06-30 50 1 0
How can I prevent a new buy ( == 1 ) signal before it is closed with -1 in the df['sell']
column?
Well, once in a need of something more complex, than a trivial numpy
vectorised / broadcast / conditional operation alike the stated np.where( <condition> , 1, 0 )
one has to implement some custom-specific function, to handle those additional features, where Finite-State-Automata may well serve for such purposes.
Simply said, your conditions have grown beyond the expressivity of simple vectorised/broadcast matrix operations, the Trade-Management sub-system has started to have an internal-, a SEQ-behaviour and some additional rules for it's internal -transition(s) and -transition-restrictions.
One could hardly expect the general, universal tools, the numpy
-matrices and pandas
-DataFrame instances are, to be over-designed to support such problem-domain specific functionalities so as to prototype algo-trading strategy simulations.
Better choose some trading-specific tools to suit such need, or expect to have to implement a SEQ-behaviour iterator-function, that would facilitate the needed logic ( none of the smart numpy vectorised / broadcasting expressions or pandas one-liner will suffice here anymore ).
Scope?
for those really interested in a rapid prototyped Trading Strategy example, using a FSA-based implementation method, check the simplicity of such system design + built-in ( script-based ) automated conformance-testing capability + line numbers for an estimate of the code-span ( definitely not anumpy
SLOC ):