Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

For loop not adding the column to a df

Joined
Feb 3, 2023
Messages
70
I'm using a for loop with if statements to create a column ['EWMA'] filled partially recoursively. For the min Date observed the value is computed using the SD of the sample while for all the others I recall the EWMA value of the previous day. The function seems to work but I don't know why the column is not added to the df (thus, df['EWMA'] doesn't exist)

Code:
import pandas as pd
import numpy as np
from numpy import log as ln
import statistics
df=pd.read_excel(r'C:\Users\cristinamariaromano\Downloads\RACE.TSLAMI.xlsx', parse_dates=['Date'])
#Returns
df['Returns RACE'] = ln(df['Close RACE'].div(df['Close RACE'].shift(3)))
df['Returns RACE'] = df['Returns RACE'].replace(np.nan, 0)
df['Returns TSLA'] = ln(df['Close TSLA'].div(df['Close TSLA'].shift(3)))
df['Returns TSLA'] = df['Returns TSLA'].replace(np.nan, 0)
lam=float(0.98)
SD_sample= float(statistics.stdev(df['Returns RACE']))
print(SD_sample)
min_Date=df['Date'].min()
for i in df['Date']:
      if min_Date == True:
         df['EWMA'] == ((lam*(SD_sample**2)+(1-lam)*(df['Returns RACE']**2)))**1/2
      if min_Date == False:
        df['EWMA'] == (lam*((df['EWMA'].shift(1))**2)+(1-lam)*(df['Returns RACE']**2))**1/2
print(df)
 
Member
Joined
Feb 3, 2023
Messages
131
In your code, you are using a double equal sign == instead of a single equal sign = when assigning values to the 'EWMA' column of the DataFrame.

Code:
min_Date = df['Date'].min()
for i in df.index:
    if df.loc[i, 'Date'] == min_Date:
        df.loc[i, 'EWMA'] = ((lam*(SD_sample**2)+(1-lam)*(df.loc[i, 'Returns RACE']**2)))**1/2
    else:
        df.loc[i, 'EWMA'] = (lam*((df.loc[i-1, 'EWMA'])**2)+(1-lam)*(df.loc[i, 'Returns RACE']**2))**1/2
 
Top