fmilthaler / FinQuant

A program for financial portfolio management, analysis and optimisation.
MIT License
1.38k stars 190 forks source link

'Index' object has no attribute 'tz_localize' #70

Closed Michael5531 closed 1 year ago

Michael5531 commented 2 years ago

Hi there,

Tried to download the stock price from yfinance, used the code snippest in documentation.

from finquant.portfolio import build_portfolio names = ['GOOG', 'AMZN', 'MCD', 'DIS'] pf = build_portfolio(names=names, data_api="yfinance")

But once I run it, it says 'AttributeError: 'Index' object has no attribute 'tz_localize''

Thanks in advance.

Leohanhart commented 1 year ago

You can work around this by collecting the data with the updated version of YFinance, bind the data toghetter using this function, put the tickers with the data in one Dict to use this function down below "create_data_frame_of_tickers"

after this, insert the data in the portfolio_optimizer.

pf = build_portfolio(data=data)

set optimalization

    opt_w, opt_res = pf.mc_optimisation(num_trials=500)

Now you have the same result.

def create_data_frame_of_tickers(self, tickers: list, data: dict):
    """

    r_data.mean(axis=1).pct_change().cumsum().plot()

    r_data.pct_change().cumsum().plot()

    Parameters
    ----------
    tickers : list
        DESCRIPTION.
    data : dict
        DESCRIPTION.

    Returns
    -------
    None.

    """

    first: bool = True
    r_data = 0
    for i in tickers:

        #
        sdata = data[i]

        # select data from dict
        df = sdata

        df = df.tail(520)
        # first column selected
        first_column = df.iloc[:, 0]

        # set to frame
        xdf = first_column.to_frame()

        # rename to ticker
        xdf = xdf.rename(columns={xdf.columns[0]: str(i)})

        if first:

            r_data = xdf
            first = False

        else:

            r_data = pd.concat([r_data, xdf], axis=1)

    return r_data
fmilthaler commented 1 year ago

Thank you @Michael5531 for reporting this issue and @Leohanhart for providing a work around. Much appreciated! :)

I guess this issue comes from an older version of yfinance. As I was unable to replicate this, I'll close this issue now.