China is earning roughly $500m an hour from exports, and AI-related goods are doing the heavy lifting
Back to Tutorials
techTutorialintermediate

China is earning roughly $500m an hour from exports, and AI-related goods are doing the heavy lifting

May 12, 202628 views5 min read

Analyze China's export data to understand the impact of AI-related goods on export earnings, using Python to calculate growth rates and visualize trends.

Introduction

In this tutorial, you'll learn how to analyze export data using Python to understand trends in China's export economy, particularly focusing on AI-related goods. This is a practical application of data analysis that demonstrates how to process, visualize, and extract insights from large datasets using real-world economic data. You'll work with pandas for data manipulation, matplotlib for visualization, and explore how to identify growth patterns in export categories.

Prerequisites

  • Basic Python knowledge (variables, loops, functions)
  • Installed Python 3.7+ environment
  • Required libraries: pandas, matplotlib, numpy
  • Access to export data (we'll use a sample dataset that mimics real export data)

Step-by-Step Instructions

1. Install Required Libraries

First, ensure you have the necessary Python libraries installed. Run the following command in your terminal or command prompt:

pip install pandas matplotlib numpy

Why this step? These libraries provide the foundation for data manipulation (pandas), mathematical operations (numpy), and visualization (matplotlib) needed for our analysis.

2. Create Sample Export Data

Let's create a sample dataset that mimics China's export data, focusing on AI-related goods:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Create sample export data
np.random.seed(42)
months = pd.date_range('2020-01-01', '2024-04-01', freq='M')

# Base export values with growth trend
base_exports = 300  # billion USD
ai_growth_rate = 0.15  # 15% annual growth for AI goods
other_growth_rate = 0.05  # 5% annual growth for other goods

# Generate data
export_data = []
for i, month in enumerate(months):
    # Base export value with some randomness
    base = base_exports * (1 + (i * 0.005))  # Slow growth over time
    
    # AI goods: higher growth rate
    ai_goods = base * 0.3 * (1 + ai_growth_rate)**(i/12)
    
    # Other goods
    other_goods = base * 0.7 * (1 + other_growth_rate)**(i/12)
    
    export_data.append({
        'date': month,
        'total_exports': base,
        'ai_goods': ai_goods,
        'other_goods': other_goods,
        'ai_percentage': (ai_goods / base) * 100
    })

# Create DataFrame
df = pd.DataFrame(export_data)
df.to_csv('china_exports_data.csv', index=False)
print(df.head())

Why this step? Creating a realistic dataset allows us to practice data analysis techniques without needing real-time data access. This approach mimics how real economic data would be structured.

3. Load and Explore the Data

Now, load the dataset and explore its structure:

# Load the data
df = pd.read_csv('china_exports_data.csv')

# Convert date column to datetime
df['date'] = pd.to_datetime(df['date'])

# Basic information about the dataset
print("Dataset Info:")
print(df.info())
print("\nFirst few rows:")
print(df.head())
print("\nDataset statistics:")
print(df.describe())

Why this step? Understanding your data structure is crucial before analysis. This step helps identify data types, missing values, and basic statistics that inform our analysis approach.

4. Analyze AI Goods Growth

Calculate and visualize the growth of AI-related exports:

# Calculate year-over-year growth for AI goods
ai_yoy_growth = []
for i in range(12, len(df)):
    current = df['ai_goods'].iloc[i]
    previous = df['ai_goods'].iloc[i-12]
    growth = ((current - previous) / previous) * 100
    ai_yoy_growth.append(growth)

# Add to DataFrame
df['ai_yoy_growth'] = [np.nan] * 12 + ai_yoy_growth

# Plot AI goods growth
plt.figure(figsize=(12, 6))
plt.plot(df['date'], df['ai_goods'], label='AI Goods Exports (USD Billion)')
plt.title('China AI Goods Exports Over Time')
plt.xlabel('Date')
plt.ylabel('Exports (USD Billion)')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

Why this step? Visualizing growth trends helps identify patterns and validate the data. The year-over-year calculation is particularly important for understanding the acceleration in AI-related exports mentioned in the news.

5. Compare AI vs Other Goods

Compare the performance of AI goods against other export categories:

# Create comparison plot
plt.figure(figsize=(14, 8))

# Plot both categories
plt.subplot(2, 1, 1)
plt.plot(df['date'], df['ai_goods'], label='AI Goods', linewidth=2)
plt.plot(df['date'], df['other_goods'], label='Other Goods', linewidth=2)
plt.title('Comparison of AI Goods vs Other Goods Exports')
plt.xlabel('Date')
plt.ylabel('Exports (USD Billion)')
plt.legend()
plt.grid(True)

# Plot percentage of AI goods
plt.subplot(2, 1, 2)
plt.plot(df['date'], df['ai_percentage'], color='orange', linewidth=2)
plt.title('Percentage of AI Goods in Total Exports')
plt.xlabel('Date')
plt.ylabel('Percentage (%)')
plt.grid(True)

plt.tight_layout()
plt.show()

Why this step? This comparison helps visualize the dominance of AI goods in China's export portfolio and demonstrates how they contribute to overall growth.

6. Calculate Key Metrics

Calculate important metrics to understand the export performance:

# Calculate key metrics
print("Key Export Metrics:")
print(f"Total Exports (April 2024): ${df['total_exports'].iloc[-1]:.2f} billion")
print(f"AI Goods (April 2024): ${df['ai_goods'].iloc[-1]:.2f} billion")
print(f"AI Goods Percentage: {df['ai_percentage'].iloc[-1]:.1f}%")

# Calculate average annual growth rates
avg_ai_growth = df['ai_yoy_growth'].mean()
avg_other_growth = df['total_exports'].pct_change(12).mean() * 100

print(f"\nAverage Year-over-Year Growth:")
print(f"AI Goods: {avg_ai_growth:.2f}%")
print(f"Total Exports: {avg_other_growth:.2f}%")

# Calculate contribution of AI goods to total growth
ai_contribution = df['ai_goods'].pct_change().mean() * 100
print(f"\nAI Goods Contribution to Total Growth: {ai_contribution:.2f}%")

Why this step? Calculating these metrics provides concrete numbers that help quantify the impact of AI goods on China's export economy, directly relating to the news article's claim about $500 million per hour.

7. Create Summary Report

Generate a summary report of your findings:

# Create summary report
print("\n=== CHINA EXPORTS ANALYSIS SUMMARY ===")
print(f"Period: {df['date'].min().strftime('%Y-%m')} to {df['date'].max().strftime('%Y-%m')}")
print(f"Total Exports (Latest): ${df['total_exports'].iloc[-1]:.2f} billion")
print(f"AI Goods Exports (Latest): ${df['ai_goods'].iloc[-1]:.2f} billion")
print(f"AI Goods Percentage of Total: {df['ai_percentage'].iloc[-1]:.1f}%")
print(f"Average AI Goods Growth Rate: {avg_ai_growth:.2f}%")
print(f"Estimated Hourly Export Earnings: ${df['total_exports'].iloc[-1] / 12 / 30 / 24:.0f} million")
print("\nThis analysis demonstrates the significant role of AI-related goods in China's export economy.")

Why this step? A summary report consolidates your findings into a clear, actionable format that communicates the insights from your data analysis.

Summary

This tutorial demonstrated how to analyze export data using Python to understand the impact of AI-related goods on China's export economy. You learned to:

  • Create and load sample export datasets
  • Calculate year-over-year growth rates
  • Visualize export trends and compare different product categories
  • Calculate key economic metrics
  • Generate summary reports

The techniques you've learned are directly applicable to real-world economic analysis and can be adapted to analyze other sectors or countries. This approach helps quantify the economic impact of technology trends, as highlighted in the news article about China's $500 million per hour export earnings.

Source: TNW Neural

Related Articles