scubamut
3/1/2019 - 10:26 AM

ZIPLINE TEMPLATE 1

%config Completer.use_jedi = False

from zipline import run_algorithm
from zipline.api import order, record, symbol, set_symbol_lookup_date, set_commission
from zipline.api import get_datetime, set_slippage, get_open_orders, order_target_percent
from zipline.pipeline import CustomFactor, Pipeline, CustomFilter
from zipline import TradingAlgorithm
from zipline.api import symbols, attach_pipeline, schedule_function, pipeline_output
from zipline.utils.events import date_rules, time_rules
from zipline.pipeline.factors import Returns
import numpy as np
import pandas as pd
from datetime import datetime
import pytz
import ffn#
from fintools import show_return_table, show_annual_returns

# dummy logger
class Log() :
    pass
    def info (self, s) :
        print ('{} INFO : {}'.format(datetime.today().utcnow().replace(tzinfo=pytz.utc),s))
        pass
    def debug (self, s) :
        print ('{} DEBUG : {}'.format(datetime.today().utcnow().replace(tzinfo=pytz.utc)))
        pass
    def warn (self, s) :
        print ('{} WARNING : {}'.format(datetime.today().utcnow().replace(tzinfo=pytz.utc)))
        pass
        
log = Log()

%matplotlib inline
# dummy logger
class Log() :
    pass
    def info (self, s) :
        print ('{} INFO : {}'.format(get_datetime().tz_convert('US/Eastern'), s))
        pass
    def debug (self, s) :
        print ('{} DEBUG : {}'.format(get_datetime().tz_convert('US/Eastern'), s))
        pass
    def warn (self, s) :
        print ('{} WARNING : {}'.format(get_datetime().tz_convert('US/Eastern'), s))
        pass
        
log = Log()
from datetime import datetime, timezone, timedelta
import pytz
 
from zipline.pipeline.loaders import USEquityPricingLoader
from zipline.pipeline import Pipeline
from zipline.pipeline.data import USEquityPricing
from zipline.pipeline.filters import StaticAssets
from zipline.pipeline.engine import SimplePipelineEngine
from fintools.make_pipeline_engine import make_pipeline_engine
 
etfs = [
        # ----------------------------------------- #
        # SPDRS/State Street Global Advisors (SSGA)
         'XLY' , # Select SPDR U.S. Consumer Discretionary
         'XLP' , # Select SPDR U.S. Consumer Staples
         'XLE' , # Select SPDR U.S. Energy
         'XLF' , # Select SPDR U.S. Financials
         'XLV' , # Select SPDR U.S. Healthcare
         'XLI' , # Select SPDR U.S. Industrials
         'XLB' , # Select SPDR U.S. Materials
         'XLK' , # Select SPDR U.S. Technology
         'XLU' , # Select SPDR U.S. Utilities
         ]
 
def make_pipeline(assets):
    pipe = Pipeline(
                    columns={
                        'price': USEquityPricing.close.latest,
                    },
                    screen=StaticAssets(assets)
                    )
    return pipe
 
start = datetime(2016, 1, 5, 0, 0, 0, 0, pytz.utc)
end = datetime(2016, 1, 7, 0, 0, 0, 0, pytz.utc)
# pipeline engine, Equity() assets
assets, engine = make_pipeline_engine(symbols=etfs, bundle='etfs_bundle')
#run pipeline
pipeline_output = engine.run_pipeline(make_pipeline(assets),start,end)
print(pipeline_output[:5])
"""
This is a template algorithm on Zipline for you to adapt and fill in.
"""

from zipline.api import attach_pipeline, pipeline_output, get_datetime
from zipline.utils.events import date_rules, time_rules
from zipline import run_algorithm
from zipline.api import symbols, get_datetime, schedule_function
from zipline.algorithm import TradingAlgorithm
from zipline.utils.events import date_rules, time_rules
from zipline.pipeline import Pipeline
from zipline.pipeline.data import USEquityPricing
from zipline.pipeline.factors import Returns, AnnualizedVolatility
from zipline.pipeline.filters import StaticAssets
import pandas as pd
from datetime import datetime, timezone
import pytz
from fintools.get_DataArray import get_DataArray

def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    # Rebalance every day, 1 hour after market open.
    schedule_function(
        rebalance,
        date_rules.month_end(),
        time_rules.market_open(hours=1)
                                  )

    # Record tracking variables at the end of each day.
    schedule_function(
        record_vars,
        date_rules.every_day(),
        time_rules.market_close(),
    )

    # Create our dynamic stock selector.
    print('ATTACH PIPELINE')
    attach_pipeline(make_pipeline(), 'pipeline')
    print('PIPELINE ATTACHED')

