Ah... that's a little trickier but, again, the
query method to the rescue.
First, get the last date of the dataframe. Next get any rows where "close > last MA5 and date==last date". Get the values of index level 1. Those will be the stocks where the above condition is True. There may be more than one. Finally, select all rows where the symbol is in this list.
One really nice thing about the
query method is one can use indexes just like columns. Since we named our level 1 index 'symbol' it makes it easy. Another nice thing about the
query method is one can access variables by prefixing them with @ (otherwise it would think they were supposed to be a column name). So, I believe this should do it
# Get all rows of stocks where the last close of the dataframe > last ma5
# First, find the last date in the dataframe
last_day = df.index.get_level_values(level=0).max()
# Get a dataframe where the date is the last date and the close is greater than ma5
close_below_ma5_on_last_day = df.query('(date == @last_day) and (close > ma5)')
# Get the values of index level 1 which will be the stocks meeting our criteria
stocks_where_close_below_ma5_on_last_day = close_below_ma5_on_last_day.index.get_level_values(level=1)
# Finally, select those rows where symbol is in our list of stocks
my_result_df = df.query('symbol in @stocks_where_close_below_ma5_on_last_day')
See if that's what you were looking for.
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.