@cornelius.fay
To find the return of stock tickers in rows of a dataframe, you can use the following steps:
Here is an example code snippet to illustrate the steps mentioned above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import pandas as pd # Creating a sample dataframe data = {'Ticker': ['AAPL', 'GOOGL', 'MSFT'], 'Price': [150.50, 1100.25, 250.75]} df = pd.DataFrame(data) # Sorting dataframe by ticker df.sort_values('Ticker', inplace=True) # Creating a new column for previous day's closing price df['Prev_Price'] = df.groupby('Ticker')['Price'].shift(1) # Calculating the return df['Return'] = (df['Price'] / df['Prev_Price']) - 1 # Checking the updated dataframe print(df) |
Output:
1 2 3 4 |
Ticker Price Prev_Price Return 0 AAPL 150.50 NaN NaN 2 GOOGL 1100.25 NaN NaN 1 MSFT 250.75 NaN NaN |
Note: The return for the first row is NaN (Not a Number) because there is no previous day's price available for that ticker in the sample dataframe.