def make_pipeline():
    """
    A function to create our dynamic stock selector (pipeline). Documentation
    on pipeline can be found here:
    https://www.quantopian.com/help#pipeline-title
    """

    etf_universe = StaticAssets(symbols('XLY', 'XLP', 'XLE', 'XLF', 'XLV', 
                                         'XLI', 'XLB', 'XLK', 'XLU'))

 
    WEIGHT1 = 1.0
    WEIGHT2 = 1.0
    WEIGHT3 = 1.0
    WEIGHT4 = 1.0
 
 
    day20_ret = Returns(inputs=[USEquityPricing.close], window_length=21, mask=etf_universe)
    day3mo_ret = Returns(inputs=[USEquityPricing.close], window_length=63, mask=etf_universe)
    day6mo_ret = Returns(inputs=[USEquityPricing.close], window_length=126, mask=etf_universe)
    day1yr_ret = Returns(inputs=[USEquityPricing.close], window_length=252, mask=etf_universe)
 
    volatility = AnnualizedVolatility(mask=etf_universe)
    score = ((WEIGHT1 * day20_ret) + (WEIGHT1 * day3mo_ret) + (WEIGHT3 * day6mo_ret) + (WEIGHT3 * day1yr_ret)) / (
        volatility)
 
    # Factor of yesterday's close price.
    yesterday_close = USEquityPricing.close.latest
    high = USEquityPricing.high.latest
    low = USEquityPricing.low.latest
    open_price = USEquityPricing.open.latest
    close = USEquityPricing.close.latest
    volume = USEquityPricing.volume.latest
 
    pipe = Pipeline(
        columns={
            'Score': score,
            'Day20': day20_ret,
            'high': high,
            'low': low,
            'close': yesterday_close,
            'open_price': open_price,
            'volume': volume,
        },
        screen=etf_universe
    )
    return pipe


def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    print('GET PIPELINE')
    context.output = pipeline_output('pipeline')
    print('PIPELINE OUTPUT')
    print(context.output)

    # These are the securities that we are interested in trading each day.
    context.security_list = context.output.index
    print('SECURITY LIST : ',context.security_list)


def rebalance(context, data):
    """
    Execute orders according to our schedule_function() timing.
    """
    print('REBALANCE - DATE', get_datetime())
    pass


def record_vars(context, data):
    """
    Plot variables at the end of each day.
    """
    pass


def handle_data(context, data):
    """
    Called every minute.
    """
    pass


if __name__ == "__main__":
    
    start = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2013, 1, 10, 0, 0, 0, 0, pytz.utc)
#     end = datetime.today().replace(tzinfo=timezone.utc)
    capital_base = 100000
    
    result = run_algorithm(start = start, end = end, initialize=initialize,\
                capital_base=capital_base,\
                before_trading_start = before_trading_start, 
                bundle = 'etfs_bundle')
    
    print(result[:3])
from zipline.pipeline import CustomFactor, Pipeline, CustomFilter
from zipline import TradingAlgorithm
from zipline.api import symbols, attach_pipeline, schedule_function, pipeline_output
from zipline.utils.events import date_rules, time_rules
from zipline.pipeline.factors import Returns
import numpy as np
import pandas as pd
from datetime import datetime
from zipline import run_algorithm
from zipline.api import order, record, symbol
import pytz
 
class SecurityInList(CustomFactor):  
    inputs = []  
    window_length = 1  
    securities = []
    def compute(self, today, assets, out):  
        out[:] = np.in1d(assets, self.securities)  
 
def initialize(context):
    
#     do NOT import symbols in RESEARCH and use following to define symbol list
#     sec_list = [symbols('SPY'),symbols('VEU'), symbols('SHY'), symbols('TLT'), symbols('AGG')]
    sec_list = symbols ('MDY', 'EFA')
    attach_pipeline(make_pipeline(sec_list, context), 'my_pipeline')
    
    schedule_function(func=rebalance,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(minutes=30))
         
def make_pipeline(sec_list, context):
 
    # Return Factors
    mask = SecurityInList()
    mask.securities = sec_list
    mask = mask.eq(1)
    yr_returns = Returns(window_length=252, mask=mask)
     
    pipe = Pipeline(
        screen = mask,
        columns = {
            'yr_returns': yr_returns
        }
    )
    return pipe
 
def before_trading_start(context, data):
    """
    Called every day before market open.
    """
    context.output = pipeline_output('my_pipeline')
    print (context.output)
    
def rebalance (context, data) :
    #     print (dir(context))
    print (pipeline_output('my_pipeline'))
    pass
 
capital_base = 10000
start = datetime(2015, 1, 1, 0, 0, 0, 0, pytz.utc)
end = datetime(2016, 1, 1, 0, 0, 0, 0, pytz.utc)
 
    
result = run_algorithm(start = start, end = end, initialize=initialize,\
                capital_base=capital_base,\
                before_trading_start = before_trading_start, 
                bundle = 'etfs_bundle')
if __name__ == "__main__":
    start = datetime(2013, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2013, 1, 10, 0, 0, 0, 0, pytz.utc)
    #     end = datetime.today().replace(tzinfo=timezone.utc)
    capital_base = 100000
 
    result = run_algorithm(start=start, end=end, initialize=initialize, \
                           capital_base=capital_base, \
                           before_trading_start=before_trading_start,
                           bundle='etfs_bundle')
 
    print(result[:3])