Home > Mobile >  Python merge dataframes and groupby
Python merge dataframes and groupby

Time:12-10

I have four dataframes vom yfinance:

dataVIX = yf.download('^VIX', '2008-01-01', date.today(), auto_adjust=True)
dataGOLD = yf.download('GLD', '2008-01-01', date.today(), auto_adjust=True)
dataBOND = yf.download('^TNX', '2008-01-01', date.today(), auto_adjust=True)
datasp500 = yf.download('^GSPC', '2008-01-01', date.today(), auto_adjust=True)

Now I would like to merge those four data frames into one and group by date. Like this:

date          Vix                 Gold
2008-01-01    Closing Value X     Closing Value Y ...
...

Everything I try comes out as bs. Any suggestions?

CodePudding user response:

You can download a list of tickers:

tickers = ['^VIX', 'GLD', '^TNX', '^GSPC']
df = yf.download(tickers, '2008-01-01', date.today(), auto_adjust=True)['Close']
print(df)

# Output:
                   GLD        ^GSPC   ^TNX       ^VIX
Date                                                 
2007-12-31   82.459999  1468.359985  4.035  22.500000
2008-01-02   84.860001  1447.160034  3.901  23.170000
2008-01-03   85.570000  1447.160034  3.901  22.490000
2008-01-04   85.129997  1411.630005  3.854  23.940001
2008-01-07   84.769997  1416.180054  3.839  23.790001
...                ...          ...    ...        ...
2021-12-02  165.240005  4577.100098  1.448  27.950001
2021-12-03  166.630005  4538.430176  1.343  30.670000
2021-12-06  166.220001  4591.669922  1.434  27.180000
2021-12-07  166.809998  4686.750000  1.480  21.889999
2021-12-08  166.899994  4701.209961  1.509  19.900000

[3511 rows x 4 columns]
  • Related