Hey
I am currently trying to test a very basic buying and selling strategy.
What I want to do is buying when price is at lower Bollinger band and selling as soon as there is an increase of 0.5% or more.
I the price drops the strategy should buy the same amount again. For instance buy with 20% of the capital price drops and touches lower Bollinger agin therefore the code should buy with another 20% of the capital. As soon as the overall price increase is greater than 0.5% sell everything....
The problem is that it only buys when it sold something before, how can I get it to buy every time it is below the lower bb?
any help would be appreciated!
import talib
# Setup our variables
def initialize(context):
context.stock = symbol('AAPL')
set_benchmark(symbol('AAPL'))
# Create a variable to track the date change
context.date = None
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(30, '1m', 'price')
#price_history = data.history(security, 'price', 2, '1m')
upper, middle, lower = talib.BBANDS(
prices[context.stock],
timeperiod=20,
# 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
if price <= lower[-1] and current_position <= 1.0:
order_target_percent(context.stock, 0.2)
print "buyprice", price
# If price is higher than 1.005 sell
# exit position
elif price > 1.005 * costBasis and current_position > 0:
order_target_percent(context.stock, 0.0)
print "sellprice", price
#print price
record(upper=upper[-1],
lower=lower[-1],
mean=middle[-1],
price=price,
position_size=current_position)
Thanks for your help!!