Back to Community
Buy & Hold of SPY on profitable months

After reading Sanz Prophet blog post on analysis of monthly profit and loss of S&P500, I was curious to see if using a simple buy and hold on the profitable months (Mar, Apr, Oct, Nov, Dec) would be successful. The strategy buys on the first day of the month and sells on the last day of the month.

Clone Algorithm
168
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
"""On certain months we buy on the first day of the month and 
sell on the last day of the month. Months selected based on:
http://sanzprophet.blogspot.ie/2012/12/seasonals-sp500-euro.html"""

from pandas.tseries.offsets import BMonthEnd

def initialize(context):
    context.spy = sid(8554)
    context.invested = False
    context.end_day = 0
    context.month = 0

def handle_data(context, data):
    trading_months = [3, 4, 10, 11, 12]
    date = data[context.spy].datetime
    end_offset = BMonthEnd()
    if not context.month:
        context.month = date.month
        context.end_day = end_offset(date).day
    
    if date.month > context.month:
        context.end_day = end_offset(date).day
    
    if not context.invested and date.month in trading_months and date.month > context.month:
        amount = int(context.portfolio.starting_cash / data[context.spy].price)
        log.info('Buying ' + str(amount) + ' shares of S&P500')
        order(context.spy, amount)
        context.invested = True
        
    if context.invested and date.day == context.end_day:
        amount = context.portfolio.positions[context.spy].amount
        log.info('Selling ' + str(amount) + ' shares of S&P500')
        order(context.spy, -amount)
        context.invested = False
    
    context.month = date.month
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
1 response

Very Nice Algo