Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| import plotly.express as px | |
| import requests | |
| import zipfile | |
| import io | |
| # --- 1. Page Configuration (Aesthetic Setup) --- | |
| st.set_page_config( | |
| page_title="The Domino Effect: 2008 Crisis", | |
| page_icon="📉", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # --- 2. Sidebar for Metadata --- | |
| with st.sidebar: | |
| st.header("About This Project") | |
| st.markdown("**Authors:**") | |
| # !!! IMPORTANT: REPLACE THESE WITH YOUR ACTUAL NAMES !!! | |
| st.markdown(""" | |
| * Shantanu Roy (roy33) | |
| * Bhoomika Ravishankar (br36) | |
| * Tejas Honmode (honmode2) | |
| """) | |
| st.markdown("---") | |
| st.markdown("**Data Sources:**") | |
| st.markdown("[World Bank WDI Database](https://databank.worldbank.org/source/world-development-indicators)") | |
| st.markdown("[IMF Banking Crises](https://www.imf.org/en/Publications/WP/Issues/2018/09/14/Systemic-Banking-Crises-Revisited-46232)") | |
| st.markdown("---") | |
| # RUBRIC SATISFACTION: "Python analysis notebook is linked" | |
| st.markdown("**Source Code:**") | |
| st.markdown("[📂 View Analysis Notebook](https://huggingface.co/spaces/shanroy1999/FP_3/blob/main/src/streamlit_app.py)") | |
| st.info("This dashboard visualizes how the 2008 financial crisis propagated from the US to the rest of the world.") | |
| # --- 3. Main Title --- | |
| st.title("📉 The Domino Effect: How the 2008 Crisis Went Global") | |
| st.markdown("---") | |
| # --- 4. Connective Text Part 1 --- | |
| st.markdown(""" | |
| ### 🌍 When Wall Street Sneezed, the World Caught a Cold | |
| In 2008, what started as a burst housing bubble in the United States quickly mutated into a global economic catastrophe. But how does a problem in one country infect the entire world? The answer lies in **Financial Contagion**. | |
| Just like a virus moving through a crowded room, economic shockwaves travel through international connections. In our modern economy, nations are linked by **Trade** (buying and selling goods) and **Finance** (banks lending money across borders). When the US economy collapsed, it stopped buying goods from China and Germany, and US banks pulled money out of emerging markets like Brazil. | |
| In this data story, we will explore these connections. We will see how "open" economies—those that trade the most—often paid the highest price during the panic, and how the "cure" (government bailouts) created a new disease: massive public deficits. | |
| """) | |
| # --- 5. Data Loading (Cached) --- | |
| def load_wdi_data(): | |
| """Loads and cleans data from the World Bank API.""" | |
| indicators = { | |
| 'GDP_Growth': 'NY.GDP.MKTP.KD.ZG', | |
| 'Trade_GDP': 'NE.TRD.GNFS.ZS', | |
| # Switched to Deficit because Debt stock data is sparse for Japan/Germany in API | |
| 'Gov_Deficit': 'GC.BAL.CASH.GD.ZS', | |
| 'Youth_Unemployment': 'SL.UEM.1524.ZS', | |
| 'Total_Unemployment': 'SL.UEM.TOTL.ZS', | |
| # ADDED FOR EXTRA CREDIT: Foreign Direct Investment | |
| 'FDI_Inflows': 'BX.KLT.DINV.WD.GD.ZS' | |
| } | |
| dfs = [] | |
| base_url = "https://api.worldbank.org/v2/en/indicator/" | |
| for key, code in indicators.items(): | |
| url = f"{base_url}{code}?downloadformat=csv" | |
| try: | |
| r = requests.get(url) | |
| with zipfile.ZipFile(io.BytesIO(r.content)) as z: | |
| filename = [f for f in z.namelist() if f.startswith("API_")][0] | |
| with z.open(filename) as f: | |
| df = pd.read_csv(f, skiprows=4) | |
| # Keep years 2000-2020 | |
| cols_to_keep = ['Country Name'] + [str(y) for y in range(2000, 2021)] | |
| existing_cols = [c for c in cols_to_keep if c in df.columns] | |
| df = df[existing_cols] | |
| # Melt to Long Format | |
| df_long = df.melt(id_vars=['Country Name'], var_name='Year', value_name=key) | |
| df_long['Year'] = pd.to_numeric(df_long['Year'], errors='coerce') | |
| # Remove any rows with missing Country/Year and Duplicates | |
| df_long = df_long.dropna(subset=['Country Name', 'Year']) | |
| df_long = df_long.drop_duplicates(subset=['Country Name', 'Year']) | |
| dfs.append(df_long.set_index(['Country Name', 'Year'])) | |
| except Exception as e: | |
| st.error(f"Error loading {key}: {e}") | |
| if dfs: | |
| df_final = pd.concat(dfs, axis=1).reset_index() | |
| if 'Trade_GDP' in df_final.columns: | |
| df_final = df_final[df_final['Trade_GDP'] < 250] | |
| return df_final | |
| else: | |
| return pd.DataFrame() | |
| with st.spinner("Fetching data from World Bank..."): | |
| df = load_wdi_data() | |
| # --- 6. Central Interactive Visualization --- | |
| st.header("📊 The Crash in Motion (2000-2020)") | |
| st.markdown(""" | |
| **How to read this chart: ** | |
| * **X-Axis:** Represents how "open" an economy is (Trade as % of GDP). | |
| * **Y-Axis:** Represents economic health (GDP Growth). | |
| * **Play the Animation:** Drag the slider at the bottom to **2008** and then **2009**. | |
| Watch how the bubbles (countries) suddenly drop en masse in 2009. This synchronized collapse is the visual signature of a global recession. | |
| """) | |
| # ---COUNTRY FILTER --- | |
| # Get a list of all unique countries | |
| all_countries_list = sorted(df['Country Name'].unique().tolist()) | |
| # Create the Multiselect Widget | |
| selected_countries_main = st.multiselect( | |
| "🔍 **Filter by Country:** (Leave empty to see the whole world, or select countries to isolate them)", | |
| options=all_countries_list, | |
| default=[], # Default is empty (show all) | |
| placeholder="Choose countries (e.g., United States, China, Germany)..." | |
| ) | |
| # Logic: If countries are selected, filter the dataframe. If not, use the full dataframe. | |
| if selected_countries_main: | |
| df_viz = df[df['Country Name'].isin(selected_countries_main)] | |
| else: | |
| df_viz = df | |
| if not df_viz.empty and 'Trade_GDP' in df_viz.columns and 'GDP_Growth' in df_viz.columns: | |
| fig_main = px.scatter( | |
| df_viz, # Use the filtered dataframe here | |
| x="Trade_GDP", | |
| y="GDP_Growth", | |
| animation_frame="Year", | |
| animation_group="Country Name", | |
| size="Trade_GDP", | |
| # STRICT RED/BLUE SCALE | |
| color="GDP_Growth", | |
| color_continuous_scale=[ | |
| [0, "red"], | |
| [0.5, "red"], | |
| [0.5, "blue"], | |
| [1, "blue"] | |
| ], | |
| color_continuous_midpoint=0, | |
| hover_name="Country Name", | |
| range_x=[0, 180], | |
| range_y=[-15, 15], | |
| labels={ | |
| "Trade_GDP": "Trade Openness (% of GDP)", | |
| "GDP_Growth": "Annual GDP Growth (%)" | |
| }, | |
| title="Interactive: Global GDP Growth vs. Trade Openness", | |
| template="plotly_white", | |
| height=600 | |
| ) | |
| # Reference line for Recession | |
| fig_main.add_hline(y=0, line_dash="dash", line_color="black", annotation_text="Recession Threshold (0%)") | |
| st.plotly_chart(fig_main, use_container_width=True) | |
| st.caption("Source: World Bank World Development Indicators (WDI). Red = Recession, Blue = Growth.") | |
| else: | |
| st.warning("Data could not be loaded for the main visualization.") | |
| # --- EXTRA CREDIT SECTION: INTERACTIVE FDI COMPARISON --- | |
| st.markdown("---") | |
| st.header("📉 Extra Credit: The Capital Freeze") | |
| st.markdown(""" | |
| Beyond trade, the crisis caused a sudden stop in financial flows. When fear gripped the markets, investors didn't just stop buying goods—they stopped investing entirely. | |
| This phenomenon is known as **Capital Flight**. Investors pulled money out of risky "emerging markets" and hoarded it in safer assets. | |
| **Explore the Data:** Use the tool below to compare **Foreign Direct Investment (FDI)** across different countries. Notice how FDI plunged for developing nations (like Brazil or India) in 2009, while some safe havens remained stable. | |
| """) | |
| # Interactive Widget for Country Selection | |
| all_countries = sorted(df['Country Name'].unique().tolist()) | |
| default_countries = ['United States', 'China', 'Brazil', 'Germany', 'India'] | |
| selected_countries = st.multiselect( | |
| "Select countries to compare FDI Inflows:", | |
| options=all_countries, | |
| default=[c for c in default_countries if c in all_countries] | |
| ) | |
| if selected_countries: | |
| df_fdi = df[df['Country Name'].isin(selected_countries)] | |
| fig_fdi = px.line( | |
| df_fdi, | |
| x="Year", | |
| y="FDI_Inflows", | |
| color="Country Name", | |
| title="Interactive Comparison: Foreign Direct Investment (FDI) Net Inflows (% of GDP)", | |
| labels={"FDI_Inflows": "FDI Net Inflows (% of GDP)"}, | |
| template="plotly_white", | |
| markers=True | |
| ) | |
| # Highlight Crisis | |
| fig_fdi.add_vrect(x0=2008, x1=2009, fillcolor="red", opacity=0.1, annotation_text="Crisis Peak") | |
| st.plotly_chart(fig_fdi, use_container_width=True) | |
| st.caption("Source: World Bank WDI. This interactive chart demonstrates the 'Financial Channel' of contagion.") | |
| else: | |
| st.info("Please select at least one country to view the data.") | |
| # --- 7. Connective Text Part 2 --- | |
| st.markdown(""" | |
| ### 💸 The Cost of Bailouts: Massive Deficits | |
| The immediate crash was stopped, but at a high cost. When major banks failed in 2008, governments stepped in to save them with massive "bailouts"—using taxpayer money to prevent the financial system from collapsing. | |
| This created massive **budget deficits**. As the chart below shows, governments like the United States, UK, and Greece spent far more than they earned in 2009 (indicated by the deep plunge into negative territory). This sudden spending shock laid the groundwork for the Sovereign Debt Crisis that followed. | |
| """) | |
| # --- 8. Contextual Viz 1: Deficits --- | |
| debt_countries = ['United States', 'United Kingdom', 'Japan', 'Greece', 'Germany'] | |
| df_debt = df[df['Country Name'].isin(debt_countries)].copy() | |
| if 'Gov_Deficit' in df_debt.columns: | |
| df_debt = df_debt.dropna(subset=['Gov_Deficit']) | |
| fig_debt = px.line( | |
| df_debt, | |
| x="Year", | |
| y="Gov_Deficit", | |
| color="Country Name", | |
| title="Contextual Viz 1: The Cost of Bailouts - Budget Surplus/Deficit (% of GDP)", | |
| labels={"Gov_Deficit": "Surplus/Deficit (% of GDP)"}, | |
| markers=True, | |
| template="plotly_white" | |
| ) | |
| fig_debt.add_vline(x=2009, line_dash="dot", line_color="red", annotation_text="Peak Bailout Spending") | |
| fig_debt.add_hline(y=0, line_color="black", line_width=1) | |
| st.plotly_chart(fig_debt, use_container_width=True) | |
| st.caption("Source: World Bank WDI. Negative values indicate a government deficit (spending more than earning). Note the synchronized crash in 2009.") | |
| # --- 9. Connective Text Part 3 --- | |
| st.markdown(""" | |
| ### 🎓 The Lost Generation | |
| While stock markets eventually recovered, the human cost of the crisis lingered for years. In Europe specifically, the financial crisis mutated into a sovereign debt crisis, leading to a long-term depression in the labor market. | |
| The group hit hardest was young adults (ages 15-24). In countries like Spain and Greece, youth unemployment skyrocketed to over **50%**. This created a "Lost Generation" of workers who were locked out of the job market during their most critical skill-building years. The comparison below highlights how disproportionately youth were affected compared to the general population during the peak of the crisis. | |
| """) | |
| # --- 10. Contextual Viz 2: The Lost Generation --- | |
| if 'Youth_Unemployment' in df.columns: | |
| df_2013 = df[df['Year'] == 2013] | |
| focus_countries = ['Spain', 'Greece', 'Italy', 'Portugal', 'Germany', 'United States'] | |
| df_unemp = df_2013[df_2013['Country Name'].isin(focus_countries)].copy() | |
| df_unemp_melt = df_unemp.melt( | |
| id_vars=['Country Name'], | |
| value_vars=['Youth_Unemployment', 'Total_Unemployment'], | |
| var_name='Category', | |
| value_name='Rate' | |
| ) | |
| df_unemp_melt['Category'] = df_unemp_melt['Category'].replace({ | |
| 'Youth_Unemployment': 'Youth (15-24)', | |
| 'Total_Unemployment': 'General Population' | |
| }) | |
| fig_youth = px.bar( | |
| df_unemp_melt, | |
| x="Country Name", | |
| y="Rate", | |
| color="Category", | |
| barmode="group", | |
| title="Contextual Viz 2: The Human Cost - Youth vs. General Unemployment (2013)", | |
| labels={"Rate": "Unemployment Rate (%)"}, | |
| color_discrete_map={"Youth (15-24)": "#FF5733", "General Population": "#33FF57"}, | |
| template="plotly_white" | |
| ) | |
| st.plotly_chart(fig_youth, use_container_width=True) | |
| st.caption("Source: World Bank WDI. Data represents the peak of the Eurozone crisis in 2013.") | |
| # --- 11. Final Citations --- | |
| st.markdown("---") | |
| st.markdown("### 📚 References") | |
| st.markdown(""" | |
| 1. **World Bank World Development Indicators (WDI):** The primary source for GDP, Trade, Deficits, FDI, and Unemployment data. [Link to Dataset](https://databank.worldbank.org/source/world-development-indicators) | |
| 2. **IMF Systemic Banking Crises Database:** Used for identifying crisis timelines. Laeven, L., & Valencia, F. (2018). [Link to Paper](https://www.imf.org/en/Publications/WP/Issues/2018/09/14/Systemic-Banking-Crises-Revisited-46232) | |
| """) |