Generate citations automatically

[2]:
import beaapi
from datetime import datetime

[3]:
# Get key from unversioned file
from dotenv import dotenv_values
beakey = dotenv_values()["beakey"]
[59]:
bibtex_str_template = """@misc{{{0},
    title        = "{1}",
    author       = "{{U.S.}} {{B}}ureau of {{E}}conomic {{A}}nalysis",
    year         = {2},
    note         = "Accessed: {3}"
}}
"""
formatted_template = "U.S. Bureau of Economic Analysis, “{0},” (accessed {1})."
def citation_named(table_name, cite_suffix=""):
    # Generates a single-line formatted cite and bibtek entry to manually import.
    now  = datetime.today()
    access_date = now.strftime('%Y-%m-%d')
    formatted = formatted_template.format(table_name, access_date)
    citekey = "bea"+cite_suffix

    bibtex_str = bibtex_str_template.format(citekey, table_name, now.strftime('%Y'), access_date)
    # howpublished = "\\url{{https://www.nasa.gov/nh/pluto-the-other-red-planet}}",
    return (formatted, bibtex_str)

def citation_search(tableid, beakey):
    # get's tablename from metadata_search, only for NIPA, NIUnderlyingDetail and FixedAssets
    search_data = beaapi.search_metadata(tableid, beakey)
    table_name2 = search_data[search_data["TableId"]==tableid]['TableName'].iloc[0]
    return(citation_named(table_name2, tableid))

Next we’ll go through each dataset and try to generate one

Working

[4]:
# NIPA
tableid = 'T20305'
bea_tbl = beaapi.get_data(beakey, datasetname='NIPA', TableName=tableid, Frequency='Q', Year='2015')
[12]:
# check out if any attrs might be helpful
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
display(bea_tbl.attrs['detail']['Notes'])
dict_keys(['params', 'response_size', 'detail', 'time_invariant_keys', 'time_invariant_vars', 'time_variant_keys', 'time_variant_vars', 'time_variant_only_vars', 'index_cols'])
Extra detail keys:dict_keys(['Statistic', 'UTCProductionTime', 'Dimensions', 'Notes'])
Let's look at some interesting ones.
Statistic: NIPA Table
Notes corresponding to NoteRef:
NoteRef NoteText
0 T20305 Table 2.3.5. Personal Consumption Expenditures...
1 T20305.1 1. Net expenses of NPISHs, defined as their gr...
2 T20305.2 2. Gross output is net of unrelated sales, sec...
3 T20305.3 3. Excludes unrelated sales, secondary sales, ...
4 T20305.4 4. Food consists of food and beverages purchas...
5 T20305.5 5. Consists of gasoline and other energy goods...
6 T20305.6 6. Market-based PCE is a supplemental measure ...
[41]:
# Two methods. The second one looks better as we don't have to parse out the units and LastRevised
table_name1 = bea_tbl.attrs['detail']['Notes'].iloc[0,1]
print(table_name1)


formatted, bibtex_str = citation_search(tableid, beakey)
print(formatted)
print(bibtex_str)
Table 2.3.5. Personal Consumption Expenditures by Major Type of Product [Billions of dollars] - LastRevised: September 29, 2022
U.S. Bureau of Economic Analysis, “Table 2.3.5. Personal Consumption Expenditures by Major Type of Product,” (accessed 2022-10-18).
@misc{beaT20305,
    title        = "Table 2.3.5. Personal Consumption Expenditures by Major Type of Product",
    author       = "{U.S.} {B}ureau of {E}conomic {A}nalysis",
    year         = 2022,
    note         = "Accessed: 2022-10-18"
}

Now just use the metadata search for NIUnderlyingDetail and FixedAssets

