Pandas (Beats 99.3%) + MySQL solution, easy way
\n# Code\nPandas []\nimport pandas as pd\n\ndef capital_gainloss(stocks: pd.DataFrame) -> pd.DataFrame:\n    stocks[\'operation\'] = stocks[\'operation\'].apply
\n# Code\n``` Pandas []\nimport pandas as pd\n\ndef capital_gainloss(stocks: pd.DataFrame) -> pd.DataFrame:\n    stocks[\'operation\'] = stocks[\'operation\'].apply(lambda x: -1 if x == \'Buy\' else 1)\n    stocks[\'price\'] *= stocks[\'operation\']\n    return stocks.groupby("stock_name")["price"].sum().reset_index().rename(columns={"price":"capital_gain_loss"})\n```\n\n``` MySQL []\nselect stock_name, \nsum(if (operation = \'Buy\', price * -1, price)) as capital_gain_loss\nfrom Stocks\ngroup by stock_name\n\n```
['Pandas']