from urllib.request import Request, urlopen
import pandas as pd
import os
import matplotlib.pyplot as plt
import seaborn as sns
if(os.path.isfile('igpm.csv')):
df = pd.read_csv('igpm.csv', encoding = "utf-8", delimiter=';', index_col=0)
print()
print('Dados extraídos do arquivo local.')
print()
else:
req = Request('https://ihack.com.br/dados/igpm.html', headers={'User-Agent': 'Mozilla/5.0'})
pagina = urlopen(req).read()
igpm = pd.read_html(pagina)
igpm = igpm[0]
igpm = igpm[[0,3]]
igpm = igpm.iloc[1:]
# igpm[3] = igpm[3].str.replace(' ', '')
igpm[3] = igpm[3].str.replace(',', '.')
df = igpm[3].astype(float) / 10000
df = pd.concat([igpm, df], axis=1)
df.columns = ['Data', 'IGPM_OLD', 'IGPM']
df = df[['Data','IGPM']]
df.set_index(['Data'], inplace=True)
del(igpm)
# Reverse order
df = df.iloc[::-1]
df.to_csv('igpm.csv', sep=';', encoding='utf-8')
print()
print('Dados extraídos da Internet.')
print()
print(df)
sns.set_style('whitegrid')
df['IGPM'].plot()
plt.legend(loc=7, bbox_to_anchor=(1.0, 0.5))
plt.xlabel('Date')
plt.ylabel('IGPM')
plt.title('IGPM Mensal')
plt.show()