I want to measure a 1-buy and hold strategy against a benchmark (SPY). I have the following code:
# Algorithm API imports
import quantopian.algorithm as algo
import pandas as pd
import datetime
#==============================================================================
URL = ...
#==============================================================================
def preview(df):
log.info(' \n %s ' % df.head())
return df
#==============================================================================
def initialize(context):
fetch_csv(URL,
pre_func=preview,
date_column='date',
date_format='%Y-%m-%d' )
# Set the benchmark to the SPY - 8554
set_benchmark(sid(8554))
# Rebalance every day, at end of day to account for forward bias
algo.schedule_function(
rebalance,
algo.date_rules.month_start(),
algo.time_rules.market_open(hours=0, minutes=20) )
#==============================================================================
def before_trading_start(context, data):
# Get the weights that will have to be traded
context.weights = data.current(data.fetcher_assets, 'weight')
# Update the universe
context.assets = context.weights.index
#==============================================================================
def rebalance(context, data):
for stock in context.weights.index:
if stock not in context.portfolio.positions:
if data.can_trade(stock) and data.current(stock, 'price') != None:
# We're dealing with exotic ones... Check if data available
log.info( 'long {A}; weight {B}; price {C}'.format(
A=stock,
B=context.weights[stock],
C=data.current(stock, 'price')))
order_target_percent(stock, context.weights[stock])
The URL links to my dropbox where a *.csv File is stored. It looks like
date,symbol,weight
2013-03-01,AAL,0.0
2013-03-04,AAL,0.0
2013-03-05,AAL,0.0
2013-03-06,AAL,0.0
2013-03-07,AAL,0.0
2013-03-08,AAL,0.0
2013-03-11,AAL,0.0
2013-03-12,AAL,0.0
2013-03-13,AAL,0.0
...
2013-03-01,AET,0.0051
2013-03-04,AET,0.0051
2013-03-05,AET,0.0051
2013-03-06,AET,0.0051
2013-03-07,AET,0.0051
2013-03-08,AET,0.0051
2013-03-11,AET,0.0051
2013-03-12,AET,0.0051
2013-03-13,AET,0.0051
...
The weights do not change over time.
So does this code only invests a amout of money in those stocks with the corresponding weight at startup? I'am a bit unsure.