Search code examples
pythonpython-3.xpandasdataframealpha-vantage

Alpha Vantage (Yahoo Fin alt) & Pandas Dataframe Issue - .days


Looking into alternatives now that Yahoo finance finally seems like it's gone for good. Came across Alpha Vantage which looks very interesting. The code below is running up until I try to find the delta between the start and end date, but I get the error below:

from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key=key, output_format="pandas")
data, meta_data = ts.get_daily("AAPL",outputsize="full")
days = (data.index[-1]- data.index[0]).days

output:

days = (data.index[-1]- data.index[0]).days
TypeError: unsupported operand type(s) for -: 'str' and 'str'

I've also tried:

days = (float(data.index[-1])- float(data.index[0])).days

and

days = (int(data.index[-1])- int(data.index[0])).days

Printed dataframe head as asked below

print(data.head())

Output:

             open     low   close    high     volume
2000-01-03  104.87  101.69  111.94  112.50  4783900.0
2000-01-04  108.25  101.19  102.50  110.62  4574800.0
2000-01-05  103.75  103.00  104.00  110.56  6949300.0
2000-01-06  106.12   95.00   95.00  107.00  6856900.0
2000-01-07   96.50   95.50   99.50  101.00  4113700.0

No luck with anything, any help would be much appreciated!


Solution

  • It's clear your index is a string. Convert it to datetime like this using df.index.astype:

    In [1165]: df.index = df.index.astype(np.datetime64)
    

    Now, what you're doing will work:

    In [1166]: (df.index[-1] - df.index[0]).days
    Out[1166]: 4