[44]:
# NIUnderlyingDetail
TableName="U001A"
bea_tbl = beaapi.get_data(beakey, datasetname='NIUnderlyingDetail', TableName=TableName, Frequency='Q', Year='1995')
print(bea_tbl.attrs['detail']['Notes'].iloc[0,1])
formatted, bibtex_str = citation_search(TableName, beakey)
print(formatted)
print(bibtex_str)
Table 1AU. Real Manufacturing and Trade Inventories, Seasonally Adjusted, End of Period [Chained 1996 dollars, 1967-96, SIC] [Millions of chained (1996) dollars; seasonally adjusted, end of period] - LastRevised: July 27, 2018
U.S. Bureau of Economic Analysis, “Table 1AU. Real Manufacturing and Trade Inventories, Seasonally Adjusted, End of Period [Chained 1996 dollars, 1967-96, SIC],” (accessed 2022-10-18).
@misc{beaU001A,
    title        = "Table 1AU. Real Manufacturing and Trade Inventories, Seasonally Adjusted, End of Period [Chained 1996 dollars, 1967-96, SIC]",
    author       = "{U.S.} {B}ureau of {E}conomic {A}nalysis",
    year         = 2022,
    note         = "Accessed: 2022-10-18"
}

[45]:
# FixedAssets
TableName="FAAt101"
bea_tbl = beaapi.get_data(beakey, datasetname='FixedAssets', TableName=TableName, Year='2013')
print(bea_tbl.attrs['detail']['Notes'].iloc[0,1])
formatted, bibtex_str = citation_search(TableName, beakey)
print(formatted)
print(bibtex_str)
Table 1.1. Current-Cost Net Stock of Fixed Assets and Consumer Durable Goods [Billions of dollars; yearend estimates] - LastRevised: September 30, 2022
U.S. Bureau of Economic Analysis, “Table 1.1. Current-Cost Net Stock of Fixed Assets and Consumer Durable Goods,” (accessed 2022-10-18).
@misc{beaFAAt101,
    title        = "Table 1.1. Current-Cost Net Stock of Fixed Assets and Consumer Durable Goods",
    author       = "{U.S.} {B}ureau of {E}conomic {A}nalysis",
    year         = 2022,
    note         = "Accessed: 2022-10-18"
}

For regional we try a different approach

[54]:
#Regional
tablename="CAINC1"
spec = {"TableName":tablename,"LineCode":"2","Year":"2012,2013","GeoFips":"09003,53033"}
bea_tbl = beaapi.get_data(beakey, 'Regional', **spec)

# check out attrs
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
print("Notes corresponding to NoteRef:")
display(bea_tbl.attrs['detail']['Notes'])

