How would I write a code to take the average price of everyday a stock has been in existence?
How would I write a code to take the average price of everyday a stock has been in existence?
Hello Jeremy,
The Quantopian platform is pretty flexible. Can you be more specific about what you're trying to do?
Grant
Sorry, I think I was trying to ask how to make a code that generates the average of every historical price of a stock past and present.
Jeremy,
If you want a 10-year average, for example, it is possible by obtaining a trailing window of data with the history API, but I suspect you may want the average over a shorter time frame on a rolling basis (e.g. up to tens of days is typical). In any case, something like this will do the trick:
def initialize(context):
context.stocks = [sid(8554)]
context.computed = False
def handle_data(context, data):
if not context.computed:
prices = history(2520,'1d','price')
mean = float(prices.mean().values)
print mean
context.computed = True
You're welcome. The context.computed boolean flag just executes the mean calculation once (the first call to handle_data) as an illustration. --Grant
def initialize(context):
context.stocks = [sid(3597)]
context.computed = False
set_slippage(slippage.FixedSlippage(spread=.05))
set_commission(commission.PerTrade(cost=7))
context.max_notional = 100000
context.min_notional = -100000
def handle_data(context, data):
if not context.computed:
price = history(2520, '1d', 'price')
mean = float(price.mean().values)
print mean
context.computed = True
notional = context.portfolio.positions[context.stocks].amount * price
if price < (mean) and notional > context.min_notional:
message = context.portfolio.positions[context.jblu].amount
log.info(message)
message = context.portfolio.cash
log.info(message)
message = 'Buy'
log.info(message)
order(context.jblu, +10)
record(Cash=context.portfolio.cash)
I am a little unsure what the error is here: it is telling me that when I define notional it is un-hashable and I am unsure what that really means. Thanks!