Ejemplo n.º 1
0
def run_after_days(data_table, params):
    '''
    ** NO default params
    days (int): Number of trading days to wait before starting 
    '''
    _check_params(params, ['days'])
    return RunAfterDays(**params)
Ejemplo n.º 2
0
def weigh_specificed(data_table, params):
    '''
    ** NO default params
    weights (dict): target weights -> ticker: weight
    '''
    _check_params(params, ['weights'])
    return WeighSpecified(**params)
Ejemplo n.º 3
0
def capital_flow(data_table, params):
    '''
    ** NO default params 
    amount (float): Amount of adjustment
    '''
    _check_params(params, ['amount'])
    return CapitalFlow(**params)
Ejemplo n.º 4
0
def run_after_date(data_table, params):
    '''
    ** NO default params
    date (string): a specific date.
        - format: 'yyyy-mm-dd'
    '''
    _check_params(params, ['date'])
    return RunAfterDate(**params)
Ejemplo n.º 5
0
def run_on_date(data_table, params):
    '''
    ** NO default params
    dates: List of dates to run Algo on. 
        - format: ['yyyy-mm-dd', 'yyyy-mm-dd', 'yyyy-mm-dd'...]
    '''
    _check_params(params, ['dates'])
    return RunOnDate(**params)
Ejemplo n.º 6
0
def run_every_n_periods(data_table, params):
    '''
    ** NO default params
    n (int): Run each n periods
    offset (int): Applies to the first run. If 0, this algo will run the
        first time it is called.
    '''
    _check_params(params, ['n', 'offset'])
    return RunEveryNPeriods(**params)
Ejemplo n.º 7
0
def select_these(data_table, params):
    '''
    default params
    include_no_data=False

    ** NO default params
    tickers (list): List of tickers to select.
    '''
    _check_params(params, ['tickers'])
    return SelectThese(**params)
Ejemplo n.º 8
0
def select_n(data_table, params):
    '''
    ** NO default params
    n (int): select top n items.

    default params
    sort_descending=True,
    all_or_none=False
    '''
    _check_params(params, ['n'])
    return SelectN(**params)
Ejemplo n.º 9
0
def target_volatility(data_table, params):
    '''
    ** NO default params
    target_volatility,

    default params
    lookback=pd.DateOffset(months=3),
    lag=pd.DateOffset(days=0),
    covar_method='standard',
    annualization_factor=252
    '''
    _check_params(params, ['target_volatility'])
    return TargetVol(**params)
Ejemplo n.º 10
0
def pte_rebalance(data_table, params):
    '''
    ** NO default params
    PTE_volatility_cap,
    target_weights,

    default params
    lookback=pd.DateOffset(months=3),
    lag=pd.DateOffset(days=0),
    covar_method='standard',
    annualization_factor=252
    '''
    _check_params(params, ['PTE_volatility_cap', 'target_weights'])
    return PTE_Rebalance(**params)
Ejemplo n.º 11
0
def select_momentum(data_table, params):
    '''
    ** NO default params
    n (int): select first N elements

    Args:
        * n (int): select first N elements
        * lookback (DateOffset): lookback period for total return
            calculation
        * lag (DateOffset): Lag interval for total return calculation
        * sort_descending (bool): Sort descending (highest return is best)
        * all_or_none (bool): If true, only populates temp['selected'] if we
            have n items. If we have less than n, then temp['selected'] = [].
    '''
    _check_params(params, ['n'])
    return SelectMomentum(**params)
Ejemplo n.º 12
0
def runComposite(params):
    _check_params(params=params,
                  list_to_check=['data_table', 'strategy_list', 'strategy'])

    start_date = params['data_table'].date[0]
    end_date = params['data_table'].date[-1]
    commission = None
    if params.get('start_date'):
        start_date = params['start_date']
    if params.get('end_date'):
        end_date = params['end_date']
    if params.get('commissions'):
        commission = params['commissions']

    comp = RunBacktest(*params['strategy_list'])
    data_table = getDataTable({
        "asset": [{
            "name": v.prices.columns[0],
            "df": v.prices,
            "freq": "D"
        } for v in comp.values()]
    })
    data_table, comp = composite({
        'data_table': data_table,
        'strategy': params['strategy']
    })

    trade = Backtest(
        **{
            'strategy':
            comp,
            'data':
            data_table.asset.loc[(data_table.asset.index >= start_date)
                                 & (data_table.asset.index <= end_date)],
            'initial_capital':
            1000000.0,
            'commissions':
            commission,
            'progress_bar':
            False
        })
    result = RunBacktest(trade)
    if params.get('riskfree_rate'):
        result.set_riskfree_rate(params['riskfree_rate'])

    return {'result': result, 'strategy': trade}
Ejemplo n.º 13
0
def composite(params):
    '''
    construct strategy composite for portfolio
    using bt.core.Strategy
    Args: 
        params (dict): containing keys `data`, `strategy` 
            data_table (dict): follow the rules of data.py
            strategy (list): list of dictionary, containing all params that each strategy needs

    --------------------------------------------------
    Strategy(class):
        Args:
        * name (str): Strategy name
        * algos (list): List of Algos to be passed into an AlgoStack
        * children (dict, list): Children - useful when you want to create
            strategies of strategies

        Attributes:
        * stack (AlgoStack): The stack
        * temp (dict): A dict containing temporary data - cleared on each call
            to run. This can be used to pass info to other algos.
        * perm (dict): Permanent data used to pass info from one algo to
            another. Not cleared on each pass.
    '''
    _check_params(params, ['data_table', 'strategy'])

    name = uuid.uuid4()
    data_table = getDataTable(params['data_table'])

    StrategyList = []
    for stra in params['strategy']:
        pkg = importlib.import_module('backtest_tools.backtest.strategy')
        func = getattr(pkg, stra['class'])
        func = run_always(func)

        inputs = {}
        inputs['data_table'] = data_table
        inputs['params'] = {}
        if stra.get('params'):
            inputs['params'] = stra['params']

        StrategyList.append(func(**inputs))

    s = Strategy(**{'name': name, 'algos': StrategyList, 'children': None})
    return data_table, s
Ejemplo n.º 14
0
def runPortfolio(params):
    _check_params(params=params, list_to_check=['data_table', 'strategy'])

    data_table, comp = composite({
        'data_table': params['data_table'],
        'strategy': params['strategy']
    })

    start_date, end_date = data_table.date[0], data_table.date[-1]
    commission = None
    if params.get('start_date'):
        start_date = params['start_date']
    if params.get('end_date'):
        end_date = params['end_date']
    if params.get('commissions'):
        commission = params['commissions']

    trade = Backtest(
        **{
            'strategy':
            comp,
            'data':
            data_table.asset.loc[(data_table.asset.index >= start_date)
                                 & (data_table.asset.index <= end_date)],
            'initial_capital':
            1000000.0,
            'commissions':
            commission,
            'progress_bar':
            False
        })
    result = RunBacktest(trade)
    if params.get('riskfree_rate'):
        result.set_riskfree_rate(params['riskfree_rate'])

    return {'result': result, 'strategy': trade}