Giter VIP home page Giter VIP logo

pysgs's Introduction

codecov.io Read the docs!

pic 1 SGS

Introduction

This library provides a pure Python interface for the Brazilian Central Bank's Time Series Management System (SGS) api. It works with Python 3.5 and above.

SGS is a service with more than 18,000 time series with economical and financial information. This library is intended to make it easier for Python programmers to use this data in projects of any kind, providing mechanisms to search for, extract and join series.

Quickstart

Access time series data with sgs is very simple

Begin by importing the sgs module:

import sgs

Now, let's try to get a time serie. For this example, let's get the "Interest rate - CDI" time serie in 2018, wich has the code 12.

CDI_CODE = 12
ts = sgs.time_serie(CDI_CODE, start='02/01/2018', end='31/12/2018')

Now, we have a Pandas Series object called ts, with all the data and the index representing the dates.

ts.head()
2018-01-02 0.026444
2018-01-03 0.026444
2018-01-04 0.026444
2018-01-05 0.026444
2018-01-08 0.026444

Feature Suport

  • Get time serie data with an one-liner using sgs.time_serie
  • Create a dataframe from a list of time series codes with sgs.dataframe
  • Search time series by text or code with sgs.search_ts
  • Get metadata from all the series in a dataframe using sgs.metadata
  • Support to search and metadata in English and Portuguese
  • Automatic retry
  • Automatic cached requests

Installation

To install, simply use pip:

$ pip install sgs

Documentation

Complete documentation is available at https://pysgs.readthedocs.io/en/stable/.

pysgs's People

Contributors

gpetrini avatar opardal avatar rafpyprog avatar royopa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

pysgs's Issues

Problema de SO (Linux/Windows)

Prezado, muito obrigado pela excelente contribuição com seu pacote para a comunidade.

Estou usando o módulo para obter a taxa Selic.

Para windows funciona perfeitamente, porém em linux o seguinte comando me retorna um dataframe com nomes de colunas diferentes:

sgs = SGS()
selic = sgs.get_valores_series(series.SELIC_META, "04/01/2010", dt.date.today().strftime("%d/%m/%Y"))

Em linux tenho as seguintes colunas: 432

                 432

2010-01-04 8,75
2010-01-05 8,75
2010-01-06 8,75
2010-01-07 8,75
2010-01-08 8,75

Em windows ele me retorna como colunas (data, valor)

Obrigado pela atenção.

Problema na data de inicio e fim

Caro, obrigado pelo excelente trabalho e pela nova versão.
sgs.dataframe([20577,20669,20745,21117,20882], start='17/08/2019', end='18/08/2019')
Quando busco os indices no intervalo acima ele me retorna o seguinte:
20577 20669 20745 21117 20882 2019-06-01 203887.0 11921.0 20.84 1.99 84.53
Há alguma diferenciação na busca de dados mensais?

Erro de locale em instância docker (Debian / Python 3)

Estou testando em uma instância Debian (docker) em inglês e recebo o erro (Error: unsupported locale setting) até quando tento executar o exemplo do README.md.

OS INFO:

PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
NAME="Debian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
ID=debian
HOME_URL="http://www.debian.org/"
SUPPORT_URL="http://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

