A couple weeks ago came across this free cloud based backtesting service, https://www.quantopian.com
Here’s a sample code of a portfolio which I’m running that is long 60% QQQ (large cap US tech), short 30% foreign markets and short 10% small caps:
def initialize(context):
set_symbol_lookup_date('2010-1-1')
context.stocks = symbols('qqq', 'veu', 'iwm', 'eem', 'iwm')
def handle_data(context, data):
# This will order as many shares as needed to
# achieve the desired portfolio allocation.
# In our case, we end up with 20% allocation for
# one stock and 80% allocation for the other stock.
order_target_percent(context.stocks[0], .60)
order_target_percent(context.stocks[1], -.30)
order_target_percent(context.stocks[2], -.10)
order_target_percent(context.stocks[3], -.00)
order_target_percent(context.stocks[4], -.0)
# Plot portfolio allocations
pv = float(context.portfolio.portfolio_value)
portfolio_allocations = []
for stock in context.stocks:
pos = context.portfolio.positions[stock]
portfolio_allocations.append(
pos.last_sale_price * pos.amount / pv * 100
)
record(perc_stock_0=portfolio_allocations[0],
perc_stock_1=portfolio_allocations[1])
Here’s a sreenshot of the rendered result versus the S&P 500 ETF, SPY: