Example #1
0
    def initialize(self, context):
        if self.verbose: print("Starting the robo advisor")

        # Populate Portfolios
        self.all_portfolios = initialize_portfolio(self.verbose)

        # Set Commission model
        self.initialize_commission(country=self.country, platform=self.trading_platform)

        # Set Slippage model
        set_slippage(slippage.FixedSlippage(spread=0.0))  # assume spread of 0

        # Schedule Rebalancing check
        rebalance_check_freq = date_rules.month_end()
        if (self.rebalance_freq == 'daily'): rebalance_check_freq = date_rules.every_day()
        elif (self.rebalance_freq == 'weekly'): rebalance_check_freq = date_rules.week_end()

        if self.verbose: print('Rebalance checks will be done %s' % self.rebalance_freq)
        schedule_function(
            func=self.before_trading_starts,
            date_rule=rebalance_check_freq,
            time_rule=time_rules.market_open(hours=1))

        # record daily weights at the end of each day
        schedule_function(
            func=record_current_weights,
            date_rule=date_rules.every_day(),
            time_rule=time_rules.market_close()
        )
Example #2
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = feature_num
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model = DecisionTreeClassifier(criterion='entropy',
                                           max_depth=feature_num,
                                           random_state=0)
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
Example #3
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = feature_num
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model = SVC(kernel='rbf', tol=1e-3, random_state=0, gamma=0.2, C=10.0, verbose=True)  # 8.05 for SVM model
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(), time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=1))
def initialize(context):
    attach_pipeline(make_pipeline(), 'pipeline')
    #Schedule Functions
    if not IS_LIVE:
        schedule_function(
            trade,
            #date_rules.every_day(),
            #date_rules.week_end(days_offset=1),#0=Fri 1= Thurs
            date_rules.month_end(days_offset=3),
            time_rules.market_close(minutes=30)
        )
        schedule_function(record_vars, date_rules.every_day(), time_rules.market_close())
        schedule_function(cancel_open_orders, date_rules.week_end(days_offset=2), time_rules.market_close())
    
    context.spy = symbol('SPY')  #sid(8554) #SPY
    context.TF_filter = False
    #context.TF_lookback = 60
    #Set number of securities to buy and bonds fund (when we are out of stocks)
    context.Target_securities_to_buy = 15 #10 #15 #2 #1 #5 #10 #5
    
    context.bonds = symbol('IEF') #sid(23870)  #IEF
    context.relative_momentum_lookback = 44 #66 #22 #4 #22 #22 #22 #126 #Momentum lookback
    context.momentum_skip_days = 1
    context.top_n_relative_momentum_to_buy = 10 #15 #10 #15 #1 #5 #5 #10 #5 #Number to buy
    context.stock_weights = pd.Series()
    context.bond_weights = pd.Series()

    context.auto_close = {} #Initialize portfolio auto_close list.
    context.TRACK_ORDERS_ON = False
Example #5
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = feature_num
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model2 = SVC(kernel='rbf',
                         tol=1e-3,
                         random_state=0,
                         gamma=0.2,
                         C=10.0,
                         verbose=True)  # 8.05 for SVM model
    context.model3 = KNeighborsClassifier(
        n_neighbors=feature_num, p=3, metric='minkowski')  # 7.05 for  model
    context.model = DecisionTreeClassifier(criterion='entropy',
                                           max_depth=feature_num,
                                           random_state=0)
    context.model4 = RandomForestClassifier(criterion='entropy',
                                            n_estimators=feature_num,
                                            random_state=1,
                                            n_jobs=2)  # 5.2 for randomforest
    context.model1 = LogisticRegression(random_state=0,
                                        solver='lbfgs',
                                        multi_class='multinomial')
    context.modellist = {
        'SVM': context.model2,
        'KNeighbors': context.model3,
        'DecisionTree': context.model,
        'RandomForest': context.model4,
        'LogisticRegression': context.model1
    }
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
Example #6
0
def initialize(context):
    __build_factor_basic_strategy(context)
    attach_pipeline(make_pipeline(context), 'my_pipeline')
    schedule_function(rebalance,
                      date_rules.week_end(days_offset=0),
                      half_days=True)
    # record my portfolio variables at the end of day
    schedule_function(func=recording_statements,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close(),
                      half_days=True)
    print("initialize over")
    pass
