# Simple Passive Momentum Trading with Bollinger Band
import numpy as np
import statsmodels.api as stat
import statsmodels.tsa.stattools as ts
# globals for batch transform decorator
R_P = 1 # refresh period in days
W_L = 30 # window length in days
lookback=22
def initialize(context):
context.stock = sid(24) # Apple (ignoring look-ahead bias)
# for long and shorting
context.max_notional = 1000000
context.min_notional = -1000000.0
# set a fixed slippage
set_slippage(slippage.FixedSlippage(spread=0.01))
def handle_data(context, data):
# find moving average
rVal=getMeanStd(data)
# lets dont do anything if we dont have enough data yet
if rVal is None:
return
meanPrice,stdPrice = rVal
price=data[context.stock].price
notional = context.portfolio.positions[context.stock].amount * price
# Passive momentum trading where for trading signal, Z-score is estimated
h=((price-meanPrice)/stdPrice)
# Bollinger band, if price is out of 2 std of moving mean, than lets trade
if h>2 and notional < context.max_notional :
# long
order(context.stock,h*1000)
if h<-2 and notional > context.min_notional:
# short
order(context.stock,h*1000)
@batch_transform(window_length=W_L, refresh_period=R_P)
def getMeanStd(datapanel):
prices = datapanel['price']
meanPrice=prices.mean()
stdPrice=prices.std()
if meanPrice is not None and stdPrice is not None :
return (meanPrice, stdPrice)
else:
return None
Screen shot of the back testing result is:
Click here to run algorithm on Quantopian.com.
Showing posts with label Momentum Trading. Show all posts
Showing posts with label Momentum Trading. Show all posts
Monday, November 18, 2013
Simple Passive Momentum Trading with Bollinger Band
Below, you can see a simple trading algorithm based on momentum and bollinger band on Quantopian.com
Labels:
Algorithmic Trading,
Bollinger Band,
finance,
Momentum Trading,
Python,
Trading
Subscribe to:
Posts (Atom)
