Issues with Algo Logic?

Hi

I just joined a couple days ago and am playing around with my first attempt at this. I'm new to python and still learning. Seems that the strategy I have has a problem with buying and selling.

Also I wanted to test this strategy against stocks that are up 5% after the first 30min of trading.

Also I am planning to only long stocks for right now since I'm looking into Robinhood, I know this isn't a complex strategy but I'm just learning and getting started. I appreciate any help!

Thanks
Steven

4
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
 Returns 1 Month 3 Month 6 Month 12 Month
 Alpha 1 Month 3 Month 6 Month 12 Month
 Beta 1 Month 3 Month 6 Month 12 Month
 Sharpe 1 Month 3 Month 6 Month 12 Month
 Sortino 1 Month 3 Month 6 Month 12 Month
 Volatility 1 Month 3 Month 6 Month 12 Month
 Max Drawdown 1 Month 3 Month 6 Month 12 Month
# This algorithm uses the talib Bollinger Bands function to determine entry entry
# points for long and short positions.

# When the price breaks out of the upper Bollinger band, a short position
# is opened. A long position is opened when the price dips below the lower band.

# Because this algorithm uses the history function, it will only run in minute mode.
# We will constrain the trading to once per day at market open in this example.

import talib
import numpy as np
import pandas as pd

# Setup our variables

def initialize(context):
set_symbol_lookup_date('2016-01-01')
context.stocks = symbols('PFE', 'BA', 'JNJ', 'PG', 'MCD', 'HD', 'MRK', 'INTC', 'MMM', 'UTX', 'NKE', 'VZ', 'CAT', 'WMT', 'AXP', 'KO', 'GE', 'CVX', 'DD', 'V', 'XOM', 'AAPL', 'TRV', 'IBM', 'JPM', 'GS', 'MSFT', 'DIS', 'UNH', 'CSCO')

# Create a variable to track the date change
context.date = None

# Keeping track of the last sale that you have.
context.last_sale = None

# Setting max daily orders
#set_max_order_count(1)

# Setting long orders only
set_long_only()

def handle_data(context, data):
todays_date = get_datetime().date()

# Do nothing unless the date has changed
if todays_date == context.date:
return

# Set the new date
context.date = todays_date

#Get cost of stock and log it
for stock in context.stocks:
current_position = context.portfolio.positions[stock].amount
log.info(stock.symbol + ' - ' + str( current_position))
funds_available = context.account.settled_cash
log.info(funds_available)
price = data[stock].price
log.info(stock.symbol + ' - ' + str(price))
cost = context.portfolio.positions[stock].cost_basis
goal = 1.05*cost
log.info(stock.symbol + ' - Cost ' +  str(cost))
log.info(stock.symbol + ' - Selling Goal ' + str(goal))
stoplimit = 0.93*cost
log.info(stock.symbol + ' - Stop Limit ' + str(stoplimit))

# Load historical data for the stocks
#for stock in context.stocks:
prices = history(15, '1d', 'price')
upper, middle, lower = talib.BBANDS(
prices[stock],
timeperiod=15,
# number of non-biased standard deviations from the mean
nbdevup=2,
nbdevdn=2,
#Moving average type: simple moving average here
matype=0)

if price <= lower[-1] and current_position == 0:
order_target_percent(stock, 0.8)

if price >= goal and current_position > 0:
#stoporder = get_order(stock)
#cancel_order(stoporder)
#log.info(stock.symbol + ' Stop Limit Cancelled!!')
order_target_percent(stock, 0.0)
log.info("Sold %s" % (stock))

if price <= stoplimit and current_position > 0:
order_target_percent(stock, 0.0)
log.info("SOLD LOSS %s" % (stock))

record(upper=upper[-1],
lower=lower[-1],
mean=middle[-1],
price=price,
position_size=current_position)


There was a runtime error.
1 response

Think the original issue was the leverage. With a few modifications I think this may be able to generate positive alpha.

1
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
 Returns 1 Month 3 Month 6 Month 12 Month
 Alpha 1 Month 3 Month 6 Month 12 Month
 Beta 1 Month 3 Month 6 Month 12 Month
 Sharpe 1 Month 3 Month 6 Month 12 Month
 Sortino 1 Month 3 Month 6 Month 12 Month
 Volatility 1 Month 3 Month 6 Month 12 Month
 Max Drawdown 1 Month 3 Month 6 Month 12 Month
# This algorithm uses the talib Bollinger Bands function to determine entry entry
# points for long and short positions.

# When the price breaks out of the upper Bollinger band, a short position
# is opened. A long position is opened when the price dips below the lower band.

# Because this algorithm uses the history function, it will only run in minute mode.
# We will constrain the trading to once per day at market open in this example.

import talib
import numpy as np
import pandas as pd

# Setup our variables

def initialize(context):
set_symbol_lookup_date('2016-01-01')
context.stocks = symbols('PFE', 'BA', 'JNJ', 'PG', 'MCD', 'HD', 'MRK', 'INTC', 'MMM', 'UTX', 'NKE', 'VZ', 'CAT', 'WMT', 'AXP', 'KO', 'GE', 'CVX', 'DD', 'V', 'XOM', 'AAPL', 'TRV', 'IBM', 'JPM', 'GS', 'MSFT', 'DIS', 'UNH', 'CSCO')

# Create a variable to track the date change
context.date = None

# Keeping track of the last sale that you have.
context.last_sale = None

# Setting max daily orders
#set_max_order_count(1)

# Setting long orders only
set_long_only()

def handle_data(context, data):
todays_date = get_datetime().date()

# Do nothing unless the date has changed
if todays_date == context.date:
return

# Set the new date
context.date = todays_date

#Get cost of stock and log it
for stock in context.stocks:
current_position = context.portfolio.positions[stock].amount
log.info(stock.symbol + ' - ' + str( current_position))
funds_available = context.account.settled_cash
log.info(funds_available)
price = data[stock].price
log.info(stock.symbol + ' - ' + str(price))
cost = context.portfolio.positions[stock].cost_basis
##was 1.05
goal = 1.08*cost
log.info(stock.symbol + ' - Cost ' +  str(cost))
log.info(stock.symbol + ' - Selling Goal ' + str(goal))
##was 0.93
stoplimit = 0.92*cost
log.info(stock.symbol + ' - Stop Limit ' + str(stoplimit))

# Load historical data for the stocks
#for stock in context.stocks:
prices = history(25, '1d', 'price')
upper, middle, lower = talib.BBANDS(
prices[stock],
timeperiod=25,
# number of non-biased standard deviations from the mean
## was 2
nbdevup=2,
nbdevdn=2,
#Moving average type: simple moving average here
matype=0)

if price <= lower[-1] and current_position == 0:
##was 0.8, now it's len
weight = len(context.stocks)
order_target_percent(stock, 1.0/weight)

if price >= goal and current_position > 0:
#stoporder = get_order(stock)
#cancel_order(stoporder)
#log.info(stock.symbol + ' Stop Limit Cancelled!!')
order_target_percent(stock, 0.0)
log.info("Sold %s" % (stock))

if price <= stoplimit and current_position > 0:
order_target_percent(stock, 0.0)
log.info("SOLD LOSS %s" % (stock))

record(upper=upper[-1],
lower=lower[-1],
mean=middle[-1],
price=price,
position_size=current_position)


There was a runtime error.