income_by_zip_code.png

Unlocking Local Insights: Income by Zip Code

Introduction

When you’re crafting a marketing strategy, opening a new retail location, or pitching real-estate investments, “average household income” is more than a vanity metric—it’s a compass. Granular, up-to-date income data at the ZIP-code level lets you:

  • Target with precision – Tailor offers or ad spend to pockets of higher disposable income instead of blanketing an entire DMA.
  • Prioritize expansion – Rank candidate neighborhoods for your next storefront or service area by purchasing power.
  • Refine look-alike models – Feed income tiers into audience-building tools to spot similar high-value zones nationwide.
  • Benchmark performance – Compare current store revenue against local earning capacity to find outliers—good or bad.
  • Strengthen investor decks – Back up “prime location” claims with IRS-sourced tax-return evidence, not anecdotal observations.

A Quick Demo: Finding High-Income Neighbors with Python

Below is the workflow of a simple Python script you could share with analysts or data-savvy clients. It takes three inputs and returns a shortlist of nearby ZIP codes whose **average income** beats a user-defined threshold.

Step What Happens Why it matters
1. Prompt for inputs zip_code (any zip code), radius_miles (input the surrounding radius zip code list), income_threshold (in 000's).  Keeps the tool flexible for any geography or campaign.
2. Build a Radius Query Using the Zip Code radius endpoint, get all of the zip codes that fall within the prompted radius.  Marketers often care about “drivable distance” rather than arbitrary county lines.
3. Fetch IRS Statistics of Income by Zip Code and calculate average income Grab `Total Gross Income` and `Number of Returns` for each candidate ZIP.  
avg_income = total_gross_income / returns
While the sample code uses only 2 fields (e.g. Adjusted Gross Income and Number of Returns), it is designed as a starting point to show how demographic data can be used in marketing use cases. The same API includes dozens of other statistical fields which marketers can easily incorporate to refine their targeting strategies.
4.  Print & Sort Results Flag rows where `avg_income > income_threshold`; optionally sort descending. Instantly surfaces the high-value zones worth further attention.

Let's review the code needed for each step

1. Prompt for Inputs

When you run the python script it will ask for 3 parameters. 1. The zip code. Second a radius in Miles. and Third the income threshold in thousands. (i.e. to represent 100,000 you type 100.) The python code used to ask for input is:

zip_code = input("Enter your ZIP code: ")
radius = input("Enter a radius in miles: ")
input_threshold = input("Enter Thresholds in 000's: ")

2. Build a radius query

To accomplish this, we have a function that takes as parameters the zip code value and the radius. Then we leverage the Zip Code Radius endpoint to get a list of zip codes that fall within the provided radius. The function will return an array with all the zip codes that are within the provided radius. The Python code of the function: 

def get_zips_in_radius(zipcode, radius):
    # Define the API endpoint
    url = f"https://global.metadapi.com/zipc/v1/radius?radius={radius}&uom=mi&zipcode={zipcode}"
    zips = []
    try:
        # Make the API request
        response = requests.get(url,headers=vheaders)
        response.raise_for_status()  # Raise an error for unsuccessful responses
        # Parse the JSON response
        data = response.json()
        for zipresp in data["data"]:
            zips.append(zipresp["zipCode"])
    except requests.exceptions.RequestException as e:
        print('error returning the json')
        print(f"An error occurred: {e}")
        return None
    return zips

3. Fetch IRS Statistics of income by zip code and calculate average income

To accomplish this, we must take each of the zip codes provided by the previous function and get the income statistics for the year of 2021 (this parameter can be changed, and we can also query for multiple years). We leverage the Zip Code IRS Statistics of Income endpoint and get the Number of returns and the adjusted gross income (AGI) to calculate the average income per zip code, this allows us to smooth out population size differences—useful when comparing a dense city core with a suburban pocket.

def get_total_returns(zipcode, threshold):
    # Define the API endpoint
    url = f"https://global.metadapi.com/zipc/v1/zipcodes/{zipcode}/soi?year=2021"
    try:
        # Make the API request
        response = requests.get(url,headers=vheaders)
        response.raise_for_status()  # Raise an error for unsuccessful responses
        
        # Parse the JSON response
        data = response.json()
        total_returns = sum(item["returns"] for item in data["data"])
        total_agi = sum(item["adjustedGrossIncome"] for item in data["data"])
        if total_returns > 0 :
                avg_agi = total_agi/total_returns
                meets_threshold = "yes" if avg_agi > threshold else "no"
        else:
            avg_agi = 0
            meets_threshold = "no"
        agi_object = {"zipcode":zipcode, "totalAgi":total_agi, "totalReturns": total_returns, "avgAgi":avg_agi, "threshold" : threshold, "meets_threshold" : meets_threshold}
        time.sleep(0.5)
        return agi_object
    
    except requests.exceptions.RequestException as e:
        print('error returning the json')
        print(f"An error occurred: {e}")
        return None

4. Print and Sort results

Finally we create a data frame with the results, and we sort and print this to screen.  This will allow us to review the data and understand the zip's that meet the threshold criteria. 

	df = pd.DataFrame(analysis_dataset)
    sorted_df = df.sort_values(by="avgAgi", ascending=False)
    print(sorted_df)

You can download the full code of this script in our zip code github repository (you can review this repository for more code samples that leverage the zip code API). 

When we run the script, using the following sample: 

Sample Output

Enter base ZIP: 19103
Enter radius (miles): 15
Income threshold ($): 95

Extending the Script

Visualization – Drop results into Plotly or Folium to create a heat-map pinwheel around your base ZIP.
Additional filters* – Layer in filing status, or population density to refine prospect lists.
Batch mode – Loop through multiple anchor ZIPs to automate territory planning for regional sales teams.
Integration – Expose it as a microservice so non-technical teammates can hit an endpoint from Excel or Zapier.


Key Takeaways

Having Income by ZIP Code at your fingertips isn’t just academic—it’s actionable. Whether you’re optimizing ad bids, scouting expansion zones, or validating a property’s upside, localized income stats transform hunches into data-driven moves.

Ready to put it to work? Grab the demo script, plug in your API key for the Zip Code API , and start illuminating your income targets hiding in plain sight!


blog comments powered by Disqus

Join our Newsletter

Get the latest information about API products, tutorials and much more. Join now.

    About Our Company

    Metadapi is based in SW Florida.

    Get in touch

    Follow Us