How to find the return of stock tickers in rows of dataframe?

How to find the return of stock tickers in rows of dataframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by roderick_marquardt , 4 months ago

@cornelius.fay 

To find the return of stock tickers in rows of a dataframe, you can use the following steps:

  1. Ensure that your dataframe has a column representing the stock tickers and another column representing the prices or closing prices of the stocks for each time period.
  2. Create a new column in the dataframe to store the returns. You can name this column 'Return' or any other suitable name.
  3. Use the shift() function to create a new column that contains the previous day's price for each stock ticker. This can be done by subtracting 1 from the current row's date index while selecting the price column.
  4. Calculate the return by dividing the current day's price by the previous day's price and subtracting 1. Store the result in the 'Return' column.


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.