'Convert a DataFrame from Close to Return form without for loop in Python [closed]

I have dataframe with daily stock prices for 5 different stocks, I want to calculate daily return without using for loop so that the operation happens fast. return= ( Day2-Day1)/Day1 price

Input:

enter image description here

Output:

enter image description here

Any hint on how to do would be very helpful?

def return_form(x):
    return x.pct_change(1)

df=df.apply(return_form,axis=0)

Edit: While loading csv I have all the columns in str format. I know how to convert column datatypes but i have 100s of columns, how to convert data type of the entire dataframe from str to number?



Solution 1:[1]

The method you are looking for is called pct_change().

There goes an example:

import pandas as pd
import yfinance as yf

df = yf.download(['AAPL','GOOG','MSFT','DIS'], period='1Y')['Adj Close'].tail(5)
df

                  AAPL         DIS         GOOG       MSFT
      Date              
2022-02-14  168.880005  150.850006  2706.000000 294.391296
2022-02-15  172.789993  154.720001  2728.510010 299.850006
2022-02-16  172.550003  156.350006  2749.750000 299.500000
2022-02-17  168.880005  152.949997  2646.169922 290.730011
2022-02-18  167.300003  151.360001  2609.350098 287.929993
df.pct_change()

                 AAPL         DIS        GOOG        MSFT
      Date              
2022-02-14        NaN         NaN         NaN         NaN
2022-02-15   0.023152    0.025655    0.008319    0.018542
2022-02-16  -0.001389    0.010535    0.007784   -0.001167
2022-02-17  -0.021269   -0.021746   -0.037669   -0.029282
2022-02-18  -0.009356   -0.010396   -0.013914   -0.009631

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1