Unable to add values to a pandas DataFrame

Question:

I am trying to find the MACD(Moving Average Convergence Divergence) for a few stocks.I am using Pandas_ta, yfinance and pandas libraries. But When I am trying to add the Macd values to the dataframe I am getting this error:

IndexError: iloc cannot enlarge its target object

My code is :

import pandas as pd 
import pandas_ta as ta
import yfinance as yf
import datetime as dt
import matplotlib.pyplot as plt
start=dt.datetime.today()-dt.timedelta(365)
end=dt.datetime.today()
zscore=pd.DataFrame()
rsi=pd.DataFrame()
tickers=['2060.SR' , '2160.SR', '3002.SR', '4007.SR', '3005.SR', '3004.SR' , '2150.SR']
macd=pd.DataFrame()
for i in tickers:
  df=pd.DataFrame(yf.download(i, start=start, end=end, interval="1mo"))

  df.columns = map(str.lower, df.columns)    
  macd=df.ta.macd()
  

Can someone let me know where my mistake is and how to solve this error. thanks

Asked By: rzee1991

||

Answers:

I am not sure which line gave you this error.

But please note that in the loop you are not adding data, but you are re-writing the data again and again:

for i in tickers:
  df=pd.DataFrame(yf.download(i, start=start, end=end, interval="1mo"))

If you want to append, do the following:

agg_df = pd.DataFrame()
for i in tickers:
  df=pd.DataFrame(yf.download(i, start=start, end=end, interval="1mo"))
  agg_df = agg_df.append(df)
Answered By: gtomer

df=df.merge(macd, on="Date")

Answered By: rzee1991

I used df.append(row) in the past which is deprecated since pandas 1.4.
most logical for me is the approach:
df.loc[len(df)] = ['list', 'of', 'elements'] # len(df.columns)

other methods are provided here: https://sparkbyexamples.com/pandas/how-to-append-row-to-pandas-dataframe/

Answered By: Oliver Prislan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.