Back to Community
New to the platform

Hi,

I'm struggling to get my first algorithm running, the goal is simple:

- ranking stocks on past 60 days return by mean/var  
- enter long on top 300 stocks and short on lowest 300

I don't understand what is going on. I would like to add that I watched tutorials and read the API reference but don't seem able to run a code written by myself on the algorithm builder.

Thank you! :)

Loading notebook preview...
Notebook previews are currently unavailable.
4 responses

Hi Quentin,

I don't understand what is going on.

Let me try my best to explain.

An immediate answer is that function np.average raises TypeError: unsupported operand type(s) for /: 'BoundColumn' and 'int'.

    inputs = [USEquityPricing.close]  
    window_length = 60  

    factor=np.average(inputs)/np.var(inputs)  

Why? Roughly speaking because it expects an array of numbers to take an average of, but you are giving it an array of objects of type BoundColumn.

A more general answer is that once you manage to fix that bug (probably by taking a closer look at built-in factors DailyReturns and SimpleMovingAverage), you will encounter a set of the other ones. There is a tab "Build Errors" in the Quantopian IDE, I suggest that you start there.

You did not ask for advice, but here it is: do not rush to build an algorithm. Take your time to understand it's building blocks, and only then assemble them all together. After you've researched your idea and concluded that it is worth doing at all.

Hope it helps :)

Thank you for the timely answer and the advice which I particularly appreciate, I ended up being able to run
I attached the code as it might help others. There is definitely room for improvement x)

Clone Algorithm
5
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
"""
This is a template algorithm on Quantopian for you to adapt and fill in.
"""
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import QTradableStocksUS
import numpy as np
import quantopian.optimize as opt

class MeanVar(CustomFactor):
    # Pre-declare inputs and window_length
    inputs = [USEquityPricing.close,]
    window_length = 60

    # Compute market cap value
    def compute(self, today, assets, out, close):
        factor=np.nanmean(close[0:60],axis=0)/np.nanvar(close[0:60],axis=0)
        factor[factor==np.nan]=np.median(np.nanmedian(factor))
        out[:] = factor

def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    algo.attach_pipeline(make_pipeline(),'test')
    #algo.attach_pipeline(risk_loading_pipeline,'risk_factors')
    
    
    schedule_function(func=rebalance,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(hours=0, minutes=1),
                      half_days=True
                      )
    

def before_trading_start(context,data):
    
    context.pipeline_data=algo.pipeline_output('test')
    #context.risk_loadings=algo.pipeline_output('risk_factors')
    
    
    
def make_pipeline():
    
    universe=QTradableStocksUS()
    
    
    
    factors=MeanVar()

    
    longs=factors.top(300, mask=universe)
    shorts=factors.bottom(300, mask=universe)
    
    long_short_screen= (longs | shorts)
    
    pipe= Pipeline(
        columns = {
            'factors': factors,
            'longs':longs,
            'shorts': shorts,
            
            },
            screen = long_short_screen
        
        )
    
    return pipe
    
    
def rebalance(context, data):
    
    pipeline_data= context.pipeline_data
    #risk_loadings= context.risk_loadings
    
    objective= opt.MaximizeAlpha(pipeline_data.factors)
    constraints= []
    
    constraints.append(opt.MaxGrossExposure(1))
    constraints.append(opt.DollarNeutral())
    
    #constraints.append(
     #   opt.PositionConcentration.with_equal_bounds(
      #      min=2/600
       #     max=2/600
        #    ))
    algo.order_optimal_portfolio(
        objective=objective,
        constraints=constraints
        )
There was a runtime error.

Can someone provide a simple example of "BoundColumn" in this sense?

There are 194,002 web pages on it. I haven't checked all of them but the trend looked like "blah blah foo yadda ..." as my mind can't seem to gain any traction except from specific examples, thanks. Maybe consider including an unbound column example also, eh.

depends on what you try to do.
my guess is that you are trying to create a custom factor?