Home > Enterprise >  How to import from investpy and then plot?
How to import from investpy and then plot?

Time:03-09

I am trying to get a nice line chart of NASDAQ (data from investpy) from a certain date, but for some reason the plot doesn't show (even though it runs without errors)

import investpy as inv
import matplotlib.pyplot as plt
import pandas as pd

TICKER = "Nasdaq 100"
COUNTRY = "United States"
FROM_DATE = "01/03/2022"
TO_DATE = "07/03/2022"

historical_data = inv.indices.get_index_historical_data(index=TICKER,
                                        country=COUNTRY,
                                        from_date=FROM_DATE,
                                        to_date=TO_DATE)

data = historical_data.reset_index()

data.plot(x = 'Date', y = 'Close')
print(data)
plt.show

This is the what the dataframe looks like from the print function.

           Date      Open      High       Low     Close     Volume Currency
0    1985-09-26    110.64    110.64    110.64    110.64          0      USD
1    1985-09-27    110.64    110.64    110.64    110.64          0      USD
2    1985-09-30    110.62    110.62    110.62    110.62          0      USD
3    1985-10-01    112.14    112.14    112.14    112.14          0      USD
4    1985-10-02    110.84    110.84    110.84    110.84          0      USD
...         ...       ...       ...       ...       ...        ...      ...
9181 2022-03-01  14197.66  14271.54  13907.94  14005.99  262503616      USD
9182 2022-03-02  14072.79  14290.67  13974.40  14243.69  232912464      USD
9183 2022-03-03  14335.16  14341.12  13965.59  14035.21  230210736      USD
9184 2022-03-04  13957.60  13992.81  13738.61  13837.83  244425040      USD
9185 2022-03-07  13855.48  13876.28  13314.68  13319.38  304169408      USD

[9186 rows x 7 columns]

Would you be able to tell me what i am doing wrong?

Thanks in advance...

CodePudding user response:

This should work:

import investpy as inv
import matplotlib.pyplot as plt
import pandas as pd

TICKER = "Nasdaq 100"
COUNTRY = "United States"
FROM_DATE = "01/03/2022"
TO_DATE = "07/03/2022"

historical_data = inv.indices.get_index_historical_data(index=TICKER,
                                        country=COUNTRY,
                                        from_date=FROM_DATE,
                                        to_date=TO_DATE)

data = historical_data.reset_index()

data.plot(x = 'Date', y = 'Close')
print(data)
plt.show()

I only added parentheses at the end as plt.show will not work if called like that. It will only work if you call it like plt.show().

CodePudding user response:

I would recommend to use DataFrame.plot.line that "Plot Series or DataFrame as lines. This function is useful to plot lines using DataFrame’s values as coordinates."

You can use:

data.plot.line(x='Date', y='Close')

# or a simple call

data.plot.line()
  • Related