Back to Community
I need help with my pipeline

I'm experimenting a bit with the pipeline and I can't seem to be able to sort values.

In this code I have a very simple algorithm: I will buy the stocks that have had the greatest percentage return the previous day. However, I do not seem to be able to sort my pipleline the way I want.

To check if my sorting is correct, every day in my rebalance function I check the actual percentage change by calling:

print data.history(security,"close", 3, "1d").iloc[:2].pct_change()

When I look in the log out put I see the following percentage changes:
2011-01-03 00:00:00+00:00 0.024726
2011-01-03 00:00:00+00:00 0.006965
2011-01-03 00:00:00+00:00 0.014212
2011-01-03 00:00:00+00:00 0.034572

The sorting has not been made, what have I done wrong here?

Thanks!

Clone Algorithm
1
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 585126d0c76f7b48092acc47
There was a runtime error.
2 responses

The problem is your choice of columns to sort on. You are sorting on the 'top' column. When you use the 'percentile_between' method from a factor it returns a filter NOT another factor. 'top' will be the results of that filter which will be a column of True and False values. You are simply sorting on the True and False values. I believe what you really want is to sort on the return values.

So, add a column for the 'returns' in the pipeline definition and then just sort on that column. It looks like you are trying to return the securities in the highest 1% of previous days returns. Then in the 'before_trading_start' method take the 5 securities with the lowest returns (you have ascending = True). To do that, first set a screen in your pipeline definition to return only the 'top' securities. Then in the 'before_trading_start' function sort by the returns.

Attached is an updated algorithm with these changes.

Clone Algorithm
1
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 585149b1ee8d8363d0d97582
There was a runtime error.

Thank you Dan!!!