Hi there,
I am new to Quantopian and want to try out a basic Bollinger method based on 1 minute candles. I want to by when below lower bb and sell as soon as the middle band gets crossed with the limitation that the sell should only happen if its profitable.
thats the current code based on a example code from Quantopian:
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import Q1500US
import talib
import numpy as np
import pandas as pd
# Setup our variables
def initialize(context):
context.exitafterlossof = True
context.losspcent = 0.97
context.stock = symbol('AAPL')
set_benchmark(symbol('AAPL'))
set_commission(commission.PerTrade(cost=20.00))
def handle_data(context, data):
current_position = context.portfolio.positions[context.stock].amount
price=data[context.stock].price
costBasis = context.portfolio.positions[context.stock].cost_basis
# Load historical data for the stocks
prices = history(15, '1m', 'price')
upper, middle, lower = talib.BBANDS(
prices[context.stock],
timeperiod=10,
# number of non-biased standard deviations from the mean
nbdevup=2,
nbdevdn=1,
# Moving average type: simple moving average here
matype=0)
# If price is below the recent lower band and we have
# no long positions then invest the entire
# portfolio value into SPY
if price <= lower[-1] and current_position <= 0:
order_target_percent(context.stock, 1.0)
print "buyprice"
print price
# If price is above the recent middle band and higher than buying price was
# exit position
elif price >= middle[-1] and current_position >= 0 and price > costBasis:
#and buyprice > current_price:
order_target_percent(context.stock, 0.0)
print "sellprice"
print price
record(upper=upper[-1],
lower=lower[-1],
mean=middle[-1],
price=price,
position_size=current_position)
from what I understand the "price > costBasis:" should do what I want but the backtesting tells me that I am selling at loss, why??
Any help is appreciated.
Thx
Thorsten