Skip to content
Advertisement

Momentum portfolio(trend following) quant simulation on pandas

I am trying to construct trend following momentum portfolio strategy based on S&P500 index (momthly data)

I used Kaufmann’s fractal efficiency ratio to filter out whipsaw signal (http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/)

I succeeded in coding, but it’s very clumsy, so I need advice for better code.

Strategy

  1. Get data of S&P 500 index from yahoo finance
  2. Calculate Kaufmann’s efficiency ratio on lookback period X (1 , if close > close(n), 0)
  3. Averages calculated value of 2, from 1 to 12 time period —> Monthly asset allocation ratio, 1-asset allocation ratio = cash (3% per year)

I am having a difficulty in averaging 1 to 12 efficiency ratio. Of course I know that it can be simply implemented by for loop and it’s very easy task, but I failed.

I need more concise and refined code, anybody can help me?

a['meanfractal'] bothers me in the code below..

JavaScript

Advertisement

Answer

You could simplify further by storing the values corresponding to p in a DF rather than computing for each series separately as shown:

JavaScript

Then, you could assign the repeating operations to a variable which reduces the re-computation time.

JavaScript

Resulting plot obtained:

JavaScript

Image

Note: If speed is not a major concern, you could perform the operations via the built-in methods present in pandas instead of converting them into it’s corresponding numpy array values.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement