예제 #1
0
def create_Fred_Client(api='32b108ff32a3a99c173ef203cbc5cdaa'):
    try:
        fr = Fred(api_key=api, response_type='json')
        print('FRED client created')
    except Exception:
        print('Cannot create FRED Client')
        exit()
    return fr
예제 #2
0
 def __init__(self, code, dates, method, params, key):
     self.fr = Fred(api_key=key, response_type='df')
     self.code = code
     self.dates = dates
     self.method = method
     self.params = params
     self.start = ''
     self.key = key
예제 #3
0
def fred_search(**k):
    off = 0
    step = 1000
    result = []
    f = Fred().series
    s = lambda off: f('search', offset=off, limit=step,  **k)
    while True:
        try:
            result += s(off)['seriess']['series']
            off += step
        except KeyError:
            return result
예제 #4
0
def FRED_data_donwload():
    fr = Fred(api_key=_API_KEY, response_type='df')

    params = {
        #'limit':5,
        'output_type': 1,
        "observation_start": "2019-01-01",
        "sort_order": "desc",
        "units": "pch"
    }

    res = fr.series.observations('PCEPILFE', params=params)

    print(res)
    res.to_csv("data/Indeces_data.csv")
    def __init__(self, dataset_path):
        # request an api key from here: https://research.stlouisfed.org/docs/api/api_key.html
        key_path = os.path.join(dataset_path, 'key.txt')
        self.max_retries = 20
        self.wait_delay = 20.0
        self.dataset_path = dataset_path

        if not os.path.isfile(key_path):
            raise Exception(
                f'Cannot find FRED key file. Create an API key and place it in {key_path}. '
                'https://research.stlouisfed.org/docs/api/api_key.html')

        with open(key_path, 'r') as f:
            key = f.readline().strip()
        self.api = Fred(api_key=key, response_type='df')
예제 #6
0
def formatIndicatorLikeQuandl(indicator, **kwargs):
    """
    Uses the FRED module to access data not included 
    in QUANDL's dataset. Limits the returned FRED data
    to only date and value fields supplied. 
    
    Accepts a FRED-formatted string for the desired
    economic index (indicator).
    
    Returns the formatted indicator as a pandas
    DataFrame for downstream processing, or 
    an error message.
    """
    try:
        # set fred instance: demo API key
        fr = Fred(api_key='0242102d8f6da35b30c2c9c28d305046',
                  response_type='df')

        # get the index and limit to start_date=start_date, end_date=end_date
        indicator = fr.series.observations(indicator).loc[:, ('date', 'value')]
        # drop nans
        indicator.dropna(inplace=True)
        # convert str date to datetime
        indicator['date'] = pd.to_datetime(indicator['date'])
        # check if start and end dates are present
        if kwargs:
            # create date mask for only dates within period of dataset
            date_mask = (indicator['date'] >= kwargs['start_date']) & (
                indicator['date'] <= kwargs['end_date'])
            # filter
            indicator = indicator[date_mask]
        # set the index to the date for index processing downstream
        indicator.set_index('date', drop=True, inplace=True)
        # rename the year col for consistency
        indicator.rename({'value': 'Value'}, axis=1, inplace=True)

    except Exception as e:
        return e

    # return the index
    return indicator
예제 #7
0
from fred import Fred
import os


project_dir = os.path.dirname(os.path.abspath(__file__))



app = Flask(__name__, static_folder='../../static/dist', template_folder='../../static/client')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'



db = SQLAlchemy(app)

fr = Fred(api_key='9191e886eb8b7e932d92df410fbf0c9e',response_type='df')

#Render Webpage#
@app.route('/', methods=['GET', 'POST'])

def show_dashboard():
    if (request.form and request.form['select'] == '1'):
        api = request.form['api']
        datasource= fr.series.observations(api)
        labelsource= fr.series.details(api)
        datasource.to_sql('Graph1', con=db.engine, index=False, if_exists='replace')
        labelsource.to_sql('Labels', con=db.engine, index=False, if_exists='replace')

    dataframe=pd.read_sql('Graph1', con=db.engine)
    labelframe=pd.read_sql('Labels', con=db.engine)
