コード例 #1
0
ファイル: buyhold.py プロジェクト: mikimaus78/trending
def run(config, testing, tickers, _filename):

    # Backtest information
    title = ['Buy and Hold Example on %s' % tickers[0]]
    initial_equity = 500000.0
    start_date = datetime.datetime(2020, 1, 1)

    todays_month = int(datetime.datetime.today().strftime("%m"))
    todays_day = int(datetime.datetime.today().strftime("%d"))
    end_date = datetime.datetime(2020, todays_month, todays_day)

    # Use the Buy and Hold Strategy
    events_queue = queue.Queue()
    strategy = BuyAndHoldStrategy(tickers[0], events_queue)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title)
    results = backtest.start_trading(testing=testing, filename=_filename)
    return results
コード例 #2
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Moving Average Crossover Example on AAPL: 100x300']
    initial_equity = 10000.0
    start_date = datetime.datetime(2000, 1, 1)
    end_date = datetime.datetime(2014, 1, 1)

    # Use the MAC Strategy
    events_queue = queue.Queue()
    strategy = MovingAverageCrossStrategy(tickers[0],
                                          events_queue,
                                          short_window=50,
                                          long_window=100)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        title=title,
        benchmark=tickers[1],
    )
    results = backtest.start_trading(testing=testing)
    # results = backtest.start_trading(testing=Fa)

    return results
コード例 #3
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Accelerating momentum for SPY: 1m, 3m, 6m > 0']
    initial_equity = 10000.0
    start_date = datetime.datetime(2000, 1, 1)
    end_date = datetime.datetime(2014, 1, 1)

    # Use the MAC Strategy
    events_queue = queue.Queue()
    strategy = AcceleratingMomentumStrategy(tickers[0], events_queue)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        title=title,
        benchmark=tickers[1],
    )
    results = backtest.start_trading(testing=testing)
    # results = backtest.start_trading(testing=Fa)

    return results
コード例 #4
0
def run(config, testing, tickers, _filename, initial_equity):
    # Backtest information
    title = ['Buy and Hold Example on %s' % tickers[0]]

    start_date = datetime.datetime(2014, 1, 1)

    todays_month = int(datetime.datetime.today().strftime("%m"))
    todays_day = int(datetime.datetime.today().strftime("%d"))
    end_date = datetime.datetime(2019, todays_month, todays_day)

    # Use the Buy and Hold Strategy
    events_queue = queue.Queue()
    strategy = BuyAndHoldStrategy(tickers[0], events_queue)

    ticker_weights = {"AZN.L": 1}
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title,
                              adjusted_or_close='adj_close',
                              position_sizer=position_sizer)

    results = backtest.start_trading(testing=testing, filename=_filename)
    return results
コード例 #5
0
def run(config, testing, tickers, safe_asset, filename):
    # Backtest information
    title = ['Accelerating momentum for SPX, BONDS, MSCI: 1m, 3m, 6m > 0']
    initial_equity = 10000.0
    start_date = datetime.datetime(2000, 1, 1)
    end_date = datetime.datetime(2019, 7, 1)

    # Use the MAC Strategy
    events_queue = queue.Queue()
    strategy = AcceleratingMomentumStrategy(tickers, safe_asset, events_queue)

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    ticker_weights = {"SPY": 1, "VUSTX": 1, "VINEX": 1}
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        position_sizer=position_sizer,
        title=title,
        benchmark=tickers[1],
    )
    results = backtest.start_trading(testing=testing)
    # results = backtest.start_trading(testing=Fa)

    return results
コード例 #6
0
def run(config, testing, tickers, _filename, initial_equity):
    # Backtest information
    title = ['Buy and Hold monthly rebalance Example on %s' % tickers[0]]

    year_start = 2016
    year_end = 2019

    start_date = datetime.datetime(year_start, 12, 28)

    todays_month = int(datetime.datetime.today().strftime("%m"))
    todays_day = int(datetime.datetime.today().strftime("%d"))
    end_date = datetime.datetime(year_end, todays_month, todays_day)

    years = list(range(year_start, year_end + 1))
    calendars = get_dict_of_trading_calendars(years, cal='LSE')

    # Use the Buy and Hold Strategy
    events_queue = queue.Queue()
    strategy = BuyAndHoldStrategy(tickers[0], events_queue, calendars)

    ticker_weights = {"TSLA": 1}
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title,
                              adjusted_or_close='adj_close',
                              position_sizer=position_sizer)

    results = backtest.start_trading(testing=testing, filename=_filename)
    return results
