1

I'm looking to implement a trading strategy working with two moving averages. A slow (60 day SMA) and a fast (10 day SMA). In general, whenever the price is above the slow MA I want to be long, with the exception that if the price is more than 5% above the slow MA, and moves below the fast MA I will sell, and buy again when/if the price crosses above the fast ma.

The position and signals for the slow MA is trivial:

df["slowma"] = df["AdjClose"].rolling(60).mean()
df['positions'] = 0.0
df['positions'] = np.where(df["AdjClose"] > df['slowma'], 1.0, 0.0)
df['signal'] = df['positions'].diff()

The fast MA crossing, conditional of the price being more than 5% above, is a bit trickier, since I'm only interested in generating a buy signal if I previously had a sell signal.

df["fastma"] = df["AdjClose"].rolling(10).mean()
df['positions_fast'] = 0.0
df['positions_fast'] = np.where(df["AdjClose"] > df['fastma'], 1.0, 0.0)

Adding a "logical and", and checking whether the price is above the 5% more than the slow MA doesn't help me, since this check should only be done when the fast MA signal happens. Any help that could point me in the right direction would be greatly appreciated.

Edit: Here is some testdata and an image that hopefully somewhat describes what I'm trying to achieve. Please do not pay attention to the fact that the slow and fast MA are not averages at all. I typed it in manually.

Graph The idea is that we only get a sell signal the second time the price crosses under the fast ma.

For this data I changed the 5% threshold to 50%. Data

Here is data in python format:

close = [1,5,8,12,19,24,26,25,20,25,30,35,40,35,30,25,40,45,50,55,50,40,30,20]
slow_ma = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
fast_ma = [5, 6, 8, 9, 12, 15, 19, 24, 22, 24, 27, 31, 35, 39, 34, 30, 33, 37, 41, 46, 50, 50, 46, 40]
rpanai
  • 12,515
  • 2
  • 42
  • 64
darkdark
  • 249
  • 1
  • 3
  • 16
  • 4
    Can you add some sample data and expected outputs to this question? – Scott Boston Nov 20 '18 at 13:48
  • Hi @ScottBoston. Sure made up some data - and a chart. – darkdark Nov 20 '18 at 18:57
  • Your example is not reproducible. Have a look at [mcve](https://stackoverflow.com/help/mcve). Then even the explanation is not that clear: at the beginning you only talk about slowMA and then you want to use fast MA. Could you please review your question? Then you can post a pic adding markers when you want to sell/buy. – rpanai Nov 21 '18 at 11:41

0 Answers0