Tentando chamar o time_serie ou o dataframe, quando ele chama setlocale(locale.LC_TIME, locales[language] provavelmente não rola o match com a language passada e acaba causando o erro.

Como eu to com um prazo apertado de entrega, não vou conseguir cavar mais fundo e debugar pra ajudar no fix. Mas conseguindo entregar posso fazer o debug e depois subir aquele PR amigo.

De qualquer forma, segue o stack trace:

---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
<ipython-input-89-981dba7d0821> in <module>
      5 
      6 CDI_CODE = 12
----> 7 ts = sgs.dataframe(CDI_CODE, start='02/01/2018', end='31/12/2018')

~/phoenix-worker/environments/python3/lib/python3.6/site-packages/sgs/dataframe.py in dataframe(ts_codes, start, end)
     41     series = []
     42     for code in ts_codes:
---> 43         ts = time_serie(code, start, end)
     44         series.append(ts)
     45 

~/phoenix-worker/environments/python3/lib/python3.6/site-packages/sgs/ts.py in time_serie(ts_code, start, end)
     40     for i in api.get_data(ts_code, start, end):
     41         values.append(i["valor"])
---> 42         index.append(to_datetime(i["data"], "pt"))
     43 
     44     # Transform empty strings in null values

~/phoenix-worker/environments/python3/lib/python3.6/site-packages/sgs/common.py in to_datetime(date_string, language)
     21         locales = {"pt": "Portuguese_Brazil.1252", "en": "Portuguese_Brazil.1252"}
     22 
---> 23     locale.setlocale(locale.LC_TIME, locales[language])
     24 
     25     dd_mm_aaaa = "%d/%m/%Y"

~/phoenix-worker/environments/python3/lib/python3.6/locale.py in setlocale(category, locale)
    596         # convert to string
    597         locale = normalize(_build_localename(locale))
--> 598     return _setlocale(category, locale)
    599 
    600 def resetlocale(category=LC_ALL):

Error: unsupported locale setting

Reprodução do Exemplo

Ola @rafpyprog ,

Tentei reproduzir o seu primeiro exemplo.

from sgs import SGS
sgs = SGS()
df = sgs.get_valores_series(12, '01/01/2016', '31/12/2016')

Quando executei a terceira linha recebi o seguinte erro:

Traceback (most recent call last):

File "", line 1, in
df = sgs.get_valores_series(12, '01/01/2016', '31/12/2016')

File "c:\python35\lib\site-packages\sgs\sgs.py", line 83, in get_valores_series
raise ValueError(msg)

ValueError: Valores não encontrados. Verifique o código da série e a data de vigência.

Fui verificar a resposta do request e isso foi o que encontrei:

b'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">soapenv:Bodysoapenv:Faultsoapenv:Server.userExceptionbr.gov.bcb.pec.sgs.comum.excecoes.SGSNegocioException: Value(s) not found</soapenv:Fault></soapenv:Body></soapenv:Envelope>'

Você sabe o que pode estar acontecendo?

Obrigado

locale.Error: unsupported locale setting

Boa tarde, parabéns pelo trabalho.

Tentei reproduzir o exemplo e imprimir uma série do cdi mas está aparecendo o seguinte erro:

File "...\Python\Python37\lib\site-packages\sgs\ts.py", line 42, in time_serie
index.append(to_datetime(i["data"], "pt"))
File "...\Python\Python37\lib\site-packages\sgs\common.py", line 18, in to_datetime
locale.setlocale(locale.LC_TIME, locales[language])
File "...\Python\Python37\lib\locale.py", line 604, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting

Você pode ajudar???

Erro ao tentar pegar metadata da serie 21554

Boa Tarde, quando tento coletar a serie 21554 recebo os seguinte erro

codigo:

ts = sgs.time_serie(i, start=first_date_str, end=last_date_str)

Nesse caso i é o numero da serie, first_date_str e last_date_str são as datas do primeiro e ultimo dado da serie, que vem no metadata ( search_ts )

i = 21554
first_date_str = "31/12/1992"
last_date_str = "01/06/2019"

Erro:

Traceback (most recent call last): File ".\populate_db.py", line 41, in <module> ts = sgs.time_serie(i, start=first_date_str, end=last_date_str) File "C:\Users\U002875\AppData\Local\Continuum\anaconda3\lib\site-packages\sgs\ts.py", line 44, in time_serie return pd.Series(values, index, name=ts_code, dtype=np.float) File "C:\Users\U002875\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py", line 314, in __init__ data = sanitize_array(data, index, dtype, copy, raise_cast_failure=True) File "C:\Users\U002875\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\internals\construction.py", line 679, in sanitize_array subarr = _try_cast(data, dtype, copy, raise_cast_failure) File "C:\Users\U002875\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\internals\construction.py", line 793, in _try_cast subarr = construct_1d_ndarray_preserving_na(subarr, dtype, copy=copy) File "C:\Users\U002875\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\dtypes\cast.py", line 1289, in construct_1d_ndarray_preserving_na subarr = np.array(values, dtype=dtype, copy=copy) ValueError: could not convert string to float:

Unsupported locale

Boa Tarde, quando tento rodar o codigo informado no README do projeto recebo o seguinte erro.

import sgs

CDI_CODE = 12
ts = sgs.time_serie(CDI_CODE, start='02/01/2018', end='31/12/2018')

Erro:

"locale.Error: unsupported locale setting"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.