So the Error is what is displayed but the message can be a bit confusing. The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). This is a type issue that you can run into with Pandas, the data manipulation library. Pandas has 3 main data strucutres: Panel, DataFrame, Series. A Panel you can think about as a 3-D matrix. A DataFrame is 2-D datastrcture, and a Series is, you guessed it, 1-D structure. The
history() function returns a DataFrame keyed by Security, so if you want to do operations on a single securities time series from it you have to call it by its key. For example,
security_history = history(10, "1d", "price")[security]
However, Pandas supports vectorized operations so you don't have to loop through a bunch of securities. So when you take the mean in your code you are applying the mean function to every security in the history DataFrame. Since the mean in a reducing operation you now have a DataFrame that contains a Series of one value (the mean of that Series), for every security.
Finally, to get that scalar value of that one security you need to call on that Security like I showed in the snippet above. So in your example to get the average value of SPY for the past 2 days. You can do this...
historical_data = history(5, '1d', 'price')
last_2_day_mean = historical_data.tail(2).mean()
last_2_day_mean_for_SPY = last_2_day_mean[context.stock]
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.