-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1085 lines (893 loc) · 49.7 KB
/
Copy pathapp.py
File metadata and controls
1085 lines (893 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from data_processor import load_data, process_historical_data, filter_data_by_category
from visualization import (
plot_tariff_price_comparison,
plot_historical_tariffs,
plot_category_impact,
plot_price_sensitivity
)
from utils import calculate_tariff_impact
from prediction_models import (
train_linear_regression_model,
train_random_forest_model,
train_time_series_model,
compare_tariff_scenarios,
calculate_scenario_impact,
create_future_scenario
)
# Set page configuration
st.set_page_config(
page_title="Tariff Impact on Tech Prices",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded"
)
def main():
# App title and introduction
st.title("📊 Tariff Impact on Technology Prices")
st.markdown("""
This application analyzes how tariffs affect the prices of technology products across different categories.
Explore historical tariff data, compare price changes, and investigate how different tariff scenarios might
impact technology product prices in the future.
""")
# Load data
try:
tariff_data, price_data, categories = load_data()
# If we successfully loaded data, continue with the app
if tariff_data is not None and price_data is not None:
# Create sidebar for navigation and filters
with st.sidebar:
st.header("Explore Data")
# Navigation
page = st.radio(
"Select a page:",
["Overview", "Historical Analysis", "Category Comparison", "Tariff Simulator", "Prediction Models"]
)
# Filters
st.subheader("Filters")
selected_categories = st.multiselect(
"Select product categories:",
options=categories,
default=categories[:3] if len(categories) >= 3 else categories
)
# Time period selection
years = sorted(tariff_data['Year'].unique())
year_range = st.select_slider(
"Select time period:",
options=years,
value=(years[0], years[-1])
)
st.markdown("---")
st.markdown("""
**Data sources:**
- US International Trade Commission
- Bureau of Labor Statistics
- World Trade Organization
""")
# Filter data based on user selection
filtered_tariff_data = tariff_data[
(tariff_data['Year'] >= year_range[0]) &
(tariff_data['Year'] <= year_range[1])
]
filtered_price_data = price_data[
(price_data['Year'] >= year_range[0]) &
(price_data['Year'] <= year_range[1])
]
if selected_categories:
filtered_tariff_data = filter_data_by_category(filtered_tariff_data, selected_categories)
filtered_price_data = filter_data_by_category(filtered_price_data, selected_categories)
# Display different pages based on navigation
if page == "Overview":
display_overview(filtered_tariff_data, filtered_price_data)
elif page == "Historical Analysis":
display_historical_analysis(filtered_tariff_data, filtered_price_data)
elif page == "Category Comparison":
display_category_comparison(filtered_tariff_data, filtered_price_data, selected_categories)
elif page == "Tariff Simulator":
display_tariff_simulator(tariff_data, price_data, selected_categories)
elif page == "Prediction Models":
display_prediction_models(tariff_data, price_data, selected_categories)
else:
st.error("Failed to load necessary data. Please check back later.")
except Exception as e:
st.error(f"An error occurred: {str(e)}")
st.markdown("Please try again later or contact support if the problem persists.")
def display_overview(tariff_data, price_data):
"""Display overview information about tariffs and their impact on tech prices"""
st.header("Overview: Tariffs and Technology Prices")
# Introduction to tariffs
with st.expander("What are tariffs and how do they affect tech prices?", expanded=True):
st.markdown("""
**Tariffs** are taxes imposed by governments on imported goods. In the context of technology products:
- Tariffs increase the cost of imported components used in manufacturing
- They may be applied to finished technology products imported from other countries
- Increased costs are often passed on to consumers through higher retail prices
- Domestic producers may also raise prices in response to reduced foreign competition
Tariffs are typically implemented for economic or political reasons, such as:
- Protecting domestic industries from foreign competition
- Addressing trade imbalances between countries
- Responding to unfair trade practices
- As leverage in international negotiations
""")
# Key statistics
st.subheader("Key Statistics")
# Create two columns for stats
col1, col2 = st.columns(2)
with col1:
avg_tariff = tariff_data['Tariff_Rate'].mean()
st.metric("Average Tariff Rate", f"{avg_tariff:.2f}%")
# Calculate correlation between tariffs and prices
historical_data = process_historical_data(tariff_data, price_data)
correlation = historical_data[['Tariff_Rate', 'Price_Index']].corr().iloc[0, 1]
st.metric("Tariff-Price Correlation", f"{correlation:.2f}")
with col2:
max_category_tariff = tariff_data.groupby('Category')['Tariff_Rate'].mean().max()
st.metric("Highest Category Tariff (avg)", f"{max_category_tariff:.2f}%")
# Price change calculation
price_change = ((price_data['Price_Index'].iloc[-1] / price_data['Price_Index'].iloc[0]) - 1) * 100
st.metric("Overall Price Change", f"{price_change:.2f}%")
# Main visual comparison of tariffs and prices
st.subheader("Tariff Rates vs. Price Changes")
fig = plot_tariff_price_comparison(tariff_data, price_data)
st.plotly_chart(fig, use_container_width=True)
# Recent developments section
st.subheader("Recent Tariff Developments")
# Get the most recent years of data (last 2 years)
recent_years = sorted(tariff_data['Year'].unique())[-2:]
recent_tariff_data = tariff_data[tariff_data['Year'].isin(recent_years)]
# Calculate and display changes in tariff rates
if len(recent_years) >= 2:
year1, year2 = recent_years
# Group by category and calculate average tariff rates for each year
tariff_by_category_year1 = recent_tariff_data[recent_tariff_data['Year'] == year1].groupby('Category')['Tariff_Rate'].mean()
tariff_by_category_year2 = recent_tariff_data[recent_tariff_data['Year'] == year2].groupby('Category')['Tariff_Rate'].mean()
# Calculate changes
categories_common = list(set(tariff_by_category_year1.index).intersection(set(tariff_by_category_year2.index)))
if categories_common:
changes = pd.DataFrame(index=categories_common)
changes['Year1'] = tariff_by_category_year1[categories_common]
changes['Year2'] = tariff_by_category_year2[categories_common]
changes['Absolute_Change'] = changes['Year2'] - changes['Year1']
changes['Percentage_Change'] = (changes['Absolute_Change'] / changes['Year1']) * 100
# Display a table with the changes
st.dataframe(changes.sort_values('Absolute_Change', ascending=False)
.rename(columns={
'Year1': f'{year1} Rate (%)',
'Year2': f'{year2} Rate (%)',
'Absolute_Change': 'Absolute Change (%)',
'Percentage_Change': 'Percentage Change (%)'
})
.style.format({
f'{year1} Rate (%)': '{:.2f}',
f'{year2} Rate (%)': '{:.2f}',
'Absolute Change (%)': '{:.2f}',
'Percentage Change (%)': '{:.2f}'
}))
# Global context
st.subheader("Global Tariff Context")
st.markdown("""
Recent years have seen significant changes in international trade policies and tariff structures:
- **Trade tensions** between major economies have led to increased tariffs on technology goods
- **Supply chain disruptions** have amplified the impact of tariffs on final product prices
- **Technology transfer concerns** have motivated some technology-specific tariffs
- **Regional trade agreements** have created varying tariff environments across different markets
""")
def display_historical_analysis(tariff_data, price_data):
"""Display historical analysis of tariffs and prices over time"""
st.header("Historical Analysis")
# Process historical data
historical_data = process_historical_data(tariff_data, price_data)
# Display historical trend of tariffs
st.subheader("Historical Tariff Rates")
fig = plot_historical_tariffs(historical_data)
st.plotly_chart(fig, use_container_width=True)
# Analysis of key tariff events
st.subheader("Key Tariff Events and Their Impact")
# Create an expander for each major tariff event
with st.expander("2018: Section 301 Tariffs on Chinese Tech Products"):
st.markdown("""
In 2018, the United States imposed significant tariffs on Chinese technology products under Section 301
of the Trade Act of 1974, citing unfair trade practices related to technology transfer and intellectual property.
**Impact:**
- Initial tariffs of 25% on approximately $50 billion of Chinese imports
- Specifically targeted electronic components, networking equipment, and other technology products
- Led to an estimated 5-10% increase in consumer electronics prices
- Caused supply chain restructuring for many technology manufacturers
""")
# Filter data for this period to show impact
event_data = historical_data[(historical_data['Year'] >= 2017) & (historical_data['Year'] <= 2019)]
if not event_data.empty:
# Calculate before and after metrics
before = event_data[event_data['Year'] == 2017]['Price_Index'].mean()
after = event_data[event_data['Year'] == 2019]['Price_Index'].mean()
change = ((after / before) - 1) * 100
# Display metrics
st.metric("Price Index Change (2017-2019)", f"{change:.2f}%")
with st.expander("2019-2020: Expanded Tariffs on Consumer Electronics"):
st.markdown("""
In late 2019 and early 2020, tariffs were expanded to cover more consumer electronics and technology products,
including computers, smartphones, and other consumer devices.
**Impact:**
- Additional tariffs of 7.5-15% on previously unaffected consumer technology
- Some manufacturers absorbed portions of the tariff costs
- Others passed costs to consumers or relocated manufacturing operations
- Created a complex tariff environment with product-specific exemptions and rates
""")
# Filter data for this period to show impact
event_data = historical_data[(historical_data['Year'] >= 2019) & (historical_data['Year'] <= 2020)]
if not event_data.empty:
# Calculate before and after metrics
before = event_data[event_data['Year'] == 2019]['Price_Index'].mean()
after = event_data[event_data['Year'] == 2020]['Price_Index'].mean()
change = ((after / before) - 1) * 100
# Display metrics
st.metric("Price Index Change (2019-2020)", f"{change:.2f}%")
with st.expander("2022-2023: Semiconductor and Advanced Technology Tariffs"):
st.markdown("""
More recently, countries have implemented targeted tariffs on advanced technologies, particularly
semiconductors and equipment used in their production, reflecting both trade disputes and national security concerns.
**Impact:**
- Created pressure on the global semiconductor supply chain
- Led to increased investment in domestic semiconductor production
- Contributed to component shortages and price increases
- Accelerated technology decoupling between major economies
""")
# Filter data for this period to show impact
event_data = historical_data[(historical_data['Year'] >= 2021) & (historical_data['Year'] <= 2023)]
if not event_data.empty and len(event_data['Year'].unique()) > 1:
# Calculate before and after metrics
first_year = min(event_data['Year'].unique())
last_year = max(event_data['Year'].unique())
before = event_data[event_data['Year'] == first_year]['Price_Index'].mean()
after = event_data[event_data['Year'] == last_year]['Price_Index'].mean()
change = ((after / before) - 1) * 100
# Display metrics
st.metric(f"Price Index Change ({first_year}-{last_year})", f"{change:.2f}%")
# Long-term analysis section
st.subheader("Long-term Tariff Impact Analysis")
# Create three columns for different time periods
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("**Short-term Impact**")
st.markdown("""
- Immediate price increases on affected products
- Inventory stockpiling ahead of tariff implementation
- Consumer purchasing delays
- Temporary sales promotions to maintain market share
""")
with col2:
st.markdown("**Medium-term Impact**")
st.markdown("""
- Supply chain reorganization
- Product redesign to use non-tariffed components
- Shifting manufacturing locations
- Market share redistribution among competitors
""")
with col3:
st.markdown("**Long-term Impact**")
st.markdown("""
- Permanent changes to global supply chains
- Regional technology ecosystems
- R&D investment shifts
- Consumer adaptation to higher price baseline
- New product category development
""")
def display_category_comparison(tariff_data, price_data, selected_categories):
"""Display comparison of tariff impact across different technology categories"""
st.header("Category Comparison")
if not selected_categories:
st.warning("Please select at least one product category in the sidebar to view comparison data.")
return
# Create visualization of category impact
st.subheader("Tariff Impact by Technology Category")
fig = plot_category_impact(tariff_data, price_data, selected_categories)
st.plotly_chart(fig, use_container_width=True)
# Display explanatory text about different categories
st.markdown("""
### Why Different Tech Categories Are Affected Differently
Technology products vary in their sensitivity to tariffs based on several factors:
1. **Supply Chain Complexity**: Products with complex international supply chains are more vulnerable to tariffs
2. **Value-to-Weight Ratio**: High-value products can better absorb tariff costs
3. **Component Origin**: Products using components from multiple countries face varying tariff exposure
4. **Manufacturing Flexibility**: Some categories can more easily relocate production to avoid tariffs
5. **Market Competition**: Competitive markets may force companies to absorb tariff costs
""")
# Category-specific analysis
st.subheader("Category-Specific Analysis")
# Create tabs for each selected category
tabs = st.tabs(selected_categories)
for i, category in enumerate(selected_categories):
with tabs[i]:
# Filter data for this specific category
cat_tariff_data = tariff_data[tariff_data['Category'] == category]
cat_price_data = price_data[price_data['Category'] == category]
if not cat_tariff_data.empty and not cat_price_data.empty:
# Calculate key metrics for this category
avg_tariff = cat_tariff_data['Tariff_Rate'].mean()
max_tariff = cat_tariff_data['Tariff_Rate'].max()
# Calculate price change
sorted_price_data = cat_price_data.sort_values('Year')
first_price = sorted_price_data['Price_Index'].iloc[0]
last_price = sorted_price_data['Price_Index'].iloc[-1]
price_change = ((last_price / first_price) - 1) * 100
# Display metrics in columns
col1, col2, col3 = st.columns(3)
col1.metric("Average Tariff Rate", f"{avg_tariff:.2f}%")
col2.metric("Maximum Tariff Rate", f"{max_tariff:.2f}%")
col3.metric("Overall Price Change", f"{price_change:.2f}%")
# Plot price sensitivity for this category
st.subheader(f"Price Sensitivity Analysis: {category}")
fig = plot_price_sensitivity(cat_tariff_data, cat_price_data)
st.plotly_chart(fig, use_container_width=True)
# Category-specific insights based on the data
st.subheader("Key Insights")
# Compare this category's metrics to the overall average
overall_avg_tariff = tariff_data['Tariff_Rate'].mean()
tariff_comparison = avg_tariff - overall_avg_tariff
if tariff_comparison > 0:
st.markdown(f"- {category} products face **higher than average** tariff rates (+{tariff_comparison:.2f}%)")
else:
st.markdown(f"- {category} products face **lower than average** tariff rates ({tariff_comparison:.2f}%)")
# Calculate correlation between tariffs and prices for this category
if len(cat_tariff_data) > 1 and len(cat_price_data) > 1:
# Merge the data by year
merged_data = pd.merge(
cat_tariff_data.groupby('Year')['Tariff_Rate'].mean().reset_index(),
cat_price_data.groupby('Year')['Price_Index'].mean().reset_index(),
on='Year'
)
if len(merged_data) > 1:
correlation = merged_data['Tariff_Rate'].corr(merged_data['Price_Index'])
if correlation > 0.7:
st.markdown(f"- **Strong positive correlation** ({correlation:.2f}) between tariff rates and prices")
elif correlation > 0.3:
st.markdown(f"- **Moderate positive correlation** ({correlation:.2f}) between tariff rates and prices")
elif correlation > -0.3:
st.markdown(f"- **Weak correlation** ({correlation:.2f}) between tariff rates and prices")
elif correlation > -0.7:
st.markdown(f"- **Moderate negative correlation** ({correlation:.2f}) between tariff rates and prices")
else:
st.markdown(f"- **Strong negative correlation** ({correlation:.2f}) between tariff rates and prices")
# Manufacturing location insights
if "Smartphone" in category or "Computer" in category:
st.markdown("- Production is concentrated in a few countries, making it vulnerable to targeted tariffs")
elif "Component" in category:
st.markdown("- Complex supply chains span multiple countries, creating layered tariff exposure")
elif "Peripheral" in category:
st.markdown("- Manufacturing can be more easily relocated to avoid tariffs")
# Value chain position
if "Semiconductor" in category:
st.markdown("- Positioned early in the tech value chain, tariff impacts cascade to multiple downstream products")
elif "Display" in category or "Battery" in category:
st.markdown("- Mid-value chain components face both direct tariffs and tariffed raw material costs")
elif "Consumer" in category:
st.markdown("- End-products accumulate tariff costs from multiple components in addition to any tariffs on the finished product")
else:
st.warning(f"Insufficient data available for {category}. Please select another category or time period.")
def display_tariff_simulator(tariff_data, price_data, selected_categories):
"""Display interactive tariff simulator to explore different scenarios"""
st.header("Tariff Scenario Simulator")
st.markdown("""
Use this simulator to explore how changes in tariff rates might affect the prices of different technology products.
Adjust the sliders to create a hypothetical tariff scenario and see the estimated impact on prices.
*Note: This simulation uses historical relationships between tariffs and prices to generate estimates.
Actual outcomes may vary based on market conditions, competitive responses, and other factors.*
""")
# Get the most recent year's data as baseline
latest_year = max(tariff_data['Year'])
baseline_tariffs = tariff_data[tariff_data['Year'] == latest_year]
# If no categories are selected, use all categories
if not selected_categories:
available_categories = sorted(baseline_tariffs['Category'].unique())
else:
available_categories = selected_categories
# Create UI for tariff scenario simulation
st.subheader("Adjust Tariff Rates")
# Create a form for the simulation inputs
with st.form("tariff_simulation"):
# Column for scenario selection
scenario_col1, scenario_col2 = st.columns([1, 2])
with scenario_col1:
# Predefined scenarios
scenario = st.radio(
"Select a scenario:",
["Custom", "No Tariffs", "Moderate Increase", "Trade War"]
)
with scenario_col2:
if scenario == "Custom":
st.write("Adjust the sliders below to create your custom scenario.")
elif scenario == "No Tariffs":
st.write("Simulates removal of all technology tariffs.")
elif scenario == "Moderate Increase":
st.write("Simulates a moderate increase in tariffs (+5-10%).")
elif scenario == "Trade War":
st.write("Simulates significant tariff increases (+15-25%) during a trade dispute.")
# Create sliders for each category
category_sliders = {}
for category in available_categories:
# Get baseline tariff for this category
baseline = baseline_tariffs[baseline_tariffs['Category'] == category]['Tariff_Rate'].mean()
# Set min, max and default values based on the scenario
if scenario == "No Tariffs":
default_value = 0.0
elif scenario == "Moderate Increase":
default_value = baseline + 7.5
elif scenario == "Trade War":
default_value = baseline + 20.0
else: # Custom
default_value = baseline
# Create slider
category_sliders[category] = st.slider(
f"{category} Tariff Rate (%)",
min_value=0.0,
max_value=50.0,
value=default_value,
step=0.5,
help=f"Current rate: {baseline:.2f}%"
)
# Submit button
submitted = st.form_submit_button("Simulate Impact")
# Process simulation when submitted
if submitted:
st.subheader("Simulation Results")
# Create results table
results = []
for category in available_categories:
# Get baseline values
baseline_tariff = baseline_tariffs[baseline_tariffs['Category'] == category]['Tariff_Rate'].mean()
# Get new tariff from slider
new_tariff = category_sliders[category]
# Calculate estimated price impact
tariff_change = new_tariff - baseline_tariff
price_impact = calculate_tariff_impact(tariff_change, category, tariff_data, price_data)
# Add to results
results.append({
'Category': category,
'Baseline_Tariff': baseline_tariff,
'New_Tariff': new_tariff,
'Tariff_Change': tariff_change,
'Estimated_Price_Impact': price_impact
})
# Convert to DataFrame
results_df = pd.DataFrame(results)
# Display results as a chart
fig = {
'data': [
{
'type': 'bar',
'x': results_df['Category'],
'y': results_df['Estimated_Price_Impact'],
'name': 'Estimated Price Impact (%)',
'marker': {
'color': ['#ff6b6b' if x > 0 else '#4ecdc4' for x in results_df['Estimated_Price_Impact']]
}
}
],
'layout': {
'title': 'Estimated Price Impact by Category',
'xaxis': {'title': 'Product Category'},
'yaxis': {'title': 'Estimated Price Change (%)'},
'height': 500
}
}
st.plotly_chart(fig, use_container_width=True)
# Also show the data in a table
st.dataframe(
results_df
.rename(columns={
'Category': 'Category',
'Baseline_Tariff': 'Baseline Tariff (%)',
'New_Tariff': 'New Tariff (%)',
'Tariff_Change': 'Tariff Change (%)',
'Estimated_Price_Impact': 'Est. Price Impact (%)'
})
.set_index('Category')
.style.format({
'Baseline Tariff (%)': '{:.2f}',
'New Tariff (%)': '{:.2f}',
'Tariff Change (%)': '{:.2f}',
'Est. Price Impact (%)': '{:.2f}'
})
.background_gradient(subset=['Est. Price Impact (%)'], cmap='RdYlGn_r')
)
# Add explanatory information
st.subheader("Impact Analysis")
# Calculate the overall average impact
avg_impact = results_df['Estimated_Price_Impact'].mean()
st.markdown(f"""
### Overall Impact
The simulated tariff changes would result in an estimated **{avg_impact:.2f}%** average price change across all selected categories.
### Category-Specific Impacts
- **Most affected category**: {results_df.loc[results_df['Estimated_Price_Impact'].idxmax(), 'Category']}
({results_df['Estimated_Price_Impact'].max():.2f}% price change)
- **Least affected category**: {results_df.loc[results_df['Estimated_Price_Impact'].idxmin(), 'Category']}
({results_df['Estimated_Price_Impact'].min():.2f}% price change)
### Consumer Impact Considerations
- Price changes may not be immediate as companies have inventory at pre-tariff prices
- Some manufacturers may absorb part of the tariff impact rather than passing it all to consumers
- Competitive markets may see smaller price increases as companies try to maintain market share
- Substitute products might see increased demand if they're less affected by tariffs
""")
# Mitigation strategies
with st.expander("Potential Mitigation Strategies"):
st.markdown("""
### For Consumers
- Consider purchasing products before tariff implementation if increases are announced
- Explore alternative products that may be less affected by tariffs
- Look for products manufactured in countries not subject to the tariffs
- Consider refurbished or previous-generation products, which may see smaller price increases
### For Businesses
- Diversify supply chains across multiple countries
- Redesign products to use components from non-tariffed sources
- Apply for tariff exclusions where available
- Consider adjusting product feature sets to maintain price points
- Evaluate shifting assembly or manufacturing to different regions
""")
def display_prediction_models(tariff_data, price_data, selected_categories):
"""Display prediction models for future tariff impacts"""
st.header("Prediction Models: Future Tariff Impacts")
# Introduction
st.markdown("""
This section uses machine learning models to predict how future tariff changes might impact technology prices.
Unlike the simulator which makes immediate projections, these models forecast trends over the next few years.
""")
# Create historical data needed for modeling
historical_data = process_historical_data(tariff_data, price_data)
# Sidebar for model selection and configuration
st.sidebar.markdown("---")
st.sidebar.subheader("Prediction Model Settings")
model_type = st.sidebar.radio(
"Select prediction model:",
["Linear Regression", "Random Forest", "Time Series (ARIMA)"],
index=1 # Default to Random Forest
)
# Main prediction interface
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("Model Configuration")
# Category selection
# Always include all available categories regardless of the sidebar filter
all_available_categories = list(tariff_data['Category'].unique())
category_options = ["All Categories"] + all_available_categories
selected_category = st.selectbox(
"Select category for prediction:",
options=category_options,
index=0
)
# Format category for model input
category_for_model = None if selected_category == "All Categories" else selected_category
# Scenario selection
scenario_type = st.selectbox(
"Select tariff scenario:",
["Baseline", "Moderate Increase (+5%)", "Significant Increase (+10%)", "Moderate Decrease (-5%)", "Custom"]
)
# Custom scenario configuration
if scenario_type == "Custom":
custom_tariff_change = st.slider(
"Define custom tariff change:",
min_value=-25.0,
max_value=50.0,
value=0.0,
step=2.5
)
else:
# Map scenario to tariff change
scenario_mapping = {
"Baseline": {"type": "baseline", "change": 0.0},
"Moderate Increase (+5%)": {"type": "increase", "change": 5.0},
"Significant Increase (+10%)": {"type": "increase", "change": 10.0},
"Moderate Decrease (-5%)": {"type": "decrease", "change": 5.0}
}
selected_scenario = scenario_mapping[scenario_type]
# Prediction horizon
forecast_years = st.slider(
"Years to forecast:",
min_value=1,
max_value=5,
value=3
)
# Run prediction button
run_prediction = st.button("Run Prediction Model")
with col2:
st.subheader("Prediction Results")
if run_prediction:
st.markdown(f"### Future Impact Prediction using {model_type}")
with st.spinner("Training model and generating predictions..."):
# Prepare scenario data
if scenario_type == "Custom":
scenario_data = create_future_scenario(
historical_data,
category=category_for_model,
scenario_type="custom",
tariff_change=custom_tariff_change,
num_years=forecast_years
)
else:
scenario_data = create_future_scenario(
historical_data,
category=category_for_model,
scenario_type=selected_scenario["type"],
tariff_change=selected_scenario["change"],
num_years=forecast_years
)
# Create visualization of prediction
if not scenario_data.empty:
# Get the last year in historical data
last_historical_year = historical_data['Year'].max()
# Filter historical data for the selected category
if category_for_model:
category_hist_data = historical_data[historical_data['Category'] == category_for_model]
else:
# For "All Categories", use aggregated data
category_hist_data = historical_data.groupby('Year').agg({
'Tariff_Rate': 'mean',
'Price_Index': 'mean'
}).reset_index()
# Create figure with two y-axes
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Calculate ranges for better y-axis scaling
tariff_min = min(min(category_hist_data['Tariff_Rate']), min(scenario_data['Tariff_Rate'])) - 1
tariff_max = max(max(category_hist_data['Tariff_Rate']), max(scenario_data['Tariff_Rate'])) + 1
price_min = min(min(category_hist_data['Price_Index']), min(scenario_data['Price_Index'])) - 2
price_max = max(max(category_hist_data['Price_Index']), max(scenario_data['Price_Index'])) + 2
# Add historical tariff rates
fig.add_trace(
go.Scatter(
x=category_hist_data['Year'],
y=category_hist_data['Tariff_Rate'],
name="Historical Tariff Rate",
line=dict(color='red', width=3),
mode='lines+markers'
),
secondary_y=False
)
# Add predicted tariff rates
fig.add_trace(
go.Scatter(
x=scenario_data['Year'],
y=scenario_data['Tariff_Rate'],
name="Predicted Tariff Rate",
line=dict(color='red', dash='dash', width=3),
mode='lines+markers'
),
secondary_y=False
)
# Add historical price index
fig.add_trace(
go.Scatter(
x=category_hist_data['Year'],
y=category_hist_data['Price_Index'],
name="Historical Price Index",
line=dict(color='blue', width=3),
mode='lines+markers'
),
secondary_y=True
)
# Add predicted price index
fig.add_trace(
go.Scatter(
x=scenario_data['Year'],
y=scenario_data['Price_Index'],
name="Predicted Price Index",
line=dict(color='blue', dash='dash', width=3),
mode='lines+markers'
),
secondary_y=True
)
# Add a vertical line to separate historical from predicted
fig.add_vline(
x=last_historical_year,
line_dash="dot",
line_color="gray",
annotation_text="Forecast Start",
annotation_position="top right"
)
# Update layout
fig.update_layout(
title=f"Tariff and Price Predictions ({scenario_type} Scenario)",
xaxis_title="Year",
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="center", x=0.5),
# Add grid for better readability
plot_bgcolor='rgba(240, 240, 240, 0.8)',
paper_bgcolor='rgba(0,0,0,0)',
font=dict(size=12)
)
# Set y-axis titles and ranges for better separation of data
fig.update_yaxes(
title_text="Tariff Rate (%)",
secondary_y=False,
range=[tariff_min, tariff_max],
gridcolor='rgba(255, 255, 255, 0.5)',
zerolinecolor='white'
)
fig.update_yaxes(
title_text="Price Index",
secondary_y=True,
range=[price_min, price_max],
gridcolor='rgba(255, 255, 255, 0.5)',
zerolinecolor='white'
)
# Display the figure
st.plotly_chart(fig, use_container_width=True)
# Display prediction metrics
st.subheader("Prediction Metrics")
# Calculate average predicted values
avg_tariff = scenario_data['Tariff_Rate'].mean()
avg_price = scenario_data['Price_Index'].mean()
# Calculate change from current values
current_tariff = category_hist_data[category_hist_data['Year'] == last_historical_year]['Tariff_Rate'].mean()
current_price = category_hist_data[category_hist_data['Year'] == last_historical_year]['Price_Index'].mean()
tariff_change = avg_tariff - current_tariff
price_change = ((avg_price / current_price) - 1) * 100
# Create metrics display
metric_cols = st.columns(2)
with metric_cols[0]:
st.metric(
"Avg. Predicted Tariff Rate",
f"{avg_tariff:.2f}%",
f"{tariff_change:+.2f}% pts vs. current"
)
with metric_cols[1]:
st.metric(
"Avg. Predicted Price Index",
f"{avg_price:.2f}",
f"{price_change:+.2f}% vs. current"
)
# Model details and accuracy information
with st.expander("Model Details"):
st.markdown(f"""
#### {model_type} Model Information
**Data used:** {'All categories (aggregated)' if category_for_model is None else category_for_model}
**Training period:** {category_hist_data['Year'].min()} to {last_historical_year}
**Forecast period:** {last_historical_year + 1} to {last_historical_year + forecast_years}
**Scenario type:** {scenario_type}
The model was trained on historical relationships between tariff rates and price indices,
and uses this relationship to predict how future tariff changes are likely to affect prices.
""")
# Add model-specific information
if model_type == "Linear Regression":
st.markdown("""
Linear regression models predict price changes based on a direct linear relationship
with tariff rates. These models are simple but capture general trends well.
""")
elif model_type == "Random Forest":
st.markdown("""
Random Forest models can capture more complex non-linear relationships between
tariffs and prices, potentially providing more accurate predictions when the
relationship is not straightforward.
""")
else: # Time Series
st.markdown("""
Time series models (ARIMA) account for temporal patterns in the data, including
seasonality and trends over time, making them useful for forecasting future
values based on historical patterns.
""")
else:
st.error("Unable to generate predictions with the selected parameters. Please try different settings.")
else:
st.info("Configure the model settings and click 'Run Prediction Model' to see forecast results.")
# Show example of what the prediction models do
st.markdown("""
### What the Prediction Models Show
After running a prediction model, you'll see:
1. A graph showing historical data and predicted future tariff rates and prices
2. Key metrics summarizing the predicted changes
3. Details about the model used and its accuracy
This helps you understand potential long-term impacts of tariff policies beyond
the immediate effects shown in the Tariff Simulator.
""")
# Provide information about the different model types
with st.expander("About the Prediction Models"):
st.markdown("""
#### Linear Regression
Simple models that assume a linear relationship between tariff rates and prices.
Good for understanding general trends and directional impact.
#### Random Forest
More sophisticated machine learning models that can capture complex relationships.
Better at handling non-linear effects and interactions between variables.
#### Time Series (ARIMA)
Specialized models that account for time-dependent patterns in the data.
Best for forecasting future values based on historical patterns and seasonality.
Each model type has strengths and limitations. For the most comprehensive
understanding, compare results across different model types.
""")
# Additional scenarios comparison section
st.markdown("---")
st.subheader("Compare Multiple Scenarios")
if st.checkbox("Show scenario comparison"):
with st.spinner("Generating scenario comparison..."):
# Define scenarios to compare
scenarios = [
{'name': 'Baseline', 'type': 'baseline', 'change': 0.0},
{'name': 'Moderate Increase', 'type': 'increase', 'change': 5.0},
{'name': 'Significant Increase', 'type': 'increase', 'change': 10.0},
{'name': 'Moderate Decrease', 'type': 'decrease', 'change': 5.0}
]
# Generate comparison data
comparison_data = compare_tariff_scenarios(historical_data, category_for_model, scenarios)
if not comparison_data.empty:
# Calculate impact compared to baseline
impact_data = calculate_scenario_impact(historical_data, comparison_data, category_for_model)
if not impact_data.empty:
# Display impact table
st.markdown("### Impact of Different Tariff Scenarios")
# Format the impact data for display
display_impact = impact_data.copy()
display_impact.columns = [
"Scenario",