Any help would be much appreciated, pretty new to python and quantopian
Any help would be much appreciated, pretty new to python and quantopian
Hi Mathew,
I took a look at your algo and corrected a few issues. I attached a modified version of your algo which addresses the following issues:
my_pipeline
(line 15). The new version attaches the output of my_pipeline
to the algo.Fundamentals.market_cap.latest
if you want to use the latest market cap. I fixed the calls in the attached algo.The algo still isn't ordering anything, but it's at least getting a non-empty pipeline. My suggestion as a next step would be to try debugging by printing out the state of different variables before orders are placed to make sure everything is behaving as you expect it to. I'd also recommend going through the tutorials to get a better understanding of the current API.
I hope this helps.
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.
Hey there Jamie! Thank you very much for your help! After seeing how you fixed my algorithm, I was able to tweak the pipeline into returning a data frame. However, now I've encountered a new problem: None of my orders are going through. I will attach the back test and some code that I think is influencing this error, but I can't seem to figure out why my python code is not executing my purchases. Any help would be much appreciated.
Creates my weights for the stocks:
def create_weights(context, stocks):
"""
Takes in a list of securities and calculates
the portfolio weighting percentage used for each stock in the portfolio
"""
if len(stocks) == 0:
return 0
else:
# Buy only 0.95 of portfolio value to avoid borrowing
weight = .95/len(stocks)
return weight
Next Code has to do with MACD:
def MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9):
'''
Function to return the difference between the most recent
MACD value and MACD signal. Positive values are long
position entry signals
optional args:
fastperiod = 12
slowperiod = 26
signalperiod = 9
Returns: macd - signal
'''
macd, signal, hist = talib.MACD(prices,
fastperiod=fastperiod,
slowperiod=slowperiod,
signalperiod=signalperiod)
return macd[-1] - signal[-1]
Next code defines my rebalance:
def rebalance(context, data):
# Track cash to avoid leverage
cash = context.portfolio.cash
pricess = data.history(context.portfolio.positions, fields="price", bar_count=40, frequency="1d")
macd = pricess.apply(MACD, fastperiod=12, slowperiod=26, signalperiod=9)
and finally, here is the purchase code I have:
# Create weights for each stock
weight = create_weights(context, context.output)
# Rebalance all stocks to target weight of overall portfolio
for stock in context.output:
if weight != 0 and data.can_trade(stock):
notional = context.portfolio.portfolio_value * weight
price = data.current(stock, 'price')
numshares = int(notional / price)
# Growth companies could be trading thin: avoid them
if cash > price * numshares and numshares < data.current(stock, 'volume') * 0.2:
if data.can_trade(stock) and macd[stock] > 0:
order_target_percent(stock, weight)
cash -= notional - context.portfolio.positions[stock].amount
log.info("Placing order: %s" % stock)
Hi Matthew,
The last algo you shared is running into an issue because you are indexing macd with securities from context.output (line 129), but macd is only calculated/ only contains securities that were already in your portfolio (lines 106, 107).
To fix this, you could create a set that contains securities in your portfolio and securities from context.output, and use it to calculate macd.
I hope this helps.
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.
Hey Ernesto, that actually did help and it made complete sense. When creating a new set for securities in context.ouput, I ran into a new error:
"Exception: inputs are all NaN There was a runtime error on line 109."
Any Idea why this is showing up??
Thank you for your help by the way, this has been a great learning experience
Hi Mathew,
Talib's functions raise that error when you pass a vector consisting entirely of NaN values as input.
The underlying issue is that HNNA has a start date of Sep, 2005, but pricing data is not available until May, 2014 (when it was listed on NASDAQ). So this asset makes it through your pipeline filters into your tradable universe before there is any pricing data for it, and data.history returns a vector of NaNs for this asset. I have made a reported of this particular issue, and I'll share it with our data team for review.
In the meantime, you can easily avoid this type of issues by adding a price filter to your pipeline screen. See the backtest attached for an example in line 46.
I hope this helps.
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.