예제 #8
0
def fred_release(**k):
    return Fred().release('series', **k)['seriess']['series']
예제 #9
0
def fred_observations(sid):
    return Fred().api('series', 'observations', series_id=sid)['observations']['observation']
예제 #10
0
def fred_search(**k):
    return Fred().series('search', **k)['seriess']['series']
예제 #11
0
def fred_search(target):
    return Fred().series('search', search_text=target)['seriess']['series']
예제 #12
0
#FRB api for net centric final project

#does compatible dates work :: nan values recorded - should I check for nan's?

#This project uses FRB api provided at
#https://github.com/avelkoski/FRB

from fred import Fred

fr = Fred(api_key='3b7e7d31bcc6d28556c82c290eb3572e', response_type='dict')


def searchTitle(
    searchKey,
    lucky=False
):  #finds series titles #TODO refactor this; not single purpose (i.e use helpers)
    #TODO better naming skills
    params = {'limit': 50}
    print(searchKey)
    searchRes = fr.series.search(searchKey,
                                 params=params)  #TODO search breaking
    series = []
    print('check 1')
    for result in searchRes:
        series.append((result['title'], result['id']))
        if lucky: break

    return series  #list of tuples (seried title, fRED id)


def get_obs(series_ID):
예제 #13
0
from __future__ import print_function
from fred import Fred
from helpers import *
from series import APPROVED
import config
import inflect

inf = inflect.engine()
fr = Fred(api_key=config.API_KEY, response_type=config.RESPONSE_TYPE)


# --------------- Functions that control the skill's behavior ------------------
def get_welcome_response():
    """ If we wanted to initialize the session to have some attributes we could
    add those here
    """
    session_attributes = {}
    card_title = "Welcome"
    speech_output = config.WELCOME
    # If the user either does not reply to the welcome message or says something
    # that is not understood, they will be prompted again with this text.
    reprompt_text = config.WELCOME_REPROMPT
    should_end_session = False
    return build_response(
        session_attributes,
        build_speechlet_response(card_title, speech_output, reprompt_text,
                                 should_end_session))


def get_economic_series(intent, session):
    session_attributes = {}
from fred import Fred
from dotenv import load_dotenv
import os
import series_id_defs
load_dotenv()

fr = Fred(api_key=os.getenv("FRED_API_KEY"), response_type="json")


def generate_interest_rate(start_date, country):
    params = {
        "observation_start": start_date,
    }
    indicator_data = {}
    if country == "Switzerland":
        indicator_data = fr.series.observations(
            series_id_defs.SWITZERLAND["interest_rate_id"], params=params)
    elif country == "Euro":
        indicator_data = fr.series.observations(
            series_id_defs.EURO["interest_rate_id"], params=params)
    elif country == "Canada":
        indicator_data = fr.series.observations(
            series_id_defs.CANADA["interest_rate_id"], params=params)
    elif country == "USA":
        indicator_data = fr.series.observations(
            series_id_defs.USA["interest_rate_id"], params=params)
    elif country == "Australia":
        indicator_data = fr.series.observations(
            series_id_defs.AUSTRALIA["interest_rate_id"], params=params)
    elif country == "Japan":
        indicator_data = fr.series.observations(
import time
from quarterize import quarterMean, growthRate
from dateutil.relativedelta import relativedelta

# FRED API key
# key = 'enter your key'
%run -i fred_api_key

## Getting Data from FRED ##

# loading keys
fseries = pd.read_csv('FRED_data_series.csv')
data = pd.read_csv('data.csv')

# Intialize Fred object for communicating with FRED API
fr = Fred(api_key = key, response_type = 'df')

start = datetime(1990, 1, 1)
end = datetime(2018, 10, 2)   

params = {'observation_start': start.strftime('%Y-%m-%d'),
          'observation_end': end.strftime('%Y-%m-%d')}

dates = []

while start <= end:
    dates.append(start.strftime('%Y-%m-%d'))
    start += relativedelta(months = 1)

# Retrieving data from Fred