Technical writing

USDA ERS: The Federal Database Behind US Food, Farm, and Rural Economic Data

· AI Analytics
USDAERSAgricultureFood EconomicsFederal Data

The USDA Economic Research Service publishes the definitive federal economic statistics on US food systems, farm income, commodity markets, rural development, trade, and food security—primary data for farm policy, food price inflation analysis, and agricultural trade research.

What ERS is and how it fits inside USDA

The Economic Research Service is a principal federal statistical agency within the US Department of Agriculture. With roughly 350 economists and social scientists, ERS conducts economic research and provides economic analysis for federal food, nutrition, agricultural, and rural policy. It is not a program agency: ERS administers no crop insurance, issues no farm loans, and runs no subsidy programs. Its entire output is data, analysis, and research reports—including the long-running Amber Waves magazine and an extensive library of Economic Information Bulletins, Economic Research Reports, and Economic Brief publications.

Understanding ERS requires distinguishing it from two other USDA agencies that analysts frequently conflate with it. USDA NASS—the National Agricultural Statistics Service—conducts the surveys and the Census of Agriculture. NASS measures physical quantities: planted acres, yield per acre, head of livestock, average farm prices received at the farm gate. NASS produces the numbers. ERS takes those numbers and builds economic accounts from them: what did the farm sector earn, what did it cost to produce a bushel of corn, how much of household food expenditure went to restaurant meals. USDA FSA—the Farm Service Agency—administers the commodity programs that ERS analyzes: it runs the ARC and PLC payment calculations, operates the marketing loan program, and delivers disaster assistance. FSA has the program; ERS has the data on what the program costs and who it reaches.

All ERS data and publications are free at ers.usda.gov, without registration. ERS does not operate a unified REST API comparable to the NASS QuickStats interface or the BLS API. Most major series are available as Excel or CSV downloads at stable URLs that support scripted access. Key ERS series are also mirrored on the Federal Reserve Bank of St. Louis FRED database, which provides a standardized API for time-series access.

Major ERS data products

ERS organizes its statistical output into approximately two dozen named data products, each covering a specific domain. The most widely used are the following.

Farm income and wealth statistics

The flagship ERS data product is the Farm Income and Wealth Statistics, produced through the Farm Income and Wealth Data System (FADS). This is the national income accounting framework for the US farm sector—the agricultural equivalent of BEA's GDP accounts. FADS publishes annual and quarterly estimates of farm sector revenues, expenses, and net income at both the national and state level, available as Excel and CSV downloads.

The headline figure is farm sector net farm income (NFI): total receipts minus total production expenses including capital consumption allowances. ERS forecast 2024 net farm income at approximately $155 billion—the second highest on record after the 2022 record of $182 billion, which was driven by the commodity price surge following Russia's invasion of Ukraine and the resulting wheat, sunflower oil, and fertilizer supply disruptions. For comparison, NFI averaged roughly $60–80 billion through most of the 2010s.

FADS also tracks farm production expenses (seed, fertilizer, pesticides, fuel, purchased machinery services, hired labor, rent), government payments by program type (commodity program payments, crop insurance indemnities, conservation payments, and ad hoc disaster and trade assistance payments), and the farm sector balance sheet: total assets (land, buildings, equipment, livestock, crops in storage), total debt, and the resulting debt-to-asset ratio. Land values—by far the largest component of farm sector assets—are tracked separately and have approximately tripled in nominal terms since 2000, with significant regional variation.

Food expenditure series

The Food Expenditure Series covers total US food spending from 1997 to the present, split between food at home (grocery retail) and food away from home (FAFH: restaurants, fast food, institutional food service). FAFH now accounts for approximately 57 percent of total US food expenditure—a structural shift that has grown steadily for six decades as Americans have shifted from home cooking toward prepared and restaurant food. The series is available by income quintile, enabling analysis of how food spending patterns differ by household income level.

The food expenditure breakdown matters for inflation analysis because food-at-home and food-away-from-home prices behave differently during supply shocks. In 2022, food-at-home prices (grocery stores) rose 11.4 percent—the largest annual increase since 1979—while food-away-from-home prices rose approximately 7.7 percent, reflecting the different labor and input cost structures of retail grocery versus food service. The BLS Consumer Price Index food components that ERS uses in its Food Price Outlook are the primary data source for this comparison.

Food price outlook

ERS publishes monthly Food Price Outlook forecasts for the current and following calendar year. The forecasts cover food CPI as a whole and by major category: beef and veal, pork, poultry, fish and seafood, eggs, dairy, fats and oils, fruits and vegetables, cereals and bakery products, nonalcoholic beverages, and sugar and sweets. Each monthly update revises forecasts based on the most recent BLS CPI data, USDA commodity supply and demand estimates, and ERS analysis of input costs and retail pricing dynamics.

Food security in the United States

ERS produces the official federal measure of household food security through the annual Household Food Security Survey, conducted jointly with the Census Bureau as a supplement to the Current Population Survey each December, reaching approximately 50,000 households. The survey uses USDA's validated 18-item food security scale, classifying households into four categories on the basis of affirmative responses to questions about food access, adequacy, and quality:

CategoryDefinition2023 prevalence
High food securityNo reported food access problems or limitations~72%
Marginal food securityOne or two reported problems; little or no reduction in food intake~14.5%
Low food securityReduced quality or variety; little or no reduction in intake quantity~8.5%
Very low food securityDisrupted eating patterns and reduced intake due to inadequate resources~5%

ERS estimated 13.5 percent of US households—approximately 17.9 million households—were food insecure in 2023. Approximately 5.1 million of those experienced “very low food security,” the most severe category in which food intake is actually reduced and eating patterns are disrupted. State-level food security estimates are published as three-year moving averages because annual state sample sizes are too small for reliable annual point estimates. ERS also maintains the Food Access Research Atlas, a geographic mapping tool that identifies low-income census tracts where significant shares of residents live more than one mile (urban) or ten miles (rural) from a supermarket—the federal definition of a food desert.

Commodity costs and returns

The Commodity Costs and Returns data product publishes break-even price estimates for major field crops (corn, soybeans, winter wheat, spring wheat, cotton, sorghum, barley, oats, rice, sunflowers, peanuts, sugar beets) and for major livestock and dairy enterprises. Estimates are provided per acre for crops and per hundredweight for livestock, breaking down both operating costs—seed, fertilizer, pesticides, fuel, hired labor, custom operations—andownership costs including land rent or land opportunity cost, capital depreciation, and interest. The full economic cost per bushel (or per cwt) indicates whether market prices provide a return to all inputs, including land and capital.

These estimates draw heavily on the Agricultural Resource Management Survey (ARMS)—a joint ERS/NASS survey of farm financial conditions conducted annually. ARMS is the primary source for data on farm production expenses, income, debt, and assets at the individual farm level. ARMS has complex survey design (stratified, multi-phase) and the microdata requires a formal data access agreement for research use, but ERS publishes extensive tabular summaries publicly.

Rural-Urban Continuum Codes

ERS produces the Rural-Urban Continuum Codes—commonly called Beale Codes after their originator, USDA economist Calvin Beale—which classify all 3,100+ US counties on a 1–9 scale based on metropolitan status and adjacency to metro areas. Codes 1–3 are metropolitan; codes 4–9 are non-metropolitan, with higher numbers indicating more rural character and greater distance from metro labor markets:

CodeDescription
1Metro: counties in areas of 1 million population or more
2Metro: counties in areas of 250,000–999,999 population
3Metro: counties in areas of fewer than 250,000 population
4Non-metro: urban pop 20,000+, adjacent to a metro area
5Non-metro: urban pop 20,000+, not adjacent to a metro area
6Non-metro: urban pop 2,500–19,999, adjacent to metro
7Non-metro: urban pop 2,500–19,999, not adjacent to metro
8Non-metro: completely rural or urban pop under 2,500, adjacent to metro
9Non-metro: completely rural or urban pop under 2,500, not adjacent to metro

Beale Codes are updated after each decennial Census. They are used across federal agencies to define program eligibility, administer USDA rural development grants and loans, define rural healthcare shortage areas for HHS, and control for urbanization in social science research. ERS also publishes Rural-Urban Commuting Area (RUCA) codes at the census tract level, providing sub-county rural-urban classification used by programs that define eligibility below the county level.

Farm Bill context and commodity program analysis

The Farm Bill—a major omnibus agricultural law reauthorized approximately every five years—covers commodity programs (Title I), crop insurance (Title XI), nutrition programs including SNAP (Title IV), and conservation programs including the Conservation Reserve Program (CRP), Environmental Quality Incentives Program (EQIP), and Conservation Stewardship Program (CSP). ERS analyzes the economic effects and expected costs of Farm Bill program design alternatives, making it a central technical resource during reauthorization debates.

The two primary commodity support mechanisms under the 2018 Farm Bill are:

ProgramPayment triggerReference prices (selected)
Agriculture Risk Coverage (ARC)County revenue falls more than 14% below 5-year Olympic benchmarkVaries by county; uses actual price and yield data
Price Loss Coverage (PLC)Market price falls below statutory reference priceCorn $3.70/bu · soybeans $8.40/bu · wheat $5.50/bu

