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
tradeday = data[stock].datetime
# 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
# updates our position.
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'))
context.d = tradeday
Hi, Quantapian company
I have several questions here for the code above.
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)
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?
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!