Example #7
0
def initialize(context):
    context.security = sid(8554)  # Trade SPY
    context.model = RandomForestRegressor()

    context.lookback = 3  # Look back 3 days
    context.history_range = 400  # Only consider the past 400 days' history

    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))

    # Trade at the start of every day
    schedule_function(trade, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
Example #8
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = 11
    context.n_components = 6
    context.SP500_symbol = [
        'AAPL', 'ABT', 'ABBV', 'ACN', 'ACE', 'ADBE', 'ADT', 'AAP', 'AES',
        'AET', 'AFL', 'AMG', 'A', 'GAS', 'ARE', 'APD', 'AKAM', 'AA', 'AGN',
        'ALXN', 'ALLE', 'ADS', 'ALL', 'ALTR', 'MO', 'AMZN', 'AEE', 'AAL',
        'AEP', 'AXP', 'AIG', 'AMT', 'AMP', 'ABC', 'AME', 'AMGN', 'APH', 'APC',
        'ADI', 'AON', 'APA', 'AIV', 'AMAT', 'ADM', 'AIZ', 'T', 'ADSK', 'ADP',
        'AN', 'AZO', 'AVGO', 'AVB', 'AVY', 'BHI', 'BLL', 'BAC', 'BK', 'BCR',
        'BXLT', 'BAX', 'BBT', 'BDX', 'BBBY', 'BRK.B', 'BBY', 'BLX', 'HRB',
        'BA', 'BWA', 'BXP', 'BSX', 'BMY', 'BRCM', 'BF.B', 'CHRW', 'CA', 'CVC',
        'COG', 'CAM', 'CPB', 'COF', 'CAH', 'HSIC', 'KMX', 'CCL', 'CAT', 'CBG',
        'CBS', 'CELG', 'CNP', 'CTL', 'CERN', 'CF', 'SCHW', 'CHK', 'CVX', 'CMG',
        'CB', 'CI', 'XEC', 'CINF', 'CTAS', 'CSCO', 'C', 'CTXS', 'CLX', 'CME',
        'CMS', 'COH', 'KO', 'CCE', 'CTSH', 'CL', 'CMCSA', 'CMA', 'CSC', 'CAG',
        'COP', 'CNX', 'ED', 'STZ', 'GLW', 'COST', 'CCI', 'CSX', 'CMI', 'CVS',
        'DHI', 'DHR', 'DRI', 'DVA', 'DE', 'DLPH', 'DAL', 'XRAY', 'DVN', 'DO',
        'DTV', 'DFS', 'DISCA', 'DISCK', 'DG', 'DLTR', 'D', 'DOV', 'DOW', 'DPS',
        'DTE', 'DD', 'DUK', 'DNB', 'ETFC', 'EMN', 'ETN', 'EBAY', 'ECL', 'EIX',
        'EW', 'EA', 'EMC', 'EMR', 'ENDP', 'ESV', 'ETR', 'EOG', 'EQT', 'EFX',
        'EQIX', 'EQR', 'ESS', 'EL', 'ES', 'EXC', 'EXPE', 'EXPD', 'ESRX', 'XOM',
        'FFIV', 'FB', 'FAST', 'FDX', 'FIS', 'FITB', 'FSLR', 'FE', 'FISV',
        'FLIR', 'FLS', 'FLR', 'FMC', 'FTI', 'F', 'FOSL', 'BEN', 'FCX', 'FTR',
        'GME', 'GPS', 'GRMN', 'GD', 'GE', 'GGP', 'GIS', 'GM', 'GPC', 'GNW',
        'GILD', 'GS', 'GT', 'GOOGL', 'GOOG', 'GWW', 'HAL', 'HBI', 'HOG', 'HAR',
        'HRS', 'HIG', 'HAS', 'HCA', 'HCP', 'HCN', 'HP', 'HES', 'HPQ', 'HD',
        'HON', 'HRL', 'HSP', 'HST', 'HCBK', 'HUM', 'HBAN', 'ITW', 'IR', 'INTC',
        'ICE', 'IBM', 'IP', 'IPG', 'IFF', 'INTU', 'ISRG', 'IVZ', 'IRM', 'JEC',
        'JBHT', 'JNJ', 'JCI', 'JOY', 'JPM', 'JNPR', 'KSU', 'K', 'KEY', 'GMCR',
        'KMB', 'KIM', 'KMI', 'KLAC', 'KSS', 'KRFT', 'KR', 'LB', 'LLL', 'LH',
        'LRCX', 'LM', 'LEG', 'LEN', 'LVLT', 'LUK', 'LLY', 'LNC', 'LLTC', 'LMT',
        'L', 'LOW', 'LYB', 'MTB', 'MAC', 'M', 'MNK', 'MRO', 'MPC', 'MAR',
        'MMC', 'MLM', 'MAS', 'MA', 'MAT', 'MKC', 'MCD', 'MCK', 'MJN', 'MMV',
        'MDT', 'MRK', 'MET', 'KORS', 'MCHP', 'MU', 'MSFT', 'MHK', 'TAP',
        'MDLZ', 'MON', 'MNST', 'MCO', 'MS', 'MOS', 'MSI', 'MUR', 'MYL', 'NDAQ',
        'NOV', 'NAVI', 'NTAP', 'NFLX', 'NWL', 'NFX', 'NEM', 'NWSA', 'NEE',
        'NLSN', 'NKE', 'NI', 'NE', 'NBL', 'JWN', 'NSC', 'NTRS', 'NOC', 'NRG',
        'NUE', 'NVDA', 'ORLY', 'OXY', 'OMC', 'OKE', 'ORCL', 'OI', 'PCAR',
        'PLL', 'PH', 'PDCO', 'PAYX', 'PNR', 'PBCT', 'POM', 'PEP', 'PKI',
        'PRGO', 'PFE', 'PCG', 'PM', 'PSX', 'PNW', 'PXD', 'PBI', 'PCL', 'PNC',
        'RL', 'PPG', 'PPL', 'PX', 'PCP', 'PCLN', 'PFG', 'PG', 'PGR', 'PLD',
        'PRU', 'PEG', 'PSA', 'PHM', 'PVH', 'QRVO', 'PWR', 'QCOM', 'DGX', 'RRC',
        'RTN', 'O', 'RHT', 'REGN', 'RF', 'RSG', 'RAI', 'RHI', 'ROK', 'COL',
        'ROP', 'ROST', 'RLD', 'R', 'CRM', 'SNDK', 'SCG', 'SLB', 'SNI', 'STX',
        'SEE', 'SRE', 'SHW', 'SPG', 'SWKS', 'SLG', 'SJM', 'SNA', 'SO', 'LUV',
        'SWN', 'SE', 'STJ', 'SWK', 'SPLS', 'SBUX', 'HOT', 'STT', 'SRCL', 'SYK',
        'STI', 'SYMC', 'SYY', 'TROW', 'TGT', 'TEL', 'TE', 'TGNA', 'THC', 'TDC',
        'TSO', 'TXN', 'TXT', 'HSY', 'TRV', 'TMO', 'TIF', 'TWX', 'TWC', 'TJX',
        'TMK', 'TSS', 'TSCO', 'RIG', 'TRIP', 'FOXA', 'TSN', 'TYC', 'UA', 'UNP',
        'UNH', 'UPS', 'URI', 'UTX', 'UHS', 'UNM', 'URBN', 'VFC', 'VLO', 'VAR',
        'VTR', 'VRSN', 'VZ', 'VRTX', 'VIAB', 'V', 'VNO', 'VMC', 'WMT', 'WBA',
        'DIS', 'WM', 'WAT', 'ANTM', 'WFC', 'WDC', 'WU', 'WY', 'WHR', 'WFM',
        'WMB', 'WEC', 'WYN', 'WYNN', 'XEL', 'XRX', 'XLNX', 'XL', 'XYL', 'YHOO',
        'YUM', 'ZBH', 'ZION', 'ZTS'
    ]

    context.model2 = SVC(kernel='rbf',
                         tol=1e-3,
                         random_state=0,
                         gamma=0.2,
                         C=10.0,
                         verbose=True)  # 8.05 for SVM model
    context.model3 = KNeighborsClassifier(
        n_neighbors=feature_num, p=3, metric='minkowski')  # 7.05 for  model
    context.model5 = DecisionTreeClassifier(criterion='entropy',
                                            max_depth=feature_num,
                                            random_state=0)
    context.model4 = RandomForestClassifier(criterion='entropy',
                                            n_estimators=feature_num,
                                            random_state=1,
                                            n_jobs=2)  # 5.2 for randomforest
    context.model1 = LogisticRegression(random_state=0,
                                        solver='lbfgs',
                                        multi_class='multinomial')
    context.model = KMeans(n_clusters=8,
                           init='k-means++',
                           max_iter=300,
                           tol=1e-4,
                           random_state=0)
    #context.model = DBSCAN(eps=0.2,min_samples=3,metric='euclidean')
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    context.times = 0
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
Example #9
0
def initialize(context):
    print("hello world")
    attach_pipeline(make_pipeline(), 'my_pipeline')
    schedule_function(rebalance,
                      date_rules.week_end(days_offset=0),
                      half_days=True)
Example #10
0
def initialize(context, date_limits, verbose, symbols):
    print "in initialize"
    start_time_initialize = time.time()
    context.verbose = verbose
    # Define rebalance frequency
    context.scheduler = SCHEDULER
    if context.scheduler  == 'Daily':
        schedule_function(rebalance)
    if context.scheduler  == 'Weekly':
        schedule_function(rebalance, date_rules.week_end())
    elif context.scheduler  == 'Monthly':
        schedule_function(rebalance, date_rules.month_end())

    context.date_limits = date_limits

    # Set slippage model and commission model
    set_slippage(slippage.FixedSlippage(spread=SLIPPAGE_SPREAD))
    set_commission(commission.PerShare(cost=COMMISSION_COST_PER_SHARE, min_trade_cost=COMMISSION_MIN_TRADE_COST))

    context.symbols = symbols
    symbol_membership = utils.get_underlying(context.symbols, sep = ' / ')
    symbol_membership.index = context.symbols
    context.symbol_membership = symbol_membership
    if REFERENCE_GROUP_SYMBOL['Cash'] in context.symbol_membership.index:
        context.symbol_membership.loc[REFERENCE_GROUP_SYMBOL['Cash']] = 'Cash'
    
    asset_keys = utils.get_asset_keys_db()
    if RETS_READER is not None:
        returns = utils.get_returns_db(RETS_READER, context.symbols, asset_keys)

    else:
        returns = None
    if VOL_READER is not None and CORR_READER is not None:
        volatility = utils.get_volatilities_db(VOL_READER, context.symbols, asset_keys)
        correlations = utils.get_correlations_db(CORR_READER, context.symbols, asset_keys)

    else:
        volatility, correlations = [None]*2
    data_dict = {'returns': returns, 'volatility': volatility, 'correlations': correlations}
    context.data_dict = data_dict


    #print returns
    #print ''
    #print ''
    #print volatility
    #print ''
    #print ''
    #print correlations
    #print asfasfasf

    # Group
    group = "Top"
    if len(sys.argv) >= 3 and 'ASSETTYPE=' in sys.argv[2]:
        group = sys.argv[2].split('=')[-1]
    params_dict = {}
    params_dict.update(data_dict)
    params_dict.update(PARAMS['params'])

    ag_name = 'Top'
    if group == 'Equity':
        ag_name = PARAMS['params']['group']
    context.group = AbstractGroup(context.symbols, name = ag_name, start=START_DATE_BT_STR, end = END_DATE_BT_STR, verbose = verbose, strategy_id = ID, scheduler = SCHEDULER , **params_dict)
    #print "DEBUG [context.group.updated_symbols] : \n", context.group.updated_symbols
    context.round_weights = 4
    context.ref_group_df = pd.DataFrame(pd.Series({v:k for k,v in REFERENCE_GROUP_SYMBOL.items()}))
    context.active_orders = []

    if verbose:
        print "INFO: Initialize took %f s." % (time.time() - start_time_initialize)
def initialize(context):
    context.has_ordered = False
    set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0))
    set_slippage(slippage.FixedSlippage(spread=0.0)) 
    schedule_function(func0, date_rules.week_end())