Thank you Viridian and Vladimir for the replies,
The problem I was having was not including the '[:-2]'.
Viridian, my apologies, I will explain what I am trying to build in greater detail:
For a buy:
The buy is initiated once price breaks above an 89-day high. The initial stop loss is set 1 ATR(20) below the entry price. However, once the 100SMA's price is greater than the initial stop loss price, the 100SMA is now the trailing stop loss.
The two scenarios are: 1. I buy and get stopped out on the initial stop loss which is 1ATR(20) below the entry price. 2. I buy and get stopped out once price goes below the 100 SMA which has a greater price than the initial stop loss.
For a sell:
The sell is initiated once price breaks below an 89-day low. The initial stop loss is set 1 ATR(20) above the entry price. However, once the 100SMA's price is lower than the initial stop loss price, the 100SMA is now the trailing stop loss.
The two scenarios are: 1. I sell and get stopped out on the initial stop loss which is 1ATR(20) above the entry price. 2. I sell and get stopped out once price goes above the 100 SMA which has a lesser price than the initial stop loss.
I was using only 2% because I want to trade this on multiple different stocks. I was using just SPY for simplicity sake.
So that brings up the next couple questions that I will have to figure out, but would be very grateful for any help with them:
How do I run the algo so it can trade on multiple different stocks at the same time? In the code below, I am trying to trade Tesla, Apple, the S&P, and Amazon. When I try to build the algo I get : "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
There was a runtime error on line 18."
import talib
def initialize(context):
schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open())
context.stock = symbols('TSLA', 'AAPL', 'SPY', 'AMZN')
def my_rebalance(context, data):
price = data.current(context.stock, "price")
high_89 = data.history(context.stock, "high", 89, "1d")[:-2].max()
low_89 = data.history(context.stock, "low", 89, "1d")[:-2].min()
hist = data.history(context.stock, "price", 100, "1d")
sma_100 = hist.mean()
open_orders = get_open_orders()
if price > high_89:
if context.stock not in open_orders:
order_target_percent(context.stock, .05)
elif price < sma_100:
if context.stock not in open_orders:
order_target_percent(context.stock, 0)
if price < low_89:
if context.stock not in open_orders:
order_target_percent(context.stock, -0.05)
elif price > sma_100:
if context.stock not in open_orders:
order_target_percent(context.stock, 0)
record(leverage = context.account.leverage)
The second question is: 1. How do set the initial stop loss to be 1ATR(20) above/below the entry point (depending on if its a buy or sell)? 2. How do I "override", if you will, the initial stoploss with the 100SMA which would act as a trailing stop loss?