The premise of my question is I would like to use one dataframe (peergroups) to create groups of stocks that are peers of other stocks and then calculate averages on another dataframe (fun_data) but I do not know how to use one dataframe to create the groups by year and ticker and then apply the groups, find the average of multiple columns, and create new columns for those averages in another dataframe. Any help is appreciated. The data I have so far is below.
I start with two dataframes, one with fundamental data and one that shows peer groups of companies for each year
fun_data
import numpy as np
import pandas as pd
fun_data = {{'data': [12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 12/30/1983, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984, 1/3/1984],
'ticker': ['AA', 'KO', 'AMB', 'AMX', 'AR', 'AS', 'BUD', 'CLF', 'CRS', 'DOC', 'EC', 'EFU', 'FTX', 'HM', 'RJR', 'AA', 'KO', 'AMB', 'AMX', 'AR', 'AS', 'BUD', 'CLF', 'CRS', 'DOC', 'EC', 'EFU', 'FTX', 'HM', 'RJR'],
'mkt_cap': [10382076219, 28615981356, 89124668974, 96863568587, 69017311359, 71368368637, 36604633897, 91086629072, 87580223715, 70605054110, 93225158261, 91412455851, 76327466814, 60245266890, 33751408249, 92924687267, 97193082284, 43372080824, 94712408349, 60356743279, 32484886660, 18571138143, 64690517329, 24838868675, 23278782495, 34286838121, 46008417484, 24020283962, 3560654158, 79189294007],
'pe_ratio': [15, 24, 15, 20, 22, 19, 16, 22, 18, 13, 18, 16, 14, 24, 15, 12, 18, 22, 16, 21, 20, 16, 24, 18, 15, 24, 24, 18, 13, 18],}
df1 = pd.DataFrame(data=fun_data)
df1
peergroups
import numpy as np
import pandas as pd
peergroup = {'year': [1983, 1983, 1983, 1983, 1983, 1984, 1984, 1984, 1984, 1984, 1983, 1983, 1983, 1984, 1984, 1984],
'ticker': ['AA', 'AA', 'AA', 'AA', 'AA', 'AA', 'AA', 'AA', 'AA', 'AA', 'KO', 'KO', 'KO', 'KO', 'KO', 'KO'],
'peer': [AMX, AS, CLF, CRS, EFU, HM, AMX, AR, EC, FTX, AMB, BUD, DOC, AMB, BUD, RJR]}
df2 = pd.DataFrame(data=peergroup)
df2
Once I have those dataframes, I imagine the code doing these steps (feel free to adjust if there is a better way to do this)
- Find the date and ticker from the fun_data dataframe (12/30/1983, AA)
- Find AA's peers for 1983 from the peergroup dataframe (AMX, AS, CLF, CRS, EFU)
- Find the mkt_cap and pe_ratio data for the peers on that date from the fun_data dataframe
- Calculate the average mkt_Cap and pe_ratio for AA's peers
- Create two columns for peer_avg_mkt_cap and peer_avg_pe_ratio and input the calculated values in those columns
- Iterate for all firms with peers for all dates in fun_data
- If no peers are found for that date, leave a 0 (will fill in with data from FF library)