Import Optimize API module
import quantopian.optimize as opt
import talib
import pandas as pd
import numpy as np
def initialize(context):
# VDE
context.security = sid(26667)
# Set cash limit for trading
context.portfolio.cash = 100000.0
context.max_leverage = 1.0
context.min_leverage = -1.0
def rebalance(context, data):
# Constrain target portfolio's leverage
max_leverage = opt.MaxGrossExposure(context.max_leverage)
min_leverage = opt.MinGrossExposure(context.min_leverage)
def handle_data(context, data):
cash = context.portfolio.cash
# We get the price history for the last 15 days.
price_history = data.history(
context.security,
fields='price',
bar_count=15,
frequency='1d'
)
# Then we take an average.
average_price = price_history.mean()
sma = price_history.sma()
# We also get the stock's current price.
low_price = data.current(context.security,'low')
# If the current price is 2% below the sma => buy,
for stock in context.security:
current_position = context.portfolio.positions[stock].amount
current_price = data.current(context.security, 'price')
if current_price < (0.90 * average_price) and current_position <= 0:
# Place the buy order (positive means buy, negative means sell)
order_target_percent(context.security, 1)
target_shares = cash // data[stock].price
order_target(stock, target_shares)
log.info('buying shares'.format(
stock.symbol, price[stock], target_shares
elif current_price > (1.10 * average_price) and current_position >= 0:
# Sell all of our shares by setting the target position to zero
order_target_percent(context.security, -1)
log.info("Selling %s" % (context.security.symbol))
else:
log.info( "no activity")
# Use the record() method to track up to five custom signals.
# Record Apple's current price and the average price over the last
# five days.
record(current_price=current_price, average_price=average_price)