Hi Community,

I've been really struggling to finish this backtest but apparently it seems there's an error on my code. I have checked Nans (even though i have explicitly rejected them on my make_pipeline function) and i have also check the data type introduced into my portfolio weights (context.weights variable) but i can't find out the solution. I would really appreciate you feedback.

Thanks a lot!!

Axel

Clone Algorithm

4

Loading...

There was an error loading this backtest.
Retry

Backtest from
to
with
initial capital

Cumulative performance:

Algorithm
Benchmark

Custom data:

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 |

""" This is a template algorithm on Quantopian for you to adapt and fill in. """ from quantopian.algorithm import attach_pipeline, pipeline_output from quantopian.pipeline import Pipeline from quantopian.pipeline.data import Fundamentals from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.filters import QTradableStocksUS import quantopian.optimize as opt import quantopian.algorithm as algo import pandas as pd bottom_percentile = 20 up_percentile = 80 def initialize(context): """ Called once at the start of the algorithm. """ # Check cointegrated pairs every month schedule_function(rebalance, date_rules.month_start(), time_rules.market_open()) 'schedule_function(rebalance)' # Record tracking variables at the end of each day. schedule_function(record_vars,date_rules.month_start(),time_rules.market_open()) # Create our dynamic stock selector. attach_pipeline(make_pipeline(), 'my_pipeline') def make_pipeline(): # Define a tradeable universe. Universe = QTradableStocksUS() # Create basic indicators for each stock, such as its sector # classification, country of domicile, last price and market_cap sector = Fundamentals.morningstar_sector_code.latest #Let's modify all of our valuation ratios to be LVRB # Price to earnings ratio PE = Fundamentals.pe_ratio.latest PE = PE.zscore(mask=PE.percentile_between(1,99)) #EVCFO EVCFO =Fundamentals.enterprise_value/(Fundamentals.cfo_per_share.latest*Fundamentals.shares_outstanding.latest) EVCFO = EVCFO.zscore(mask=EVCFO.percentile_between(1,99)) # Free cash flow FCF = 1.0/(Fundamentals.free_cash_flow.latest) FCF = FCF.zscore(mask=FCF.percentile_between(1,99)) # Price to sales PS = Fundamentals.ps_ratio.latest PS = PS.zscore(mask=PS.percentile_between(1,99)) factor = (PE+EVCFO+PS+FCF)/4.0 Universe = (PE.notnull() & EVCFO.notnull() & PS.notnull() & FCF.notnull()& QTradableStocksUS()) longs = factor.percentile_between(0,bottom_percentile,mask=Universe) shorts = factor.percentile_between(up_percentile,100,mask=Universe) return Pipeline( columns = { 'sector': sector, 'factor': factor, 'longs':longs, 'shorts':shorts }, screen=(longs|shorts) ) def rebalance(context, data): """ Execute orders according to our schedule_function() timing. """ context.dataset = pipeline_output('my_pipeline') 'remove possible NANS' context.dataset.dropna() 'Store our securities in a context variable and create and integer to get the total amount' 'TAKE INTO ACCOUNT THAT THE NUMBER OF LONG AND SHORT' context.longs = context.dataset.loc[context.dataset['longs'] == True].index.tolist() context.shorts = context.dataset.loc[context.dataset['shorts'] == True].index.tolist() context.securities = context.longs + context.shorts context.N = len(context.securities) 'Create weights according the pb ratio value, +50% longs -50% shorts' 'longs' context.ll = context.dataset.loc[context.longs,'factor'] 'context.ll = context.ll.multiply(0.5/sum(context.ll))' context.ll = pd.Series(0.5/len(context.longs), index= context.ll.index) 'shorts' context.ss = context.dataset.loc[context.shorts,'factor'] 'context.ss = context.ss.multiply(-0.5/sum(context.ss))' context.ss = pd.Series(-0.5/len(context.shorts), index = context.ss.index) 'Create an unique list with all securities that have to traded.' context.weights = context.ll.append(context.ss) 'before doing the portfolio allocation, retrieve the current portfolio.positions' context.current_positions = context.portfolio.positions print('Number of active positions: '+ str(len(context.current_positions))) 'retrieve the equities that are not longer on the trading list.' context.closing_positions = set(context.current_positions)-set(context.weights.index.tolist()) context.closing_positions = pd.Series(0.0, index = context.closing_positions) allocate(context,data,context.closing_positions) print('Number of positions to close'+str(len(context.closing_positions.index.tolist()))) 'Allocate the portfolio with the current weights' allocate(context,data,context.weights) pass def record_vars(context, data): """ Plot variables at the end of each day. """ num_longs = len(context.longs) num_shorts = len(context.shorts) record(longs = num_longs, shorts = num_shorts, number_of_positions = len(context.portfolio.positions)) record(portfolio_cash = context.portfolio.cash, leverage = context.account.leverage) pass def allocate(context, data, weights): # Set objective to match target weights as closely as possible, given constraints. # opt.TargetWeights takes as input a dictionary/series with assets as keys/index and weights as values. # Let's try how opt.MaximezeAlpha works # selected MaximizeAlpha because we believe our combined factor # ranking to be proportional to expected returns. This routine # will optimize the expected return of our algorithm, going # long on the highest expected return and short on the lowest. if len(weights.index) !=0: objective = opt.TargetWeights(weights) # Define constraints constraints = [] #constraints.append(opt.MaxGrossExposure(1.0)) algo.order_optimal_portfolio( objective=objective, constraints=constraints, )