Hi,
I'm just getting started and looked at the examples and api documentation, are there any examples of buying an asset at 10 minutes to market close only if it is down more than 5% from previous days close?
Thanks in advance
Hi,
I'm just getting started and looked at the examples and api documentation, are there any examples of buying an asset at 10 minutes to market close only if it is down more than 5% from previous days close?
Thanks in advance
Hi Jay,
Take a look at the following sections of the help page:
- To have a function run on specific dates and/or at specific times
- To obtain historical data
If you combine both of those sections you will be able to create a code doing what you need.
Below I've written something that I believe will help get you started.
*I'm not an experienced coder, so if any one sees a better way please offer your solution.
def initialize(context):
# Set Universe 90.0-90.1 percentile (~8 securities)
set_universe(universe.DollarVolumeUniverse(90.0, 90.1))
# Algorithm will call myfunc every day, 10 minutes before market closes
schedule_function(
myfunc,
date_rules.every_day(),
time_rules.market_close(minutes=10)
)
def myfunc(context,data):
# Current price and Yesterday's Close
price_history = history(bar_count=2, frequency='1d', field='price')
# Loops through all stocks in our universe
for s in data:
prev_bar = price_history[s][-2]
curr_bar = price_history[s][-1]
# Buy only if current price is < 5% of prev_day_close
if curr_bar < 0.95*prev_bar:
order(s, 20) # Buy 20 shares
def handle_data(context,data):
pass
I've actual got a question myself.
In the above code I wrote, if I look at the len(data), which is the number of stocks in my universe on day 1, it is 8 after 1 year it monotonically goes up to 37. Is this normal behavior? Is this because the universe is updated every quarter? It just seems like too many stocks to me.
len(data) is the number of securities in your universe that have traded in the last minute. This may have to do with increasing volume (and frequency of trades) of the securities in your dollar volume percentile range. Look at len(data) in daily mode and see if it's different.
My findings were found using daily data.
Also, I changed the percentile range to try to find some that would not monotonicslly increase but had no luck (5 to 5.1%, 10 to 10.1%, etc...).
The increase seems to happen every quarter.
The portfolio includes companies that get delisted, so I suspect you ran a backtest over a long period of time, perhaps including the 2008 crisis. Since companies leave the exchanges in different manners, it's hard to construct a one-size-fits-all solution. We're working to make it easier to handle in the backtester, but in the meantime I'd suggest to use this trick in the algo for testing.
Also, I'd recommend to always run your backtest in minute mode. This closely simulates the live trading environment and gives you fresher prices.
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.
@Alisa Deychman
Thanks for the link, very useful.
However, I feel that what I am observing is strange.
I've run the algorithm for 1 year (2014-2015 or 2008-2009 etc...) using various percentiles (all with a range of 0.1, i.e: 5.0-5.1 or 90.0 to 90.1)
Take a look at my backtest, I record len(data) and it always has the same increasing trend (monotically increasing from 8 to around 37) in one year.
Hello Marc,
I see this as a combo of the universe updating each quarter and the algo only placing buy orders. Each quarter a new .1 percent list is created so they add up over the year.
I tried to write a specific code which does what you want. It sells all the previous positions first , then checks the 5% condition and buys . I am getting a syntax error though at the "def handle_data(context,data)" line.
def initialize(context):
set_universe(universe.DollarVolumeUniverse(floor_percentile=95.0, ceiling_percentile=100.0))
context.secs = []
schedule_function(check_for_buy,date_rules.every_day(),time_rules.market_close(minutes=10)
def handle_data(context,data):
pass
def check_for_buy(context,data):
context.secs.clear()
for stock in context.portfolio.positions:
order_target(stock,0)
cl_p = history(2,'1d','close_price')
for stock in data:
last_min = cl_p[stock][-1]
prev_day = cl_p[stock][-2]
if last_min < 0.95*prev_day:
context.secs.append(stock)
wt = (1.0/len(context.secs))
for stock in context.secs:
order_target_percent(stock,wt)
@Yatharth - When you see a syntax error reported on what looks like a perfectly good line, look at the previous line, not counting empty lines and comments.
The schedule_function call has a missing closing parenthesis at the end. Hint: when you type a closing parenthesis in the IDE, it highlights the corresponding opening one. That is a good time to check if you need to type another one.
@Jeff Koch
So if I understand correctly:
The universe will only add new stocks, it will never remove unused ones.
So if I start with 90.0-90.1 percentile on 1/1/2008 and that gives me 8 stocks.
And on 1/1/2009 it's still 8 stocks, but 4 of them have been changed to different stocks (they moved percentile rating), then my universe will increase to 12.
Is this how it is?
Thank you
M
This would be easy to find out with a function named get_universe and returning a list of Security or Asset objects then in your universe. There is no such function, but there should be. There should be a getter for every setter. Quantopian: consider this a feature request.
In the meantime, you can make your own. Start with an empty set in initialize:
context.universe=set({})
Then update it in handle_data - once at the beginning of each calendar quarter is enough:
for stock in data:
context.universe.add(stock)
Then print the ticker symbols of its members on one line, separated by spaces, sorted alphabetically:
print "Universe: "+' '.join(sorted([stock.symbol for stock in context.universe]))
More information about Python sets is at https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset .
Actually, this is not what you want. It will add new stocks, but will not remove them. You would need to reinitialize to an empty set each quarter, as in the first code chunk above. Then you would need to run the for loop to harvest your current universe all over again. Then print at the end of each quarter.