1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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()