Long Short Coding

Zipline

from zipline.api import( symbol, get_datetime,order_target_percent,schedule_function,

                        date_rules, time_rules, attach_pipeline, pipeline_output,

                        set_commission,set_slippage,get_open_orders,cancel_order,

                        order_target,order,get_order

                       )

from zipline.errors import HistoryWindowStartsBeforeData    

from zipline.finance import commission,slippage

from zipline.finance.slippage import FixedBasisPointsSlippage 

from zipline.pipeline import Pipeline, CustomFactor

from zipline.pipeline.data import EquityPricing

from zipline.pipeline.factors import SimpleMovingAverage

from zipline.errors import HistoryWindowStartsBeforeData     

from zipline.pipeline import Pipeline, CustomFilter    

from zipline.finance.slippage import FixedSlippage   

from zipline.finance import commission   

from zipline.finance.slippage import FixedBasisPointsSlippage 

from zipline.pipeline.factors import DailyReturns   


Data manipulation

import pandas as pd

import numpy as np



def initialize(context):



    context.universe =  [symbol('TITAN'),symbol('SUNPHARMA'), symbol('MARUTI'),

      symbol('TATAMOTORS'),symbol('BPCL'),symbol('BAJFINANCE'),

      symbol('HDFCBANK'),symbol('ASIANPAINT'),

      symbol('TCS'),symbol('RELIANCE'),symbol('INFY'),symbol('KOTAKBANK'),

      symbol('WIPRO'),symbol('HEROMOTOCO'),symbol('AXISBANK'),

      symbol('POWERGRID'),symbol('UPL'),symbol('TITAN'),symbol('MARUTI'),

      symbol('YESBANK'),symbol('INDUSINDBK'),symbol('ICICIBANK'),

      symbol('GAIL'),symbol('TECHM'),symbol('BHARTIARTL'),symbol('VEDL'),symbol('NTPC'),

      symbol('HCLTECH'),symbol('HINDUNILVR'),symbol('ONGC'),symbol('TATASTEEL'),

      symbol('LT'),symbol('COALINDIA'),symbol('JSWSTEEL'),symbol('GRASIM'),symbol('SBIN')]

    

    context.set_slippage(FixedBasisPointsSlippage(basis_points = 3))    



    schedule_function(strategy,

                    date_rules.every_day(),

                    time_rules.market_open(hours=0, minutes=30)) 

    

    schedule_function(placetrade, date_rules.every_day(), 

                        time_rules.market_close(hours=0, minutes=10))



    attach_pipeline(make_pipeline(context), name='my_pipeline')



def filter_universe(universe):

    class FilteredUniverse(CustomFilter):

        inputs = ()

        window_length = 1

        def compute(self,today,assets,out):

            in_universe = [asset in universe for asset in assets]

            out[:] = in_universe

    return FilteredUniverse()    



def technical_factor(lookback, indicator_fn, indicator_lookback):

    class TechnicalFactor(CustomFactor):

        inputs = [EquityPricing.close]

        def compute(self,today,assets,out,close_price):

            signals = np.apply_along_axis(indicator_fn, 0, close_price, indicator_lookback)

            out[:] = signals

    return TechnicalFactor(window_length = lookback)



def up_days(px, lookback):

    return np.sum(np.where(np.diff(px) > 0, 1, 0))



def make_pipeline(context):    

    # Initialize the pipeline

    pipe = Pipeline()

    

    # Construct Factors

    plusdays = technical_factor(30, up_days, 0)

    pipe.add(plusdays, 'plus')

    nifty200 =  filter_universe(context.universe)

    pipe.set_screen(nifty200)       

    return pipe



def strategy(context,data):

    # Access results using the name passed to attach_pipeline.

    n=5

    pipeline_results = pipeline_output('my_pipeline')

    context.longselected_stocks = pipeline_results.sort('plus', ascending=False).iloc[:n] 

    context.shortselected_stocks = pipeline_results.sort('plus', ascending=True).iloc[:n] 



    weight = 1/10

    

    for security in context.longselected_stocks.index: 

            #print(context.longselected_stocks) 

            #print(context.shortselected_stocks)             

            order_target_percent(security, weight)

    

    for security in context.shortselected_stocks.index:

            order_target_percent(security, -weight)  

    

def placetrade(context,data):      

    for security in context.portfolio.positions:

        order_target(security,0)

          

       

This is an issue/ feature of how Python 2.7 handles integer division. Replace the weight = 1/10 to weight = 1.0/10 and it should work

Thank you sir.

Dear Sir,



In the above program, in pipeline



plusdays = technical_factor(30, up_days, 0)



actually I want to look for 30 '1 minute bar'  to calculate plus days. But I think it is taking only daily data eventhough I am applying it in NSE Minute data.



How to solve this?

Pipeline methods do a lot of number crunching across the entire datasets. They are implemented for daily data only. If you want to use minute data you have to separately query the assets using data.history method. One scheme will be to screen your universe using pipeline to a small set, and then use data.history on these assets to get minute data.

Sir,



Not able to get in coding. Please help me.



def strategy(context,data):

  

    iddata = data.history(context.universe,'close',5,'1m')

    updays = np.sum(np.where(np.diff(iddata) > 0, 1, 0))   

    

    print(updays)



I am not getting updays for each stock. It gives sum of all stocks.

I want to get for each stock and I would like to sort based on updays values.

Please refer to pandas and numpy docs to make yourself more familiar with them - this is very important for customizing strategies on Blueshift (or on any Pythonic platform). You are applying the function over whole dataframe - so you should not be surprised that it gives sum over all stocks. You need to apply it along the index axis, like below.



def up_days(px):

    return np.sum(np.where(np.diff(px) > 0, 1, 0)) 



def strategy(context,data):

    prices = data.history(context.universe,"close",5,"1m")

    df = prices.apply(up_days, axis=0)

    print(df)

    print(df.loc[context.universe[0]])

Thank you Sir. I will become more familier with pandas and numpy.