ERS tracks whether prevailing market prices are above or below PLC reference prices and projects expected payment volumes under different price scenarios. The 2022 NFI record of $182 billion was driven by commodity prices well above PLC reference levels following Ukraine invasion—corn traded near $7/bu against a $3.70 reference, and soybeans near $14/bu against an $8.40 reference—meaning ARC and PLC generated near-zero payments in 2022 and 2023 because commodity prices far exceeded support levels. ERS also tracks marketing loan rates and loan deficiency payments (LDPs) for the marketing loan program, which provides a price floor when market prices fall below loan rates.

ERS datasets and data access

ERS data products are organized at ers.usda.gov/data-products/. Each product page links directly to Excel and CSV downloads. The most frequently accessed datasets for analytical work:

DatasetCoverage and notes
Farm Income and Wealth StatisticsNet farm income, expenses, government payments, balance sheet; national and state; Excel/CSV
Food Price OutlookCPI food forecasts by category (beef, pork, eggs, dairy, produce); updated monthly
Food Expenditure SeriesTotal food spending 1997–present; food at home vs. away; by income quintile
Food Security in the USAnnual household food security prevalence; 4-category USDA scale; state 3-year averages
Commodity Costs and ReturnsBreak-even prices per acre and per bushel for major field crops; operating and ownership costs
ARMS Farm Financial DataJoint ERS/NASS survey; farm income, expenses, debt, assets; tabular summaries public
Rural-Urban Continuum CodesBeale Codes 1–9 for all US counties; updated decennially; CSV download
Agricultural Trade (via USDA FAS)US ag export and import values by commodity and destination; Global Agricultural Trade System (GATS)

For production and price survey data, NASS QuickStats at quickstats.nass.usda.gov/api/ provides a REST API requiring a free API key. QuickStats covers crop production, acreage, yields, and farm-level prices received. The Census of Agriculture—conducted every five years (2017, 2022)—is accessible through QuickStats and provides farm counts, total acreage, and sales by county. For agricultural trade data, the USDA Foreign Agricultural Service runs the Global Agricultural Trade System (GATS) at apps.fas.usda.gov/gats/. ERS food CPI series and net farm income are mirrored on FRED under standard series identifiers including CUSR0000SAF1 (food CPI), CUSR0000SAF11 (food at home), and CUSR0000SEFV (food away from home).

Python: food price inflation analysis via FRED (2019–2024)

The script below uses the FRED API to fetch USDA ERS food price CPI series and compute five analyses: (a) food inflation versus overall CPI comparison 2019–2024, rebased to January 2019 to show cumulative price level change; (b) food-at-home versus food-away-from-home inflation divergence, illustrating how grocery and restaurant prices moved at different rates during the 2022 supply shock; (c) the egg price index spike driven by the 2022–2023 Highly Pathogenic Avian Influenza (HPAI) outbreak, which caused record flock depopulations and sent retail egg prices to historic highs; (d) 12-month rolling year-over-year food inflation by major category to show how inflation decelerated through 2023 and 2024; and (e) a real versus nominal food price comparison deflating the food CPI by the overall CPI to show whether food has become relatively cheaper or more expensive over time.

import requests
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from datetime import datetime

# ---------------------------------------------------------------------------
# USDA ERS food price inflation analysis via FRED API
# Uses BLS/ERS food CPI series mirrored on FRED -- no ERS API key required.
# Register for a free FRED API key at: https://fred.stlouisfed.org/docs/api/api_key.html
# ---------------------------------------------------------------------------

FRED_BASE = "https://api.stlouisfed.org/fred/series/observations"
FRED_API_KEY = "YOUR_FRED_API_KEY"

# Series used in this analysis:
#   CPIAUCSL        -- All Items CPI (overall inflation baseline)
#   CUSR0000SAF1    -- Food CPI (BLS, all urban consumers)
#   CUSR0000SAF11   -- Food at Home CPI (grocery stores)
#   CUSR0000SEFV    -- Food Away from Home CPI (restaurants, fast food)
#   CUSR0000SS61031 -- Eggs CPI (captures avian flu price spike 2022-2023)

SERIES = {
    "overall_cpi":    "CPIAUCSL",
    "food_cpi":       "CUSR0000SAF1",
    "food_at_home":   "CUSR0000SAF11",
    "food_away":      "CUSR0000SEFV",
    "eggs_cpi":       "CUSR0000SS61031",
}

