Introduction
In 2026, the American EV market is experiencing a significant shift due to trade policies and tariffs. This tutorial will teach you how to analyze EV model data using Python to understand the impact of tariffs on vehicle availability. You'll learn to scrape, clean, and visualize EV data to identify which models are being affected by import restrictions.
Prerequisites
- Basic Python knowledge
- Installed Python libraries: requests, pandas, matplotlib, seaborn
- Understanding of data analysis concepts
Step-by-Step Instructions
1. Setting Up Your Environment
1.1 Install Required Libraries
First, ensure you have the necessary Python libraries installed:
pip install requests pandas matplotlib seaborn
This step prepares your environment for data collection and analysis.
1.2 Create Project Structure
Create a new directory for this project and set up the following files:
ev_data_analysis.py- Main analysis scriptdata/- Directory for storing downloaded data
2. Data Collection
2.1 Define Data Sources
We'll use public databases and APIs to gather EV model information:
import requests
import pandas as pd
def fetch_ev_data():
# Example API endpoint (replace with actual source)
url = "https://api.example-ev-database.com/models"
headers = {'Authorization': 'Bearer YOUR_API_KEY'}
response = requests.get(url, headers=headers)
return response.json()
# Fetch data
try:
data = fetch_ev_data()
df = pd.DataFrame(data)
print("Data successfully fetched")
except Exception as e:
print(f"Error fetching data: {e}")
This code demonstrates how to retrieve EV model data from an API, which is essential for analyzing tariff impacts.
2.2 Collect Tariff Information
Download tariff data from government sources:
import requests
def download_tariff_data():
# Example URL for tariff data
url = "https://www.trade.gov/tariff-data-2026.csv"
response = requests.get(url)
with open('data/tariff_data.csv', 'wb') as file:
file.write(response.content)
print("Tariff data downloaded")
download_tariff_data()
Collecting tariff data allows us to correlate it with EV model availability.
3. Data Processing
3.1 Load and Clean EV Data
Process the collected EV data to identify discontinued models:
def clean_ev_data(df):
# Remove duplicates
df = df.drop_duplicates()
# Handle missing values
df = df.fillna({'status': 'active', 'discontinued_date': 'N/A'})
# Convert date columns
df['discontinued_date'] = pd.to_datetime(df['discontinued_date'], errors='coerce')
# Filter for 2026 data
df_2026 = df[df['discontinued_date'].dt.year == 2026]
return df_2026
# Load data
ev_df = pd.read_csv('data/ev_models.csv')
ev_clean = clean_ev_data(ev_df)
print(ev_clean.head())
This cleaning process ensures data accuracy for analysis.
3.2 Merge Data Sets
Combine EV data with tariff information:
def merge_ev_with_tariffs(ev_df, tariff_df):
# Merge on manufacturer or model name
merged_df = pd.merge(ev_df, tariff_df, left_on='manufacturer', right_on='tariffed_manufacturer', how='left')
# Identify models affected by tariffs
affected_models = merged_df[merged_df['tariff_rate'] > 0]
return affected_models
# Merge datasets
merged_data = merge_ev_with_tariffs(ev_clean, tariff_df)
print(merged_data[['model', 'manufacturer', 'tariff_rate']])
Merging datasets allows you to identify which EV models are directly impacted by tariffs.
4. Analysis and Visualization
4.1 Create Impact Analysis
Build a dashboard showing tariff impacts:
import matplotlib.pyplot as plt
import seaborn as sns
# Set style
sns.set_style("whitegrid")
# Create bar chart of affected models
plt.figure(figsize=(12, 6))
bar_plot = sns.barplot(data=merged_data, x='manufacturer', y='tariff_rate')
plt.title('Tariff Rates by EV Manufacturer (2026)')
plt.xlabel('Manufacturer')
plt.ylabel('Tariff Rate (%)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('tariff_impact.png')
plt.show()
This visualization helps identify which manufacturers face the highest tariff impacts.
4.2 Generate Summary Report
Create a summary of affected models:
def generate_summary_report(merged_df):
# Count models by manufacturer
manufacturer_count = merged_df.groupby('manufacturer').size().sort_values(ascending=False)
# Calculate average tariff rate
avg_tariff = merged_df['tariff_rate'].mean()
# Identify top affected models
top_affected = merged_df.nlargest(5, 'tariff_rate')
report = {
'total_affected_models': len(merged_df),
'average_tariff_rate': avg_tariff,
'top_manufacturers': manufacturer_count,
'top_affected_models': top_affected
}
return report
# Generate report
summary = generate_summary_report(merged_data)
print("Summary Report:")
print(f"Total affected models: {summary['total_affected_models']}")
print(f"Average tariff rate: {summary['average_tariff_rate']:.2f}%")
The summary report provides key insights into tariff impacts on the EV market.
5. Interpretation and Action
5.1 Analyze Results
Interpret your findings:
- Models with high tariff rates are likely to be discontinued
- Manufacturers with multiple affected models face greater challenges
- Geographic regions with high tariffs may see reduced EV availability
This analysis helps predict which EV models will be most affected by 2026 trade policies.
5.2 Create Predictive Model
Build a simple predictive model to forecast future impacts:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# Prepare data for prediction
X = merged_data[['tariff_rate', 'base_price']]
Y = merged_data['sales_volume']
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# Train model
model = LinearRegression()
model.fit(X_train, y_train)
# Predict
predictions = model.predict(X_test)
print(f"Model R-squared: {model.score(X_test, y_test):.3f}")
This predictive model helps forecast how tariff impacts might affect sales volumes.
Summary
In this tutorial, you've learned to analyze EV model data to understand the impact of tariffs on the American EV market. You've collected data from multiple sources, cleaned and merged datasets, created visualizations, and built a predictive model. This approach helps identify which EV models are being "tariffed out of existence" and can inform business decisions or policy analysis. The skills you've learned can be adapted to analyze other trade impacts on consumer products.



