Package: beapy
BEApyA pandas-based python package for programatically requesting data from the U.S. Bureau of Economic Analysis (BEA).InstallationBEApyis registered on PyPI, so just use pip to install:pip install beapyorpython3 -m pip install beapyRequesting Economic DataThe BEA organizes its data into the following datasets:National Income & Product Accounts (NIPA)National Income Underlying Detail (NIUnderlyingDetail)Multinational Enterprises (MNE)Standard Fixed Assets (FixedAssets)International Transaction Accounts (ITA)International Investment Position (IIP)Input-Output Data (InputOutput)International Services Trade (IntlServTrade)GDP by Industry (GDPByIndustry)Regional Economic Data (Regional)Underlying GDP by Industry (UnderlyingGDPByIndustry)The terms in parantheses above are the labels to use when accessing the corresponding dataset usingBEApy.Dataset DataWe first initialize an instance of thebeapy.BEAclass, providing it with your personal BEA API key (request a free keyhere). Then provide the dataset name, table name, and data frequency:>>>importbeapy>>>bea=beapy.BEA(key=your_personal_api_key)>>>res=bea.data('nipa',tablename='t10101',frequency='a')# DataResponseThis would return aDataResponseobject that stores the annual data of table 't10101' in its.dataproperty, and the associated metadata in.metadata, both of which arepandasDataFrames. (See below for how to assign more intuitive, human-readable, names to the tables). Thebea.data()method's keywords necessary to construct a valid API call vary from dataset to dataset; the full list for each one can be retrieved using thebea.parameter_list(dataset)method.This second example retrieves monthly underlying data for 2015 & 2016:>>>res=bea.data('underlying',tablename='u70205s',frequency='m',year=['2015','2016'])>>>res.dataALLO03AUTO35AUTO40...UPR02UPR03UPR052015M0145.833726400.03542200.0...28471.026743.024139.02015M0246.033619700.03481400.0...28797.026946.024214.02015M0345.773924700.03740500.0...29038.026982.024199.0........................2016M1045.633382600.03173400.0...29132.027052.024529.02016M1144.853450200.03126100.0...28635.026812.024411.02016M1245.473447900.03216700.0...28492.026897.024466.0[24rowsx44columns]Note the index is not formatted as apandasDatetimeIndex, as might be expected. This is because the BEA API can return data of multiple frequencies within the same request, formatting the periods asyyyy,yyyyQq, andyyyyMmmfor annual, quarterly, and monthly data, respectively. Casting these to Datetimes would mean, for example, '2000', '2000Q1', and '2000M01' would be indistinguishable. ApandasPeriodIndex would not be able to hold the Periods of differing frequencies.Dataset MetadataEachDataResponseobject also stores the metadata for the requested table. Using the same response as in the last example, we access the metadata using the.metadataattribute:>>>res.metadataTableNameSeriesCode...CL_UNITNotesindex...NSATU70205SNSAT...LevelTable7.2.5S.AutoandT...NSADU70205SNSAD...LevelTable7.2.5S.AutoandT...NSAFU70205SNSAF...LevelTable7.2.5S.AutoandT.....................UPR03U70205SUPR03...LevelTable7.2.5S.AutoandT...UPR05U70205SUPR05...LevelTable7.2.5S.AutoandT...CPA43U70205SCPA43...LevelTable7.2.5S.AutoandT...The information stored in this DataFrame varies from dataset to dataset. For this request, the metadata fields are>>>res.metadata.columnsIndex(['TableName','SeriesCode','LineNumber','LineDescription','METRIC_NAME','CL_UNIT','Notes'],dtype='object')A lot of the meta information relates to how the dataset is organized and displayed in the BEA tables. In this example, 'LineNumber'; in other examples, 'RowNumber', 'ColumnNumber', and the like. Other common ones are 'CL_UNIT' (level, percent change, etc.);  'METRIC_NAME' (Fisher Index, ratio, current dollars); and 'Notes', which are the footnotes of the BEA table.Identifying SeriesThe BEA doesn't seem to have a consistent term to identify series in a dataset table. The NIPA & NIUnderlyingDetail datasets use the term 'SeriesCode' to uniquely label a series in the data and metadata tables, whereas the IIP dataset uses 'TimeSeriesID'. The entries in these fields are used in the.metadataindex labels, and the.datacolumn labels.The MNE dataset has a 'SeriesID' field, but it doesn't refer to a single variable in a table. Instead, the 'RowCode' & 'ColumnCode' are additionally needed to locate an individual series. In this case, the entries are concatenated together and separated by underscores to form the column/index labels. For example, a series in the MNE dataset withSeriesID = 5,RowCode = 202, andColumnCode = 5400will be uniquely identified in the metadata index and data columns by withthe label5_202_5400.The fields that are used to label series in a dataset are stored in the.series_identifiersproperty:>>>res=bea.data('mne',...)>>>res.series_identifiers['SeriesID','RowCode','ColumnCode']Requesting MetadataBEA stores information about the datasets themselves as well, providing four different methods, which return three different subclasses of theBEAResponseclass.Dataset ListThe first metadata method simply retrieves the dataset names, along with short descriptions. The.dataset_list()method ofbeapy.BEAreturns aDatasetListResponseobject, with a dictionary of those names and descriptions:>>>importbeapy>>>bea=beapy.BEA(key=your_personal_api_key)>>>res=bea.dataset_list()>>>forname,descrinres.datasets.items():>>>print(name,': ',desc)'NIPA':'Standard NIPA tables''NIUnderlyingDetail':'Standard NI underlying detail tables''MNE':'Multinational Enterprises'...Parameter ListThe second method returns aParameterListResponseobject, with a dictionary of names and summaries of the parameters that can define an API call. Those parameters differ between datasets though, so some care must be taken.>>>res=bea.parameter_list('regional')>>>forname,descinres.parameters.items():>>>print(name,': ',desc)'GeoFips':{'ParameterDataType':'string','ParameterDescription':...}'LineCode':{'ParameterIsRequiredFlag':'1','MultipleAcceptedFlag':'0',...}'TableName':{'ParameterDescription':'Regional income or product table',...}'Year':{'ParameterDataType':'string',...}Parameter ValuesThe third method returns the permissible values of a parameter:>>>res=bea.parameter_values('intlservtrade',parameter='tradedirection')>>>fork,vinres.parameters.items():>>>print(k,': ',v)'Balance':'Balance''Exports':'Exports''Imports':'Imports''SupplementalIns':'Supplemental detail on insurance transactions'Filtered Parameter ValuesThe final metadata method retrieves the permissible values of a parameter (called thetarget parameter) based on the other provided parameters, which are provided as keyword arguments. For example,>>>res=bea.filtered_parameter_values('regional',target='linecode',tablename='sainc1')>>>fork,vinres.parameters.items():>>>print(k,': ',v)'1':'[SAINC1] Personal income''2':'[SAINC1] Population''3':'[SAINC1] Per capita personal income'Multiple parameters can be filtered on at the same time; just provide them as additional keyword arguments.res=bea.filtered_parameter_values('regional',target='year',tablename='cainc5n',geofips='01001')This returns a list of the valid years in the Regional table 'cainc5n' with geographic code '01001'.Saving your API KeyThebeapy.BEAclass can be initialized with or without the BEA-provided key (gohereto request your free API key). If the code isn't provided upon initialization, it is assumed your key has been saved with the built-inbeapy.save_key()method.Before you initialize theBEAclass for the first time, use this method to record your key:>>>importbeapy>>>beapy.save_key('YOUR_PERSONAL_API_KEY_FROM_BEA')>>>bea=beapy.BEA()The stored API key is automatically overwritten by further calls of thebeapy.save_key()method.Custom Table NamesThe table names of the 'NIPA', 'NIUnderlyingDetail', and 'FixedAssets' datasets are not particularly informative or nice to look at. Thebeapymodule provides methods that can be used to define custom table names that will be stored for future use.Usebeapy.define_table_name()to create a custom reference:>>>res=bea.data('underlying',tablename='auto_output',year='2016')# raises a BEAAPIError>>>beapy.define_table_name(custom='auto_output',table_name='u70205s',dataset='underlying')>>>res=bea.data('underlying',tablename='auto_output',year='2016')# no Error; data in table 'u70205s' is returnedA similar method is provided to define other names for the datasetsbeapy.define_dataset_name(custom:str,dataset_name:str)