Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help Getting Total Market Cap in Sector

I'm trying to get the total market cap in a sector by day. I'm new to coding in general as you can probably tell. I think I'm on the right track but I can't figure out how to sum the market cap for all stocks in my universe daily. I have tried tech_stocks['market_cap'].sum() but it adds all the days together. Just to be clear because I'm new to this and don't know if I'm explaining it right, I want to end up with one market cap number per trading day that is the sum of my selected stocks market caps. I'm planning on plotting this along with a moving average of the market cap. Also, I have a price filter to limit the selection until I get it working to make the data easier to handle.

Thanks for helping me out.

PS - I'm aware that their are Sector ETF's and such that I could use instead, but at this point I just want to figure out how to do it myself. It's not for any real world trading, just learning.

3 responses

You are looking for the groupby method (https://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.groupby.html). Something like this

tech_stocks.market_cap.groupby(level=0).sum()

What that does is starts with the 'tech_stock' dataframe. Then selects the 'market_cap' column. Then applies the 'groupby method. The initial dataframe has a multi index (first indexed by date - level 0, and then by security - level 1) . If one wants to group by date then specify 'level=0' . It's often less cryptic to first name the indexes (eg 'date' and 'security') so one could simply group by 'date' for easier reading.

Once the data is grouped, then apply the 'sum' method. There are a number of methods which could also be applied.

See attached notebook. Hope that helps.

Thanks Dan! I also really appreciate you explaining it in detail so that I understand it. That will help me remember it down the road.

@Brett. Always glad to help. Good luck!