Calculating Stock price returns using python

Import the libraries

import pandas as pd

Load the data

# read the data
stock = pd.read_csv("stock.csv")
# display the first 5 rows data
stock.head()

We can see that we have the Daily Stock Price Closing Data.

Calculate the return

To calculate the 1-day returns, we need the previous closing price.

# shift the close prices by 1 position since we need 1-day previous close.
stock['previous_close'] = stock['close'].shift(1)
# display the data
stock.head()

Now that we have the Data in required format, we can calculate the daily returns.

# 1-day returns
stock['return'] = (stock['close'] / stock['previous_close']) - 1
# % return
stock['% return'] = stock['return'] * 100
# display the data
stock.head()