from zipline.pipeline import Pipeline
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,
record,
order_target,
)
import pandas as pd
import numpy as np
from zipline.pipeline import Pipeline, CustomFactor
from zipline.pipeline.data import EquityPricing
from zipline.pipeline.factors import SimpleMovingAverage
from zipline.errors import HistoryWindowStartsBeforeData
'''
A function to define things to do at the start of the strategy
'''
def initialize(context):
The context variables can be accessed by other methods
context.long_securities = [
symbol('DIVISLAB'),
symbol('SUNPHARMA'),
symbol('MARUTI'),
symbol('AMARAJABAT'),
symbol('BPCL'),
symbol('BAJFINANCE'),
symbol('HDFCBANK'),
symbol('ASIANPAINT'),
symbol('TCS'),
symbol('RELIANCE')
]
schedule_function(strategy,
date_rules.month_end(days_offset=0),
time_rules.market_close(hours=0, minutes=5))
attach_pipeline(make_pipeline(context), name='my_pipeline')
def make_pipeline(context):
Initialize the pipeline
pipe = Pipeline()
Construct Factors
Get the data for past 20 days
currentprice = EquityPricing.close.latest
sma_65 = SimpleMovingAverage(inputs=[EquityPricing.close], window_length=65)
Register outputs
pipe.add(currentprice, 'cmp')
pipe.add(sma_65, 'sma_65')
Momentum = currentprice/sma_65
Pick the top stocks ranked by Momentum
Momentum_rank = Momentum.percentile_between(98, 100)
pipe.set_screen(Momentum_rank)
return pipe
def strategy(context,data):
Access results using the name passed to attach_pipeline
.
pipeline_results = pipeline_output('my_pipeline')
mom = pd.DataFrame()
mom['cmp1'] = pipeline_results['cmp']
mom['65m'] = pipeline_results['sma_65']
context.long_securities = mom.loc[mom.loc[:,'cmp1'] > mom.loc[:,'65m']].index
weight = compute_weights(context)
for security in context.long_securities:
order_target_percent(security, weight)
Exit positions which are not part of long_securities
for security in context.portfolio.positions:
if (security not in context.long_securities):
order_target_percent(security, 0)
def compute_weights(context):
Set the allocations to equal weights for each long positions
num_of_security = len(context.long_securities)
return 1.0/num_of_security
I want to run the program only on the 10 stocks which i have initialised. But it runs on entire NSE in Quantra blueshift backtesting.