Several questions about building the algorithms
import datetime
import pytz

def initialize(context):
# Here we initialize each stock.  Note that we're not storing integers; by
# calling sid(24) we're storing the Security object.
context.stocks = [sid(24), sid(2), sid(2673), sid(5061)]

# Setting our maximum position size, like previous example
context.max_notional = 1000000.1
context.min_notional = -1000000.0

# Initializing the time variables we use for logging
# Convert timezone to US EST to avoid confusion
est = pytz.timezone('EST')
context.d=datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=est)

def handle_data(context, data):
# Initializing the position as zero at the start of each frame
notional=0
# This runs through each stock.  It computes
# our position at the start of each frame.
for stock in context.stocks:
price = data[stock].price
notional = notional + context.portfolio.positions[stock].amount * price
# This runs through each stock again.  It finds the price and calculates
# the volume-weighted average price.  If the price is moving quickly, and
# we have not exceeded our position limits, it executes the order and
close_price = history(bar_count=21, frequency='1d',field='close_price')
ma_line = data[stock].mavg(24)
short_ma = data[stock].mavg(15)
long_ma = data[stock].mavg(30)
r = (close_price - ma_line)/ma_line
Bias = {}
highPrices  = history(25, '1d', 'high')
lowPrices   = history(25, '1d', 'low')
closePrices = history(25, '1d', 'close_price')

for stock in context.stocks:
Bias[stock] = r
stochast = ta.STOCH(highPrices[context.stocks], lowPrices[context.stocks], closePrices[context.stocks],fastk_period=25)
slowk = stochast[0]
slowd = stochast[1]
if slowk > slowd and slowd < 10 and notional > context.min_notional:
order(stock,-100)
notional = notional - price*100
elif short_ma > long_ma and notional < context.max_notional:
order(stock,+100)
notional = notional + price*100

# If this is the first trade of the day, it logs the notional.
if (context.d + datetime.timedelta(days=1)) < tradeday:
log.debug(str(notional) + ' - notional start ' + tradeday.strftime('%m/%d/%y'))

Hi, Quantapian company

I have several questions here for the code above.

1. I got an error saying that "Error Runtime exception: TypeError: init() got multiple values for keyword argument 'close'. " on the line ---> stochast = ta.STOCH(highPrices[context.stocks], lowPrices[context.stocks], closePrices[context.stocks],fastk_period=20)

2. For the ta.STOCH, what is the reason I need to specify the fastk_period even that I specify the data frequency in the previous high price/low price/close price?

3. I want to write the buy condition when slowk cross above slowd not just over it as it showed above. Also, I want to write the cross below condition when short_ma cross below long_ma?

Thanks!

4 responses

Hello,

The attached may get you a little further forward syntactically. I don't fully understand it but if you specify a 'fastk_period' you need at least four more periods of data i.e. 8 and 12 or 21 and 25. If you don't specify a 'fastk_period' the first results are on period 9 assuming you have at least 9 periods of data.

P.

2
Backtest from to with initial capital
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
import datetime
import pytz
import talib

def initialize(context):
# Here we initialize each stock.  Note that we're not storing integers; by
# calling sid(24) we're storing the Security object.
context.stocks = [sid(24), sid(2), sid(2673), sid(5061)]

# Setting our maximum position size, like previous example
context.max_notional = 1000000.1
context.min_notional = -1000000.0

# Initializing the time variables we use for logging
# Convert timezone to US EST to avoid confusion
est = pytz.timezone('EST')
context.d=datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=est)

def handle_data(context, data):
# Initializing the position as zero at the start of each frame
notional=0
# This runs through each stock.  It computes
# our position at the start of each frame.
for stock in context.stocks:
price = data[stock].price
notional = notional + context.portfolio.positions[stock].amount * price
# This runs through each stock again.  It finds the price and calculates
# the volume-weighted average price.  If the price is moving quickly, and
# we have not exceeded our position limits, it executes the order and
close_price = history(bar_count=21, frequency='1d',field='close_price')
ma_line = data[stock].mavg(24)
short_ma = data[stock].mavg(15)
long_ma = data[stock].mavg(30)
r = (close_price - ma_line)/ma_line
Bias = {}
highPrices  = history(9, '1d', 'high')
lowPrices   = history(9, '1d', 'low')
closePrices = history(9, '1d', 'close_price')

for stock in context.stocks:
Bias[stock] = r
stochast = talib.STOCH(highPrices[stock], lowPrices[stock], \
closePrices[stock])
print stochast
slowk = stochast[0][-1]
slowd = stochast[1][-1]
if slowk > slowd and slowd < 10 and notional > context.min_notional:
order(stock,-100)
notional = notional - price*100
elif short_ma > long_ma and notional < context.max_notional:
order(stock,+100)
notional = notional + price*100

# If this is the first trade of the day, it logs the notional.
if (context.d + datetime.timedelta(days=1)) < tradeday:
log.debug(str(notional) + ' - notional start ' + tradeday.strftime('%m/%d/%y'))
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

Hi, @Peter, thanks so much for your answer. Do you know how to write cross above and cross below function?

Hello,

This is from quite a few months ago so I'm sure there are better ways. It uses a deque of length 2 to store the current and previous values of of the two moving averages. It seems to be checking for fast crossing slow from below but I'm not sure!

P.

25
Backtest from to with initial capital
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
from collections import deque
import talib

fastEMAperiod = 3
slowEMAperiod = 9

def initialize(context):
context.ema1buffer = deque(maxlen=2)
context.ema2buffer = deque(maxlen=2)
context.stock = sid(2)

def handle_data(context, data):
closePrices = get_prices(data)
if closePrices is None:
return
moving_average1  = talib.EMA(closePrices[context.stock],timeperiod=fastEMAperiod)[-1:]
moving_average2  = talib.EMA(closePrices[context.stock],timeperiod=slowEMAperiod)[-1:]
context.ema1buffer.append(moving_average1)
context.ema2buffer.append(moving_average2)
if len(context.ema1buffer) == 2:
if context.ema1buffer[1]>context.ema2buffer[1] and context.ema2buffer[0]>context.ema1buffer[0]:
print "Cross!"
record(EMA1=float(moving_average1[-1:]), EMA2=float(moving_average2[-1:]))

@batch_transform(window_length=slowEMAperiod, refresh_period=0)
def get_prices(DataPanel):
closePrices = DataPanel['close_price']
return closePrices

This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

Is there any inner function in quantopian that can reference the cross above function?