def fetch_fred(series_id, start="2019-01-01", end="2024-12-31"):
    """
    Fetch monthly observations for a FRED series.
    Returns a pandas Series indexed by date.
    """
    params = {
        "series_id":        series_id,
        "api_key":          FRED_API_KEY,
        "file_type":        "json",
        "observation_start": start,
        "observation_end":   end,
        "frequency":        "m",
    }
    r = requests.get(FRED_BASE, params=params, timeout=30)
    r.raise_for_status()
    obs = r.json().get("observations", [])
    records = []
    for o in obs:
        if o["value"] == ".":
            continue  # FRED uses "." for missing values
        records.append({"date": pd.to_datetime(o["date"]), "value": float(o["value"])})
    df = pd.DataFrame(records).set_index("date")["value"]
    return df.rename(series_id)

# Fetch all series
print("Fetching FRED series...")
raw = {name: fetch_fred(sid) for name, sid in SERIES.items()}
df = pd.DataFrame(raw).dropna()

# ---------------------------------------------------------------------------
# (a) Food inflation vs. overall CPI comparison 2019-2024
# Rebase each series to January 2019 = 100 to show cumulative inflation
# ---------------------------------------------------------------------------
base = df.loc["2019-01-01"]
rebased = df.divide(base) * 100

print("\n--- (a) Cumulative price level change, Jan 2019 = 100 ---")
print(rebased[["overall_cpi", "food_cpi"]].tail(12).round(1).to_string())

fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(rebased.index, rebased["overall_cpi"], label="All Items CPI", linewidth=1.8, color="#555555")
ax.plot(rebased.index, rebased["food_cpi"], label="Food CPI", linewidth=1.8, color="#2c6e49")
ax.axhline(100, color="black", linewidth=0.7, linestyle="--")
ax.set_title("US Food Inflation vs. Overall CPI (Jan 2019 = 100)", fontsize=13)
ax.set_ylabel("Index (Jan 2019 = 100)")
ax.legend()
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
fig.savefig("food_vs_overall_cpi.png", dpi=150)
print("Saved food_vs_overall_cpi.png")

# ---------------------------------------------------------------------------
# (b) Food-at-home vs. food-away-from-home inflation divergence
# FAFH (restaurants) and FAH (groceries) often diverge during supply shocks
# ---------------------------------------------------------------------------
print("\n--- (b) Food-at-home vs. food-away-from-home (rebased Jan 2019 = 100) ---")
print(rebased[["food_at_home", "food_away"]].tail(12).round(1).to_string())

fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(rebased.index, rebased["food_at_home"], label="Food at Home (groceries)", linewidth=1.8, color="#e76f51")
ax.plot(rebased.index, rebased["food_away"], label="Food Away from Home (restaurants)", linewidth=1.8, color="#264653")
ax.axhline(100, color="black", linewidth=0.7, linestyle="--")
ax.set_title("Food at Home vs. Food Away From Home: Cumulative Price Change (Jan 2019 = 100)", fontsize=12)
ax.set_ylabel("Index (Jan 2019 = 100)")
ax.legend()
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
fig.savefig("fah_vs_fafh_cpi.png", dpi=150)
print("Saved fah_vs_fafh_cpi.png")

# ---------------------------------------------------------------------------
# (c) Egg price index spike 2022-2023 (driven by HPAI avian influenza)
# HPAI = Highly Pathogenic Avian Influenza; caused record flock depopulations
# ---------------------------------------------------------------------------
eggs_rebased = rebased["eggs_cpi"]
eggs_peak = eggs_rebased.idxmax()
eggs_peak_val = eggs_rebased.max()

print(f"\n--- (c) Egg CPI spike (avian flu) ---")
print(f"Peak egg CPI index: {eggs_peak_val:.1f} (Jan 2019 = 100) on {eggs_peak.strftime(\'%Y-%m\')}")
print(f"Egg price roughly {(eggs_peak_val - 100):.0f}% above January 2019 levels at peak")

fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(rebased.index, rebased["eggs_cpi"], label="Eggs CPI", linewidth=1.8, color="#e9c46a")
ax.axvline(pd.Timestamp("2022-01-01"), color="#c0392b", linewidth=0.8, linestyle=":", label="HPAI detection wave 1 (Jan 2022)")
ax.axhline(100, color="black", linewidth=0.7, linestyle="--")
ax.set_title("Egg Price Index: Avian Flu Impact 2022-2023 (Jan 2019 = 100)", fontsize=13)
ax.set_ylabel("Index (Jan 2019 = 100)")
ax.legend()
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
fig.savefig("egg_cpi_spike.png", dpi=150)
print("Saved egg_cpi_spike.png")

