A Python Food Price Inflation Analysis with LightningChart Python
Tutorial
Written by a Human
Explore a Python food price inflation analysis using LightningChart to visualize trends and understand the impact of rising food costs.
Introduction
Inflation is one of the most critical macroeconomic indicators, influencing economic stability, purchasing power, and living standards across the globe.
This study examines the dynamics of inflation, food price indices, and energy price trends from 2000 to 2023 across selected countries, including Turkey, Iran, and Egypt. Inflation trends reveal the interplay between economic policies, global supply chains, and local market conditions, which are essential for understanding the broader economic landscape.
As noted in several studies, inflation has cascading effects on socioeconomic factors. For instance, rising food prices disproportionately impact low-income households, while energy price volatility directly affects production costs and economic output (Burke & Stephens, 2018; Stern & Burke, 2019).
By analyzing these trends, this research aims to provide actionable insights into the complex interdependencies between inflation, energy consumption, and GDP growth.
About the Dataset
The dataset used in this analysis is sourced from the World Bank and contains comprehensive data on inflation and price indices for up to 209 countries, spanning 1970 to 2023. Key indicators include:
- Food Consumer Price Index (FCPI_M): Monthly data tracking food price inflation.
- Energy Consumer Price Index (ECPI_M): Monthly data tracking energy price inflation.
- GDP Deflator Growth Rate (DEF_A): Annual data representing overall inflation.
This dataset enables cross-country and cross-sector analysis, uncovering trends and disparities in economic performance.
LightningChart Python
LightningChart Python was chosen as the primary visualization tool due to its exceptional performance in handling large datasets and creating real-time interactive visualizations. Its capabilities include:
- Seamless Data Handling: Processes millions of data points without performance degradation.
- Real-Time Updates: Facilitates dynamic visualization, making it ideal for time-series and comparative analyses.
- Customizability: Offers a wide range of chart types, enabling tailored visualizations for specific insights.
Chart Types and Analysis
- Line Charts: Energy Price Index and Food Price Index for Ukraine (2018-2023)
Purpose: Analyze the year-on-year trends for Ukraine.
- Heatmaps: Price Indices for Albania (2000-2023)
- Food Price Index:
- Energy Price Index:
- Real-Time Dashboard: Energy Price Index Growth for Continents (2000-2023)
- Bar Chart: Yearly Comparison of FCPI and ECPI for Turkey (2018-2023)
- Radar Chart: Inflation and Price Indices for Turkey (2015-2023)
- Balloon Race Chart: GDP Deflator Growth Rate and Energy Index for Turkey, Iran, and Egypt (2000-2023)
Optimizing Data Visualization Performance
In this project, the ability to efficiently visualize extensive datasets on inflation, food price indices, and energy price indices in real-time was paramount.
Given the large scope of the dataset, spanning multiple decades (1970-2023) and up to 209 countries, maintaining high performance during analysis was essential. LightningChart Python was selected for its robust capabilities in handling such complex datasets seamlessly.
Several key factors contributed to its effectiveness:
- Seamless Large Dataset Handling: LightningChart Python excels at rendering large datasets without sacrificing speed or quality. This ensures that data involving millions of points, such as country-level inflation, food, and energy price indices, is processed and visualized with precision and efficiency.
- Interactive and Real-Time Capabilities: The tool allows users to interact with visualizations dynamically, enabling real-time exploration of inflationary trends. Whether zooming into specific years, countries, or regions or updating the charts with live data, LightningChart maintains high responsiveness, making it ideal for monitoring time-sensitive economic shifts.
- Optimized Resource Utilization: Despite the dataset’s scale, which includes monthly and annual data across various indicators, LightningChart efficiently manages system resources. This optimization ensures smooth rendering of 3D balloon charts, radar charts, and dashboards, providing a lag-free and engaging user experience.
By leveraging LightningChart’s high-performance visualization capabilities, this analysis successfully uncovered intricate inflation and energy dynamics while maintaining exceptional usability and performance throughout the project.
Setting Up Python Environment
To begin working on this project, it’s necessary to install the required libraries, including Pandas and LightningChart Python. You can do this by following the steps below:
- First, you need to install Python: Download and install the latest version of Python from the official Python website.
- Second, you need to Install Pandas and LightningChart:
Use the pip package manager to install the necessary libraries by running these commands:
pip install lightningchart
pip install pandas numpy
To analyze and visualize the data, we’ll use a combination of libraries such as:
- Pandas: For data manipulation and analysis.
- NumPy: For numerical operations.
- LightningChart: A high-performance charting library for data visualization.
- Time and Random: For simulating real-time data updates and generating random values.
import pandas as pd
import lightningchart as lc
import time
import numpy as np
Visualizing Data with LightningChart Python
LightningChart offers a powerful way to visualize complex datasets in real-time. Below, we’ll create several visualizations to explore electricity access across the globe.
Energy Price Index Dashboard for Ukraine (2018-2023)
Trends Interpretation:
- 2018-2020: The energy price index shows a generally stable trend, with minor fluctuations across the months. The values stay within a narrow range, indicating consistency in energy prices during these years.
- 2021-2022: A noticeable rise in the energy price index is observed, especially in 2022, where the values spike around mid-year, potentially reflecting external factors such as geopolitical or economic shifts.
- 2023: The data highlights a sharp increase during the latter months of the year, showing a significant upward trend compared to previous years, possibly hinting at inflation or other crises.
Script Summary:
import lightningchart as lc
import pandas as pd
lc.set_license(open(license-key').read().strip())
data = pd.read_excel('dataset/Processed.xlsx', sheet_name='ecpi_m')
selected_country_data = data[data['Country'] == "Ukraine"].iloc[:, 5:].filter(regex='^2018|^2019|^2020|^2021|^2022|^2023')
data_t = selected_country_data.T
data_t.columns = ['Index Value']
data_t['Year'] = data_t.index.str[:4].astype(int)
data_t['Month'] = data_t.index.str[4:6].astype(int)
chart = lc.ChartXY(theme=lc.Themes.Black, title="Energy Price Index for Ukraine (2018-2023)")
chart.get_default_x_axis().set_title('Month')
chart.get_default_y_axis().set_title('Value')
legend = chart.add_legend()
for year in range(2018, 2024):
year_data = data_t[data_t['Year'] == year]
chart.add_line_series().set_name(str(year)).add(list(year_data['Month']), list(year_data['Index Value']))
chart.open()
Significance of Results:
- Economic Stability: The relatively stable index in earlier years could point to a balanced energy market.
- Impact of External Events: The sharp rise in 2022 and 2023 suggests external disruptions such as global conflicts or policy changes impacting energy prices.
- Policy Implications: The upward trend emphasizes the need for energy price regulation and alternative energy sourcing to stabilize future trends.
- Forecasting Needs: Identifying periods of sharp increases could help design predictive models for mitigating economic shocks related to energy prices.
Food Price Index Dashboard for Ukraine (2018-2023)
Trends Interpretation:
As previously noted for the Energy Price Index, a stable trend is observed from 2018 to 2020, followed by sharp increases in 2021 and 2022, indicating external disruptions. However, in this case, the food price index specifically highlights:
- 2022: A peak mid-year, suggesting heightened supply chain issues or inflationary pressures.
- 2023: While growth continues, the increase is less steep compared to 2022, hinting at a possible stabilization of food prices.
import lightningchart as lc
import pandas as pd
lc.set_license(open('license-key').read().strip())
data = pd.read_excel('dataset/Processed.xlsx', sheet_name='fcpi_m')
selected_country_data = data[data['Country'] == "Ukraine"].iloc[:, 5:].filter(regex='^2018|^2019|^2020|^2021|^2022|^2023')
data_t = selected_country_data.T
data_t.columns = ['Index Value']
data_t['Year'] = data_t.index.str[:4].astype(int)
data_t['Month'] = data_t.index.str[4:6].astype(int)
chart = lc.ChartXY(theme=lc.Themes.Black, title="Food Price Index for Ukraine (2018-2023)")
chart.get_default_x_axis().set_title('Month')
chart.get_default_y_axis().set_title('Value')
legend = chart.add_legend()
for year in range(2018, 2024):
year_data = data_t[data_t['Year'] == year]
chart.add_line_series().set_name(str(year)).add(list(year_data['Month']), list(year_data['Index Value']))
chart.open()
Significance of Results:
As with energy prices, the significant rise in food prices reflects broader economic challenges. The 2022 peak underscores vulnerabilities in food supply chains, emphasizing the need for improved resilience planning.
Unlike the energy index, the food price index shows slightly more stabilization in 2023, offering a potential opportunity for recovery strategies in agriculture and food production.
Food Price Index Heatmap for Albania (2000-2023)
Trends Interpretation:
- Overall Visualization: The heatmap illustrates the monthly variation in the food price index across the years from 2000 to 2023. The vertical axis represents months (1-12), while the horizontal axis represents years (2000-2023). Blue represents lower index values, and red represents higher index values.
- Key Observations:
- Lower Intensities (Blue): Dominant in the early years (2000-2010), indicating relatively stable or lower food prices across all months.
- Increasing Intensities (Red): From around 2010 onwards, there is a clear shift toward higher intensities, with more red visible in the heatmap, particularly at the top (winter months). This suggests that food prices have been increasing steadily over the years, especially during the winter months.
- Seasonal Patterns: Higher intensity (red) is more pronounced in the winter months (11-12), indicating that food prices tend to peak during the end of each year.
import pandas as pd
import numpy as np
import lightningchart as lc
lc.set_license(open('license-key').read().strip())
# Load data and filter for Albania
data = pd.read_excel('dataset/Processed.xlsx', sheet_name='fcpi_m')
selected_country_data = data[data['Country'] == "Albania"].iloc[:, 5:].filter(regex='^2000|^2023')
# Transform data for heatmap
data_t = selected_country_data.T
data_t.columns = ['Index Value']
data_t['Year'] = data_t.index.str[:4].astype(int)
data_t['Month'] = data_t.index.str[4:6].astype(int)
heatmap_data = data_t.pivot(index="Month", columns="Year", values="Index Value").fillna(0).values
years_ms = [int(pd.Timestamp(year=year, month=1, day=1).timestamp() * 1000) for year in data_t['Year'].unique()]
# Create heatmap
chart = lc.ChartXY(title="Food Price Index Heatmap for Albania (2000-2023)", theme=lc.Themes.Dark)
heatmap_series = chart.add_heatmap_grid_series(columns=heatmap_data.shape[0], rows=heatmap_data.shape[1])
heatmap_series.set_start(x=years_ms[0], y=1).set_end(x=years_ms[-1], y=12)
heatmap_series.invalidate_intensity_values(heatmap_data.tolist())
heatmap_series.set_palette_coloring([
{"value": np.min(heatmap_data), "color": lc.Color(0, 0, 255)},
{"value": np.max(heatmap_data), "color": lc.Color(255, 0, 0)}
])
chart.get_default_x_axis().set_title('Year').set_tick_strategy('DateTime', utc=True)
chart.get_default_y_axis().set_title('Month').set_interval(1, 12, 1)
chart.add_legend(data=heatmap_series).set_title('Index Intensity')
chart.open()
Significance of Results:
- Economic Trends: The increase in intensity over time reflects long-term inflation in the food market in Albania. The peak during the winter months suggests potential supply chain constraints or seasonal demand spikes driving up prices.
- Policy Insights: Authorities could focus on addressing price stability, particularly during the winter months, to ensure food affordability for consumers.
- Strategic Planning: This heatmap highlights the need for targeted seasonal interventions and strategies for improving food supply resilience during periods of increased prices.
Energy Price Index Heatmap for Albania (2000-2023)
Trends Interpretation:
- Horizontal Axis (Years): The heatmap shows the variation in energy price index across the years 2000 to 2023.
- Vertical Axis (Months): Monthly variations are depicted, from January (1) to December (12).
- Key Observations:
- Early Years (2000-2010): The lower part of the heatmap is predominantly blue, indicating relatively low energy price intensity across all months during these years.
- Post-2010: A gradual shift toward red intensity, with a visible increase in the energy price index, particularly in the upper months (October to December).
- Recent Years (2020-2023): The intensity becomes predominantly red, signifying a sharp rise in energy prices across most months, especially during the colder months (late in the year).
import pandas as pd
import numpy as np
import lightningchart as lc
lc.set_license(open('license-key').read().strip())
data = pd.read_excel('dataset/Processed.xlsx', sheet_name='ecpi_m')
selected_country_data = data[data['Country'] == "Albania"].iloc[:, 5:].filter(regex='^2000|^2023')
data_t = selected_country_data.T
data_t.columns = ['Index Value']
data_t['Year'] = data_t.index.str[:4].astype(int)
data_t['Month'] = data_t.index.str[4:6].astype(int)
heatmap_data = data_t.pivot(index="Month", columns="Year", values="Index Value").fillna(0).values
years_ms = [
int(pd.Timestamp(year=year, month=1, day=1).timestamp() * 1000)
for year in data_t['Year'].unique()
]
chart = lc.ChartXY(title="Energy Price Index Heatmap for Albania (2000-2023)", theme=lc.Themes.Dark)
heatmap_series = chart.add_heatmap_grid_series(columns=heatmap_data.shape[1], rows=heatmap_data.shape[0])
heatmap_series.set_start(x=years_ms[0], y=1).set_end(x=years_ms[-1], y=12).set_step(x=(years_ms[-1] - years_ms[0]) / heatmap_data.shape[1], y=1)
heatmap_series.set_intensity_interpolation(True).invalidate_intensity_values(heatmap_data.tolist()).hide_wireframe()
heatmap_series.set_palette_coloring([
{"value": np.min(heatmap_data), "color": lc.Color(0, 0, 255)},
{"value": np.max(heatmap_data), "color": lc.Color(255, 0, 0)}
])
chart.get_default_x_axis().set_title('Year').set_tick_strategy('DateTime', utc=True)
chart.get_default_y_axis().set_title('Month').set_interval(1, 12, 1)
chart.add_legend(data=heatmap_series).set_title('Index Intensity')
chart.open()
Significance of Results:
- Seasonal Patterns: Higher intensities toward the upper part of the heatmap suggest that energy prices typically peak in the winter months, likely due to increased heating demands.
- Economic Impact: The sustained rise in energy prices post-2010 reflects the growing costs of energy resources, potentially driven by geopolitical events or supply-demand imbalances.
- Policy Recommendations: Addressing seasonal spikes in energy prices could help stabilize household and industrial energy costs. Initiatives such as energy subsidies or alternative energy sources may mitigate these price pressures.
Real-Time Dashboard: Energy Price Index Growth for Continents (2000-2023)
Overview:
The dashboard displays real-time Energy Price Index Growth (%) across six continents (Africa, Asia, Europe, North America, Oceania, and South America) for each year from 2000 to 2023. Each gauge dynamically updates to show the percentage growth for a specific continent, categorized into four intervals:
- Blue: Significant negative growth (-50% to -10%)
- Orange: Moderate negative growth (-10% to 0%)
- Yellow: Moderate positive growth (0% to 10%)
- Red: Significant positive growth (10% to 50%).
Observations:
- Africa: Exhibits the highest volatility, with sharp growth spikes in 2022 (80.6%) and 2023 (493.2%).
- Asia: Shows steady growth with major spikes in 2021 (8.8%) and 2022 (32.6%).
- Europe: Experiences moderate growth, peaking at 20.8% in 2022 but showing minor growth in 2023 (5.7%).
- North America: Demonstrates stable growth, peaking modestly in 2021 (6.4%) and 2022 (9.6%).
- Oceania: Maintains smaller fluctuations, with moderate growth in 2022 (8.2%) but lower intensity in most years.
- South America: Shows consistently positive growth with peaks in 2021 (14%) and 2022 (23.2%).
Key Features:
- Real-Time Updates: The dashboard dynamically updates each second to display growth for the next year, creating an engaging and interactive visualization.
- Color-Coded Indicators: The intervals provide quick visual cues about growth severity for each continent.
pandas as pd
import lightningchart as lc
import time
from pycountry_convert import country_name_to_country_alpha2, country_alpha2_to_continent_code
lc.set_license(open('license-key').read().strip())
data = pd.read_excel('dataset/Processed.xlsx', sheet_name='ecpi_m')
# Add continent information to the dataset
def get_continent(country_name):
try:
code = country_name_to_country_alpha2(country_name)
return {'AF': 'Africa', 'AS': 'Asia', 'EU': 'Europe',
'NA': 'North America', 'SA': 'South America', 'OC': 'Oceania'}.get(
country_alpha2_to_continent_code(code), 'Unknown')
except:
return 'Unknown'
data['Continent'] = data['Country'].apply(get_continent)
data = data[data['Continent'] != 'Unknown']
# Calculate growth percentage
def calculate_growth(year, prev_year):
try:
current = data.filter(like=str(year)).groupby('Continent').mean().mean(axis=1)
previous = data.filter(like=str(prev_year)).groupby('Continent').mean().mean(axis=1)
return ((current - previous) / previous) * 100
except:
return None
# Create a dashboard with gauges for each continent
dashboard = lc.Dashboard(theme=lc.Themes.TurquoiseHexagon, rows=2, columns=3)
gauges = {c: dashboard.GaugeChart(row_index=i // 3, column_index=i % 3)
.set_title(f"{c}: Growth (%)").set_angle_interval(225, -45)
.set_interval(-50, 50).set_bar_thickness(20).set_value_indicator_thickness(10)
.set_value_indicators([
{'start': -50, 'end': -10, 'color': lc.Color('blue')},
{'start': -10, 'end': 0, 'color': lc.Color('orange')},
{'start': 0, 'end': 10, 'color': lc.Color('yellow')},
{'start': 10, 'end': 50, 'color': lc.Color('red')}])
for i, c in enumerate(['Africa', 'Asia', 'Europe', 'North America', 'Oceania', 'South America'])}
# Update gauges dynamically for each year
dashboard.open(live=True)
for year in range(2000, 2024):
growth = calculate_growth(year, year - 1)
if growth is not None:
for continent, percentage in growth.items():
if continent in gauges:
gauges[continent].set_value(percentage).set_title(f"{continent}: Growth ({year}) (%)")
time.sleep(1)
Significance of Results:
- Africa’s Volatility: The sharp spikes in 2022 and 2023 suggest external economic shocks or resource demand surges.
- Asia’s Steady Rise: Indicates sustained economic development, with growing energy demands.
- Europe’s Stability: Reflects moderate resilience, though slightly impacted in 2022.
- Strategic Planning: The dashboard provides a clear visualization tool for policymakers and researchers to monitor and respond to trends in energy price growth across continents.
Bar Chart: Yearly Comparison of FCPI and ECPI for Turkey (2018-2023)
Trends and Observations:
- Prominent Peak in 2023:
- For Turkey, the Food Consumer Price Index (FCPI) reached a record high of 732, while the Energy Consumer Price Index (ECPI) was significantly lower at 491.
- Gradual Decline Over Time:
- Starting from 2023 (left side of the chart) to 2000 (right side), both indices display a progressive decrease year by year.
- The gap between FCPI and ECPI remains evident for most years, especially in recent periods, but narrows as values drop below 100 in earlier years.
- Stable Values from 2000-2015:
- During this period, indices for Turkey remained low and steady, fluctuating between 10-50, showing relative stability in food and energy prices compared to recent years.
import lightningchart as lc
import pandas as pd
lc.set_license(open('license-key').read().strip())
file_path = 'dataset/Processed.xlsx'
fcpi_data = pd.read_excel(file_path, sheet_name='fcpi_m')
ecpi_data = pd.read_excel(file_path, sheet_name='ecpi_m')
country = "Turkey"
if country in fcpi_data['Country'].values and country in ecpi_data['Country'].values:
def calculate_yearly_averages(data, start_year=2000, end_year=2023):
return {str(year): data.filter(like=str(year)).mean(axis=1).values[0]
for year in range(start_year, end_year + 1) if str(year) in data}
fcpi_yearly_avg = calculate_yearly_averages(fcpi_data[fcpi_data['Country'] == country])
ecpi_yearly_avg = calculate_yearly_averages(ecpi_data[ecpi_data['Country'] == country])
valid_years = sorted(fcpi_yearly_avg.keys() & ecpi_yearly_avg.keys())
data = [
{'subCategory': 'FCPI', 'values': [fcpi_yearly_avg[year] for year in valid_years]},
{'subCategory': 'ECPI', 'values': [ecpi_yearly_avg[year] for year in valid_years]},
]
chart = lc.BarChart(
vertical=True, theme=lc.Themes.Light,
title=f'Yearly Comparison of FCPI and ECPI for {country} (2018-2023)'
)
chart.set_data_grouped(valid_years, data)
chart.set_label_rotation(45).set_value_label_font_size(14).set_bars_margin(0.2)
chart.add_legend().add(chart)
chart.open()
Insights:
- Economic Trends in Turkey:
- The 2023 and 2022 may be attributed to inflationary pressures or specific economic challenges impacting Turkey’s food and energy markets disproportionately.
- The decline toward 2000 reflects historical stability in Turkey’s consumer price indices before recent economic turbulence.
- Divergence in 2023:
- The substantial gap in 2023 suggests that food prices in Turkey are experiencing sharper inflationary pressures compared to energy prices, highlighting potential sector-specific challenges.
Radar Chart: Inflation and Price Indices for Turkey (2015-2023)
Trends and Observations:
- FCPI (Food Consumer Price Index):
- High Values in 2023: As mentioned earlier, FCPI experienced a sharp increase in 2023, highlighting significant inflationary pressures in the food sector for Turkey.
- Stability Before 2021: Similar to observations in the bar chart, FCPI remained relatively stable between 2015 and 2020.
- ECPI (Energy Consumer Price Index):
- Gradual Increase: ECPI followed a consistent upward trend, as also seen in the bar chart, reflecting rising energy prices over time.
- Lower Than FCPI: As mentioned previously, ECPI consistently remained below FCPI across all years, highlighting a slower inflationary trend in energy compared to food.
- DEF_A (GDP Deflator Growth Rate):
- Moderate and Stable: DEF_A values showed consistent moderate growth, indicating overall economic stability despite fluctuations in FCPI and ECPI.
import lightningchart as lc
import pandas as pd
lc.set_license(open('license-key').read().strip())
# Load datasets
file_path = 'dataset/Processed.xlsx'
fcpi_data = pd.read_excel(file_path, sheet_name='fcpi_m')
ecpi_data = pd.read_excel(file_path, sheet_name='ecpi_m')
def_a_data = pd.read_excel(file_path, sheet_name='def_a')
# Filter for Turkey and calculate yearly averages
country = "Turkey"
if all(country in data['Country'].values for data in [fcpi_data, ecpi_data, def_a_data]):
years = [str(year) for year in range(2015, 2024)]
def calculate_yearly_averages(data, years):
return [
data.filter(like=year).mean(axis=1).values[0] if year in data else None
for year in years
]
fcpi_avg = calculate_yearly_averages(fcpi_data[fcpi_data['Country'] == country], years)
ecpi_avg = calculate_yearly_averages(ecpi_data[ecpi_data['Country'] == country], years)
def_a_values = [
def_a_data[def_a_data['Country'] == country].get(year, pd.Series([None])).values[0]
for year in map(int, years)
]
# Create radar chart
chart = lc.SpiderChart(theme=lc.Themes.TurquoiseHexagon, title=f'Radar Chart: FCPI, ECPI, and DEF_A for {country} (2015-2023)')
for year in years:
chart.add_axis(tag=year)
chart.add_series(name='FCPI', values=fcpi_avg, line_color=lc.Color(31, 119, 180), fill_color=lc.Color(31, 119, 180, 100))
chart.add_series(name='ECPI', values=ecpi_avg, line_color=lc.Color(255, 127, 14), fill_color=lc.Color(255, 127, 14, 100))
chart.add_series(name='DEF_A', values=def_a_values, line_color=lc.Color(44, 160, 44), fill_color=lc.Color(44, 160, 44, 100))
chart.add_legend()
chart.open()
else:
print(f"{country} does not exist in all datasets.")
Key Insights:
- Economic Pressures:
-
- As previously noted, the sharp increase in FCPI and ECPI in 2023 underscores Turkey’s vulnerability to inflation, particularly in food and energy sectors.
- Policy Implications:
-
- Similar to the bar chart insights, targeted interventions in the food sector are essential to address the growing inflationary challenges reflected by the high FCPI values in 2023.
- Resilient GDP:
-
- As observed earlier, the stable DEF_A values suggest that Turkey’s economic growth remained resilient, even during inflationary spikes.
Chart Highlights – Complementary Insights:
This radar chart reinforces the trends seen in the bar chart but offers a comparative multi-index perspective, emphasizing the interrelation between food prices, energy prices, and GDP growth.
Balloon Race Chart: GDP Deflator Growth Rate and Energy Index for Turkey, Iran, and Egypt (2000-2023):
- The Balloon Race Chart is a 3D visualization of GDP Deflator Growth Rate (balloon height) and Energy Index (balloon brightness) for the countries Turkey, Iran, Islamic Rep., and Egypt, Arab Rep. from 2000 to 2023.
- X-Axis: Represents the countries.
- Y-Axis: Shows normalized GDP Deflator Growth Rate (inflation) between 0 and 2.
- Z-Axis: Represents the timeline from 2000 to 2023.
Trends and Observations:
- Turkey (Blue Balloon):
- Significant Inflation Growth: The balloon height for Turkey rises sharply in recent years, indicating substantial growth in GDP deflator (inflation).
- Moderate Energy Brightness: The balloon’s brightness, corresponding to energy index, is moderate but shows an upward trend in recent years.
- Iran, Islamic Rep. (Green Balloon):
- Unstable Inflation Growth: Iran exhibits significant fluctuations in balloon height, indicating volatile inflation rates. However, there is an overall upward trend.
- Sharp Energy Index Increase: The brightness of Iran’s balloon increases significantly in recent years, showing a surge in energy index values.
- Egypt, Arab Rep. (Red Balloon):
- Stable and Low Inflation: The balloon for Egypt remains consistently lower in height compared to Turkey and Iran, reflecting a relatively stable and lower inflation rate.
- Gradual Increase in Energy Brightness: The energy index for Egypt increases steadily over the years, leading to higher balloon brightness.
import lightningchart as lc
import pandas as pd
import trimesh
import asyncio
lc.set_license(open('license-key').read().strip())
file_path = 'dataset/Processed.xlsx'
def_a_data = pd.read_excel(file_path, sheet_name='def_a')
ecpi_data = pd.read_excel(file_path, sheet_name='ecpi_m')
countries = ["Turkey", "Iran, Islamic Rep.", "Egypt, Arab Rep."]
years = [str(year) for year in range(2000, 2024)]
# Normalize inflation and energy data
def normalize(data, min_val, max_val, scale=1):
return [(value - min_val) / (max_val - min_val) * scale for value in data]
inflation_data = {
country: normalize(
def_a_data.loc[def_a_data['Country'] == country].filter(regex='|'.join(years)).iloc[0].tolist(),
min_val=def_a_data.filter(regex='|'.join(years)).min().min(),
max_val=def_a_data.filter(regex='|'.join(years)).max().max(),
scale=2
)
for country in countries
}
energy_data = {
country: normalize(
ecpi_data.loc[ecpi_data['Country'] == country].filter(regex='|'.join(years)).mean(axis=1).tolist(),
min_val=ecpi_data.filter(regex='|'.join(years)).min().min(),
max_val=ecpi_data.filter(regex='|'.join(years)).max().max()
)
for country in countries
}
balloon_colors = {"Turkey": (0, 0, 255), "Iran, Islamic Rep.": (0, 255, 0), "Egypt, Arab Rep.": (255, 0, 0)}
# Chart setup
chart = lc.Chart3D(title="Balloon Race: Normalized GDP Deflator Growth Rate & Energy", theme=lc.Themes.Light)
chart.get_default_x_axis().set_title('Countries').set_interval(-0.5, 4.5, stop_axis_after=True)
chart.get_default_y_axis().set_title('Height (Inflation)').set_interval(0, 2, stop_axis_after=True)
chart.get_default_z_axis().set_title('Time (Years)')
# Balloons and lines
balloons = {}
line_series = {}
for i, country in enumerate(countries):
x_position = 0.75 + i * 1.5
balloons[country] = chart.add_mesh_model().set_model_location(x_position, 0, 0).set_scale(0.005)
line_series[country] = chart.add_line_series().set_name(f"{country} Path").set_line_color(lc.Color(*balloon_colors[country]))
async def move_balloons():
for year_idx in range(len(years) - 1):
for step in range(50):
for i, country in enumerate(countries):
x_pos = 0.75 + i * 1.5
h_start, h_end = inflation_data[country][year_idx:year_idx + 2]
b_start, b_end = energy_data[country][year_idx:year_idx + 2]
height = h_start + (h_end - h_start) * (step / 50)
brightness = b_start + (b_end - b_start) * (step / 50)
balloons[country].set_model_location(x_pos, height, year_idx + (step / 50))
line_series[country].add([x_pos], [height], [year_idx + (step / 50)])
await asyncio.sleep(0.02)
chart.open(live=True)
asyncio.run(move_balloons())
Key Insights:
- Real-Time Representation: The chart demonstrates dynamic balloon movements in real time, visually depicting the changes in inflation (height) and energy (brightness) over the years.
- Comparative View: This chart allows for a direct comparison of economic trends between the three countries.
- Economic Implications:
- Turkey and Iran: Both countries show significant inflation growth, with Turkey having a more consistent upward trajectory.
- Egypt: While relatively stable in inflation, Egypt shows a gradual increase in energy consumption, reflected in the brightness.
Chart Highlights:
- Visual Dynamics: The live motion of the balloons and their respective paths make it easy to identify trends and differences across countries.
- Complementary Insights: The chart provides an engaging and intuitive way to analyze inflation and energy trends, supporting a broader understanding of economic conditions in Turkey, Iran, and Egypt.
Conclusion
This study highlights the interconnected dynamics of inflation, food, and energy price indices across regions and countries. Visualizations created using LightningChart provide a comprehensive and intuitive understanding of these trends.
Policymakers can leverage these insights to address inflationary pressures, ensure food and energy security, and stabilize economic growth. For instance, interventions targeting food inflation in Turkey and energy price volatility in Iran could mitigate broader economic risks.
By utilizing state-of-the-art visualization tools, this research bridges the gap between complex economic data and actionable insights, setting a benchmark for future analyses in macroeconomic trends and policy evaluation.
Continue learning with LightningChart
High-Performance WPF Charts : The Truth
What about manufacturers’ claims about Fastest rendering charts? There are a lot of false marketing terms used in the industry, so we are going to tell the truth, based on facts that anyone can reproduce and verify.
No Results Found
The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.
No Results Found
The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.