コード例 #7
0
ファイル: expo_momo.py プロジェクト: mikimaus78/trending
def run(config, testing, tickers, _filename, initial_equity):
    # Backtest information
    title = ['Exponential momentum on basket %s' % len(tickers), "tickers"]

    year_start = 2012
    year_end = 2019

    start_date = datetime.datetime(year_start, 12, 28)

    todays_month = int(datetime.datetime.today().strftime("%m"))
    todays_day = int(datetime.datetime.today().strftime("%d"))
    end_date = datetime.datetime(year_end, todays_month, todays_day)

    csv_dir = config.CSV_DATA_DIR
    adjusted_or_close = 'adj_close'

    events_queue = queue.Queue()

    price_handler = YahooDailyCsvBarPriceHandler(csv_dir,
                                                 events_queue,
                                                 tickers,
                                                 start_date=start_date,
                                                 end_date=end_date,
                                                 calc_adj_returns=True)
    """
	we need to pass the first date dictionary ino the strategy,  the np of -1s needs t obe the length 
	on a given day how many -1s are we expecting.
	
	"""
    first_date_dict = {}
    # last_date_dict = {}
    for ticker in price_handler.tickers:
        first_date, last_date = price_handler.tickers[ticker][
            'timestamp'], price_handler.tickers_data[ticker].index[-1]
        first_date_dict[ticker] = (first_date, last_date)
        # last_date_dict[ticker] = price_handler.tickers_data[ticker].index[-1]

    first_date_df = pd.DataFrame(list(first_date_dict.items()),
                                 columns=['ticker', 'Dates'])
    first_date_df[['start_date',
                   'end_date']] = pd.DataFrame(first_date_df['Dates'].tolist(),
                                               index=first_date_df.index)
    first_date_df = first_date_df[['ticker', 'start_date', 'end_date']]
    print(first_date_df)

    # save the dataframe
    first_date_df.to_pickle('tickers_date_range.pkl')

    years = list(range(year_start, year_end + 1))
    calendars = get_dict_of_trading_calendars(years, cal='LSE')

    # Use the Buy and Hold Strategy
    strategy = ExponentialMomentum(tickers, events_queue, calendars,
                                   first_date_df)

    risk_per_stock = 0.002

    ticker_weights = {}
    for ticker in tickers:
        ticker_weights[ticker] = risk_per_stock

    # ticker_weights = {
    #     "BP.L": 1,
    #     "GSK.L": 1,
    #     "ITV.L": 1,
    #     "NG.L": 1
    # }

    position_sizer = RiskParityATRPositionSizer(ticker_weights)

    # risk_manager = ExampleRiskManager()
    risk_manager = ExpoMomoRiskManager(PriceParser.parse(initial_equity))

    portfolio_handler = PortfolioHandler(PriceParser.parse(initial_equity),
                                         events_queue, price_handler,
                                         position_sizer, risk_manager,
                                         adjusted_or_close)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title,
                              adjusted_or_close=adjusted_or_close,
                              position_sizer=position_sizer,
                              portfolio_handler=portfolio_handler,
                              price_handler=price_handler)

    results = backtest.start_trading(testing=testing, filename=_filename)
    return results
コード例 #8
0
def run(config, testing, tickers, filename):
    """
	http://www.lazyportfolioetf.com/allocation/ray-dalio-all-weather/

	All weather portfolio,
	We show the regular weightings
	And use 2x leveraged ETFs to show the leveraged version. 
	"""

    # Backtest information
    title = [
        'quarterly Liquidate/Rebalance on All-Weather\n30%/15%/40%/7.5%/7.5% SPY/IEF/TLT/GLD/DBC Portfolio'
    ]
    # title = [
    # 	'Monthly Liquidate/Rebalance on All-Weather2x\n30%/15%/40%/7.5%/7.5% FLGE/UST/UBT/DGP/DBC Portfolio'
    # ]
    initial_equity = 100000.0
    start_date = datetime.datetime(2011, 1, 1)
    end_date = datetime.datetime(2020, 12, 27)

    # Use the Monthly Liquidate And Rebalance strategy
    events_queue = queue.Queue()
    strategy = MonthlyLiquidateRebalanceStrategy(tickers, events_queue)

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    ticker_weights = {
        "SPY": 0.3,
        "IEF": 0.15,
        "TLT": 0.4,
        "GLD": 0.075,
        "DBC": 0.075
    }

    # ticker_weights = {
    # 	"SSO":0.29,
    # 	"FLGE": 0.29,
    # 	"UST": 0.15,
    # 	"UBT": 0.4,
    # 	"DGP": 0.075,
    # 	"DBC": 0.075,
    # 	"SPY": 0.01
    # }

    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        position_sizer=position_sizer,
        adjusted_or_close='adj_close',
        title=title,
        benchmark=tickers[0],
    )
    results = backtest.start_trading(testing=testing, filename=filename)
    return results