# ---------------------------------------------------------------------------
# (d) 12-month rolling food inflation by major category
# Year-over-year percentage change using the food CPI series
# ---------------------------------------------------------------------------
food_yoy = df["food_cpi"].pct_change(12) * 100
fah_yoy  = df["food_at_home"].pct_change(12) * 100
fafh_yoy = df["food_away"].pct_change(12) * 100

print("\n--- (d) 12-month rolling food inflation (year-over-year %) ---")
combined_yoy = pd.DataFrame({
    "food_cpi_yoy":    food_yoy,
    "fah_yoy":         fah_yoy,
    "fafh_yoy":        fafh_yoy,
}).dropna()
print(combined_yoy.tail(18).round(2).to_string())

fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(combined_yoy.index, combined_yoy["food_cpi_yoy"],  label="Food CPI (all)", linewidth=1.8, color="#2c6e49")
ax.plot(combined_yoy.index, combined_yoy["fah_yoy"],       label="Food at Home",    linewidth=1.5, color="#e76f51", linestyle="--")
ax.plot(combined_yoy.index, combined_yoy["fafh_yoy"],      label="Food Away",       linewidth=1.5, color="#264653", linestyle="--")
ax.axhline(0, color="black", linewidth=0.8)
ax.set_title("12-Month Rolling Food Inflation by Category (Year-over-Year %)", fontsize=13)
ax.set_ylabel("Year-over-Year % Change")
ax.legend()
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
fig.savefig("food_yoy_inflation.png", dpi=150)
print("Saved food_yoy_inflation.png")

# ---------------------------------------------------------------------------
# (e) Real vs. nominal food spending trend
# ERS Food Expenditure Series: total food spending and real (deflated) trend
# Nominal spending from BEA PCE food series via FRED (DFXARC1A027NBEA / DFDAPC1A027NBEA)
# Here we approximate using the food CPI to deflate a placeholder nominal series.
# For the full ERS Food Expenditure Series, download directly from:
#   https://www.ers.usda.gov/data-products/food-expenditure-series/
# ---------------------------------------------------------------------------

# Compute a real food price index: nominal food CPI deflated by overall CPI
# A value below 100 means food has gotten cheaper relative to overall prices;
# above 100 means food has gotten relatively more expensive.
real_food_price = (df["food_cpi"] / df["overall_cpi"]) * 100
real_food_rebased = real_food_price / real_food_price.iloc[0] * 100

print("\n--- (e) Real food price index (food CPI / overall CPI, Jan 2019 = 100) ---")
print(real_food_rebased.tail(12).round(2).to_string())

fig, ax = plt.subplots(figsize=(12, 5))
ax.plot(df.index, rebased["food_cpi"],   label="Nominal food CPI",           linewidth=1.8, color="#e76f51")
ax.plot(df.index, real_food_rebased,     label="Real food price (vs. CPI)",  linewidth=1.8, color="#2c6e49")
ax.axhline(100, color="black", linewidth=0.7, linestyle="--")
ax.set_title("Real vs. Nominal Food Prices (Jan 2019 = 100)", fontsize=13)
ax.set_ylabel("Index (Jan 2019 = 100)")
ax.legend()
ax.grid(axis="y", alpha=0.3)
fig.tight_layout()
fig.savefig("real_vs_nominal_food.png", dpi=150)
print("Saved real_vs_nominal_food.png")

print("\nAll five analyses complete.")

The five outputs together tell the food price story of the 2019–2024 period. Grocery prices rose sharply faster than restaurant prices in 2022—the reverse of the usual pattern, where food-away-from-home inflation typically leads food-at-home inflation because labor costs are a larger share of restaurant operating costs. The inversion in 2022 reflected commodity and supply chain shocks hitting grocery shelves faster than restaurant menu prices, which adjust more slowly. The egg series is the most extreme single-category case: the 2022 HPAI outbreak killed approximately 58 million birds in the United States, roughly one in seven commercial egg-laying hens, causing a supply collapse that drove retail egg prices to more than double their pre-pandemic levels at peak. The real versus nominal comparison in panel (e) shows whether these nominal price increases represented genuine relative price shifts or were largely swept along by overall inflation—a distinction that matters for understanding long-run consumer food burden.

For the full ERS Food Expenditure Series—including historical spending by income quintile—download directly from ers.usda.gov/data-products/food-expenditure-series/. For the Farm Income and Wealth Statistics including state-level breakdowns, the download URL is at ers.usda.gov/data-products/farm-income-and-wealth-statistics/. Both sets of files are structured as multi-sheet Excel workbooks with header rows and footer notes; pandas' read_excel() with skiprows and manual column selection handles the format reliably.


Related: USDA NASS crop production surveys · USDA SNAP program data

Part of the Federal Regulatory Data Hub.