dict_keys(['params', 'response_size', 'detail', 'time_invariant_keys', 'time_invariant_vars', 'time_variant_keys', 'time_variant_vars', 'time_variant_only_vars', 'index_cols'])
Extra detail keys:dict_keys(['Statistic', 'UnitOfMeasure', 'PublicTable', 'UTCProductionTime', 'NoteRef', 'Dimensions', 'Notes'])
{'Statistic': 'Population', 'UnitOfMeasure': 'Number of persons', 'PublicTable': 'CAINC1 County and MSA personal income summary: personal income, population, per capita personal income', 'UTCProductionTime': '2022-10-18T20:18:33.067', 'NoteRef': '1', 'Dimensions':          Name DataType  IsValue
0        Code   string        0
1     GeoFips   string        0
2     GeoName   string        0
3  TimePeriod   string        0
4   DataValue  numeric        1
5     CL_UNIT   string        0
6   UNIT_MULT  numeric        0, 'Notes':   NoteRef                                           NoteText
0       1  Census Bureau midyear population estimates. Es...
1          Metropolitan Areas are defined (geographically...
2   Note.  All dollar estimates are in thousands of curre...
3          Last updated: November 16, 2021-- new statisti...}
Notes corresponding to NoteRef:
NoteRef NoteText
0 1 Census Bureau midyear population estimates. Es...
1 Metropolitan Areas are defined (geographically...
2 Note. All dollar estimates are in thousands of curre...
3 Last updated: November 16, 2021-- new statisti...
[58]:
formatted, bibtex_str = citation_named(bea_tbl.attrs['detail']['PublicTable'], cite_suffix=tablename)
print(formatted)
print(bibtex_str)
U.S. Bureau of Economic Analysis, “CAINC1 County and MSA personal income summary: personal income, population, per capita personal income,” (accessed 2022-10-18).
@misc{beaCAINC1,
    title        = "CAINC1 County and MSA personal income summary: personal income, population, per capita personal income",
    author       = "{U.S.} {B}ureau of {E}conomic {A}nalysis",
    year         = 2022,
    note         = "Accessed: 2022-10-18"
}

Not working

For the rest, we can’t use metadata search and none of the attrs[‘detail’] are helpful

[53]:
#underlyingGDPbyIndustry
spec = {"Year":"2013,2012","Industry":"ALL","tableID":"210,211","Frequency":"A,Q"}
bea_tbl = beaapi.get_data(beakey, 'underlyingGDPbyIndustry', **spec)

# check out attrs
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
print("Notes corresponding to NoteRef:")
display(bea_tbl.attrs['detail']['Notes'])
underlyinggdpbyindustry currenty only returns Annual results (even if you ask for additional frequencies).
dict_keys(['params', 'response_size', 'detail', 'time_invariant_keys', 'time_invariant_vars', 'time_variant_keys', 'time_variant_vars', 'time_variant_only_vars', 'index_cols'])
Extra detail keys:dict_keys(['Statistic', 'UTCProductionTime', 'Dimensions', 'Notes'])
{'Statistic': 'GDP by Industry Table', 'UTCProductionTime': '2022-10-18T20:17:30.463', 'Dimensions':    Ordinal                 Name DataType  IsValue
0        1              TableID  numeric        0
1        2            Frequency   string        0
2        3                 Year   string        0
3        4              Quarter   string        0
4        5             Industry   string        0
5        6  IndustryDescription   string        0
6        7            DataValue  numeric        1, 'Notes':       NoteRef                                           NoteText
0   210.1.A,Q  1. Consists of agriculture, forestry, fishing,...
1   210.2.A,Q  2. Consists of utilities; wholesale trade; ret...
2   210.3.A,Q  3. Consists of computer and electronic product...
3   210.0.A,Q  Note. Detail may not add to total due to round...
4   210.0.A,Q  Note. The Bureau of Economic Analysis does not...
5         210    U.Value Added by Industry [Billions of dollars]
6   211.1.A,Q  1. Consists of agriculture, forestry, fishing,...
7   211.2.A,Q  2. Consists of utilities; wholesale trade; ret...
8   211.3.A,Q  3. Consists of computer and electronic product...
9   211.0.A,Q  Note. Detail may not add to total due to round...
10  211.0.A,Q  Note. The Bureau of Economic Analysis does not...
11        211  U.Value added by Industry as a Percentage of G...}
Notes corresponding to NoteRef:
NoteRef NoteText
0 210.1.A,Q 1. Consists of agriculture, forestry, fishing,...
1 210.2.A,Q 2. Consists of utilities; wholesale trade; ret...
2 210.3.A,Q 3. Consists of computer and electronic product...
3 210.0.A,Q Note. Detail may not add to total due to round...
4 210.0.A,Q Note. The Bureau of Economic Analysis does not...
5 210 U.Value Added by Industry [Billions of dollars]
6 211.1.A,Q 1. Consists of agriculture, forestry, fishing,...
7 211.2.A,Q 2. Consists of utilities; wholesale trade; ret...
8 211.3.A,Q 3. Consists of computer and electronic product...
9 211.0.A,Q Note. Detail may not add to total due to round...
10 211.0.A,Q Note. The Bureau of Economic Analysis does not...
11 211 U.Value added by Industry as a Percentage of G...
[52]:
#GDPbyIndustry
spec = {'Year':'2012,2011','Industry':'ALL','tableID':'1, 2', "Frequency":"A,Q"}
bea_tbl = beaapi.get_data(beakey, 'GDPbyIndustry', **spec)

# check out attrs
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
print("Notes corresponding to NoteRef:")
display(bea_tbl.attrs['detail']['Notes'])
dict_keys(['params', 'response_size', 'detail', 'time_invariant_keys', 'time_invariant_vars', 'time_variant_keys', 'time_variant_vars', 'time_variant_only_vars', 'index_cols'])
Extra detail keys:dict_keys(['Statistic', 'UTCProductionTime', 'Dimensions', 'Notes'])
{'Statistic': 'GDP by Industry Table', 'UTCProductionTime': '2022-10-18T20:13:58.440', 'Dimensions':    Ordinal                 Name DataType  IsValue
0        1              TableID  numeric        0
1        2            Frequency   string        0
2        3                 Year   string        0
3        4              Quarter   string        0
4        5             Industry   string        0
5        6  IndustryDescription   string        0
6        7            DataValue  numeric        1, 'Notes':    NoteRef                                           NoteText
0  1.1.A,Q  1. Consists of agriculture, forestry, fishing,...
1  1.2.A,Q  2. Consists of utilities; wholesale trade; ret...
2  1.3.A,Q  3. Consists of computer and electronic product...
3  1.0.A,Q  Note. Detail may not add to total due to round...
4        1      Value Added by Industry [Billions of dollars]}
Notes corresponding to NoteRef:
NoteRef NoteText
0 1.1.A,Q 1. Consists of agriculture, forestry, fishing,...
1 1.2.A,Q 2. Consists of utilities; wholesale trade; ret...
2 1.3.A,Q 3. Consists of computer and electronic product...
3 1.0.A,Q Note. Detail may not add to total due to round...
4 1 Value Added by Industry [Billions of dollars]
[51]:
#IntlServTrade
spec = {"AreaOrCountry":"Germany","Year":"1999,2000"}
bea_tbl = beaapi.get_data(beakey, 'IntlServTrade', **spec)

# check out attrs
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
print("Notes corresponding to NoteRef:")
display(bea_tbl.attrs['detail']['Notes'])
dict_keys(['params', 'response_size', 'detail', 'time_invariant_keys', 'time_invariant_vars', 'time_variant_keys', 'time_variant_vars', 'time_variant_only_vars', 'index_cols'])
Extra detail keys:dict_keys(['TsLastUpdated', 'EarliestFullYear', 'LatestFullYear', 'Dimensions', 'Notes'])
{'TsLastUpdated': '2022-07-07 10:00:00.000', 'EarliestFullYear': '1999', 'LatestFullYear': '2021', 'Dimensions':     Ordinal                   Name DataType  IsValue
0         1          TypeOfService   string        0
1         2         TradeDirection   string        0
2         3            Affiliation   string        0
3         4          AreaOrCountry   string        0
4         5                   Year   string        0
5         6           TimeSeriesId   string        0
6         7  TimeSeriesDescription   string        0
7         8             TimePeriod   string        0
8         9                CL_UNIT   string        0
9        10              UNIT_MULT   string        0
10       11              DataValue  numeric        1, 'Notes':          NoteRef                                           NoteText
0            (D)  Suppressed to avoid the disclosure of data of ...
1  IntlServ2.3:1  Courier services are included in "Air transpor...
2  IntlServ2.3:2  Insurance services transactions are considered...
3  IntlServ2.3:3  Outcomes of research and development include p...
4  IntlServ2.3:4  This category includes installation, alteratio...
5           n.a.  Transactions are possible, but data are not av...}
Notes corresponding to NoteRef:
NoteRef NoteText
0 (D) Suppressed to avoid the disclosure of data of ...
1 IntlServ2.3:1 Courier services are included in "Air transpor...
2 IntlServ2.3:2 Insurance services transactions are considered...
3 IntlServ2.3:3 Outcomes of research and development include p...
4 IntlServ2.3:4 This category includes installation, alteratio...
5 n.a. Transactions are possible, but data are not av...
[50]:
#InputOutput
spec = {"Year":"2010,2011,2012,2013","tableID":"56"} # Note: due to api error, only as for one table at a time
bea_tbl = beaapi.get_data(beakey, 'InputOutput', **spec)

# check out attrs
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
print("Notes corresponding to NoteRef:")
display(bea_tbl.attrs['detail']['Notes'])
dict_keys(['params', 'response_size', 'detail', 'time_invariant_keys', 'time_invariant_vars', 'time_variant_keys', 'time_variant_vars', 'time_variant_only_vars', 'index_cols'])
Extra detail keys:dict_keys(['Statistic', 'UTCProductionTime', 'Dimensions', 'Notes'])
{'Statistic': 'Input-Output Table', 'UTCProductionTime': '2022-10-18T20:11:55.573', 'Dimensions':    Ordinal       Name DataType  IsValue
0        1    TableID  numeric        0
1        2       Year   string        0
2        3    RowCode   string        0
3        4   RowDescr   string        0
4        5    RowType   string        0
5        6    ColCode   string        0
6        7   ColDescr   string        0
7        8    ColType   string        0
8        9  DataValue  numeric        1, 'Notes':                                             NoteText NoteRef
0  Note. Detail may not add to total due to round...    <NA>
1  Industry-by-Commodity Total Requirements, Afte...    6003}
Notes corresponding to NoteRef:
NoteText NoteRef
0 Note. Detail may not add to total due to round... <NA>
1 Industry-by-Commodity Total Requirements, Afte... 6003
[ ]:
#IIP
spec = {"TypeOfInvestment":"FinAssetsExclFinDeriv","Component":"ALL","Frequency":"ALL","Year":"ALL"}
bea_tbl = beaapi.get_data(beakey, 'IIP', **spec)

# check out attrs
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
#print("Notes corresponding to NoteRef:")
#display(bea_tbl.attrs['detail']['Notes'])
[48]:
#ITA
spec = {'Indicator':"BalGds","AreaOrCountry":"China,Brazil","Frequency":"A,QSA,QNSA", "Year":"2011,2012"}
bea_tbl = beaapi.get_data(beakey, 'ITA', **spec)

# check out attrs
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
print("Notes corresponding to NoteRef:")
display(bea_tbl.attrs['detail']['Notes'])
dict_keys(['params', 'response_size', 'detail', 'time_invariant_keys', 'time_invariant_vars', 'time_variant_keys', 'time_variant_vars', 'time_variant_only_vars', 'index_cols'])
Extra detail keys:dict_keys(['TsLastUpdated', 'Dimensions', 'Notes'])
{'TsLastUpdated': '2022-09-22 08:30:00.000', 'Dimensions':    Ordinal                   Name DataType  IsValue
0        1              Indicator   string        0
1        2          AreaOrCountry   string        0
2        3              Frequency   string        0
3        4                   Year   string        0
4        5           TimeSeriesId   string        0
5        6  TimeSeriesDescription   string        0
6        7             TimePeriod   string        0
7        8                CL_UNIT   string        0
8        9              UNIT_MULT   string        0
9       10              DataValue  numeric        1, 'Notes':   NoteRef                                           NoteText
0       Q  Quarterly estimates are not annualized and are...}
Notes corresponding to NoteRef:
NoteRef NoteText
0 Q Quarterly estimates are not annualized and are...
[47]:
#MNE
print("DI")
spec = {'Country':'650,699', 'SeriesId':'27,30', 'DirectionOfInvestment':'Outward',
        'Year':'2012,2011', 'Classification':'Country', 'GetFootnotes':'Yes'}
#bea_tbl = beaapi.get_data(beakey, 'MNE', **spec)

# check out attrs
print(bea_tbl.attrs.keys())
print('Extra detail keys:' + str(bea_tbl.attrs['detail'].keys()))
print(bea_tbl.attrs['detail'])
print("Notes corresponding to NoteRef:")
display(bea_tbl.attrs['detail']['Notes'])

#print("AMNE")
#spec = {"Year":"2012,2011","Country":"202","Industry":"all","DirectionOfInvestment":"Outward",
#        "Classification":"CountryByIndustry","SeriesId":"5,4","NonBankAffiliatesOnly":"0","OwnershipLevel":"0", 'GetFootnotes':'Yes'}


DI
dict_keys(['params', 'response_size', 'detail', 'time_invariant_keys', 'time_invariant_vars', 'time_variant_keys', 'time_variant_vars', 'time_variant_only_vars', 'index_cols'])
Extra detail keys:dict_keys(['Table_Count', 'rowTypeID', 'InvestmentType', 'DataType', 'Entity', 'IndustryClassification', 'YearList', 'DIRECTIONOFINVESTMENT', 'OwnershipLevel', 'NonbankAffiliatesOnly', 'Tables', 'cnt', 'Dimensions', 'Notes'])
{'Table_Count': '2', 'rowTypeID': '10', 'InvestmentType': 'U.S. Direct Investment Abroad', 'DataType': 'Balance of Payments and Direct Investment Position Data', 'Entity': 'None', 'IndustryClassification': 'NAICS', 'YearList': '2012,2011', 'DIRECTIONOFINVESTMENT': 'OUTWARD', 'OwnershipLevel': '2', 'NonbankAffiliatesOnly': '2', 'Tables': '210,211', 'cnt': '8', 'Dimensions':    Ordinal                  Name DataType  IsValue
0        1                  Year  numeric        0
1        2              SeriesID  numeric        0
2        3            SeriesName   string        0
3        4                   Row   string        0
4        5                Column   string        0
5        6               RowCode   string        0
6        7            ColumnCode   string        0
7        8            TableScale   string        0
8        9  DataValueUnformatted   string        1
9       10             DataValue   string        1, 'Notes':                                              NoteText   NoteRef
0   <strong>n.s.</strong>  Not shown.  Data may no...      2.00
1    ? The data appear on another line in this table.      4.00
2   ? The data are not shown in this table but may...      6.00
3   ? The data are not available, do not apply, or...      8.00
4   <strong>(*)</strong> A nonzero value that roun...     10.00
5   <strong>(D)</strong> indicates that the data i...     12.00
6   Balance of payments transactions (and associat...     34.00
7   The composition of the "Other" categories show...     36.00
8           Source: U.S. Bureau of Economic Analysis      41.00
9   1.&#x09;In 2021, the euro area includes Austri...    112.01
10  1. The "United Kingdom Islands, Caribbean" is ...    113.00
11  2. Data for the European Union (EU) reflect th...    114.00
12  3. OPEC (Organization of Petroleum Exporting C...    115.00
13  1.&#x09;In 2021, the euro area includes Austri...    221.00
14  2. The ?United Kingdom Islands, Caribbean? inc...    222.00
15  3. Prior to 2011, data were included in the Ne...    223.00
16  4. Prior to 2011, included data for Curacao, S...    224.00
17   5. Prior to 2011, included data for South Sudan.    225.00
18  2. OPEC (Organization of Petroleum Exporting C...    226.00
19  If you have a question about the availability ...  10000.00}
Let's look at some interesting ones.
Notes corresponding to NoteRef:
NoteText NoteRef
0 <strong>n.s.</strong> Not shown. Data may no... 2.00
1 ? The data appear on another line in this table. 4.00
2 ? The data are not shown in this table but may... 6.00
3 ? The data are not available, do not apply, or... 8.00
4 <strong>(*)</strong> A nonzero value that roun... 10.00
5 <strong>(D)</strong> indicates that the data i... 12.00
6 Balance of payments transactions (and associat... 34.00
7 The composition of the "Other" categories show... 36.00
8 Source: U.S. Bureau of Economic Analysis 41.00
9 1.&#x09;In 2021, the euro area includes Austri... 112.01
10 1. The "United Kingdom Islands, Caribbean" is ... 113.00
11 2. Data for the European Union (EU) reflect th... 114.00
12 3. OPEC (Organization of Petroleum Exporting C... 115.00
13 1.&#x09;In 2021, the euro area includes Austri... 221.00
14 2. The ?United Kingdom Islands, Caribbean? inc... 222.00
15 3. Prior to 2011, data were included in the Ne... 223.00
16 4. Prior to 2011, included data for Curacao, S... 224.00
17 5. Prior to 2011, included data for South Sudan. 225.00
18 2. OPEC (Organization of Petroleum Exporting C... 226.00
19 If you have a question about the availability ... 10000.00