Edwin Salguero
commited on
Commit
ยท
94e5687
1
Parent(s):
712bf79
Remove all demo data and update project to use only real FRED API data
Browse files- frontend/app.py +161 -445
- frontend/demo_data.py +0 -288
frontend/app.py
CHANGED
@@ -37,7 +37,6 @@ def get_requests():
|
|
37 |
return requests
|
38 |
|
39 |
# Initialize flags
|
40 |
-
DEMO_MODE = False
|
41 |
ANALYTICS_AVAILABLE = False
|
42 |
FRED_API_AVAILABLE = False
|
43 |
CONFIG_AVAILABLE = False
|
@@ -90,19 +89,6 @@ def load_config():
|
|
90 |
REAL_DATA_MODE = FRED_API_KEY and FRED_API_KEY != 'your-fred-api-key-here'
|
91 |
return False
|
92 |
|
93 |
-
# Lazy load demo data
|
94 |
-
def load_demo_data():
|
95 |
-
"""Load demo data only when needed"""
|
96 |
-
global DEMO_MODE
|
97 |
-
try:
|
98 |
-
from demo_data import get_demo_data
|
99 |
-
DEMO_DATA = get_demo_data()
|
100 |
-
DEMO_MODE = True
|
101 |
-
return DEMO_DATA
|
102 |
-
except ImportError:
|
103 |
-
DEMO_MODE = False
|
104 |
-
return None
|
105 |
-
|
106 |
# Custom CSS for enterprise styling
|
107 |
st.markdown("""
|
108 |
<style>
|
@@ -425,16 +411,14 @@ def main():
|
|
425 |
# Initialize AWS clients
|
426 |
s3_client, lambda_client = init_aws_clients()
|
427 |
config = load_config()
|
428 |
-
|
429 |
-
# Load demo data if needed
|
430 |
-
if not REAL_DATA_MODE:
|
431 |
-
demo_data = load_demo_data()
|
432 |
|
433 |
# Show data mode info
|
434 |
if REAL_DATA_MODE:
|
435 |
st.success("๐ฏ Using real FRED API data for live economic insights.")
|
436 |
else:
|
437 |
-
st.
|
|
|
|
|
438 |
|
439 |
# Sidebar
|
440 |
with st.sidebar:
|
@@ -481,6 +465,7 @@ def show_executive_dashboard(s3_client, config):
|
|
481 |
if REAL_DATA_MODE and FRED_API_AVAILABLE:
|
482 |
# Get real insights from FRED API
|
483 |
try:
|
|
|
484 |
insights = generate_real_insights(FRED_API_KEY)
|
485 |
|
486 |
with col1:
|
@@ -529,97 +514,10 @@ def show_executive_dashboard(s3_client, config):
|
|
529 |
|
530 |
except Exception as e:
|
531 |
st.error(f"Failed to fetch real data: {e}")
|
532 |
-
|
533 |
-
if DEMO_MODE:
|
534 |
-
insights = DEMO_DATA['insights']
|
535 |
-
# ... demo data display
|
536 |
-
else:
|
537 |
-
# Static fallback
|
538 |
-
pass
|
539 |
-
|
540 |
-
elif DEMO_MODE:
|
541 |
-
insights = DEMO_DATA['insights']
|
542 |
-
|
543 |
-
with col1:
|
544 |
-
gdp_insight = insights['GDPC1']
|
545 |
-
st.markdown(f"""
|
546 |
-
<div class="metric-card">
|
547 |
-
<h3>๐ GDP Growth</h3>
|
548 |
-
<h2>{gdp_insight['growth_rate']}</h2>
|
549 |
-
<p>{gdp_insight['current_value']}</p>
|
550 |
-
<small>{gdp_insight['trend']}</small>
|
551 |
-
</div>
|
552 |
-
""", unsafe_allow_html=True)
|
553 |
-
|
554 |
-
with col2:
|
555 |
-
indpro_insight = insights['INDPRO']
|
556 |
-
st.markdown(f"""
|
557 |
-
<div class="metric-card">
|
558 |
-
<h3>๐ญ Industrial Production</h3>
|
559 |
-
<h2>{indpro_insight['growth_rate']}</h2>
|
560 |
-
<p>{indpro_insight['current_value']}</p>
|
561 |
-
<small>{indpro_insight['trend']}</small>
|
562 |
-
</div>
|
563 |
-
""", unsafe_allow_html=True)
|
564 |
-
|
565 |
-
with col3:
|
566 |
-
cpi_insight = insights['CPIAUCSL']
|
567 |
-
st.markdown(f"""
|
568 |
-
<div class="metric-card">
|
569 |
-
<h3>๐ฐ Inflation Rate</h3>
|
570 |
-
<h2>{cpi_insight['growth_rate']}</h2>
|
571 |
-
<p>{cpi_insight['current_value']}</p>
|
572 |
-
<small>{cpi_insight['trend']}</small>
|
573 |
-
</div>
|
574 |
-
""", unsafe_allow_html=True)
|
575 |
-
|
576 |
-
with col4:
|
577 |
-
unrate_insight = insights['UNRATE']
|
578 |
-
st.markdown(f"""
|
579 |
-
<div class="metric-card">
|
580 |
-
<h3>๐ผ Unemployment</h3>
|
581 |
-
<h2>{unrate_insight['current_value']}</h2>
|
582 |
-
<p>{unrate_insight['growth_rate']}</p>
|
583 |
-
<small>{unrate_insight['trend']}</small>
|
584 |
-
</div>
|
585 |
-
""", unsafe_allow_html=True)
|
586 |
else:
|
587 |
-
|
588 |
-
|
589 |
-
st.markdown("""
|
590 |
-
<div class="metric-card">
|
591 |
-
<h3>๐ GDP Growth</h3>
|
592 |
-
<h2>2.1%</h2>
|
593 |
-
<p>Q4 2024</p>
|
594 |
-
</div>
|
595 |
-
""", unsafe_allow_html=True)
|
596 |
-
|
597 |
-
with col2:
|
598 |
-
st.markdown("""
|
599 |
-
<div class="metric-card">
|
600 |
-
<h3>๐ญ Industrial Production</h3>
|
601 |
-
<h2>+0.8%</h2>
|
602 |
-
<p>Monthly Change</p>
|
603 |
-
</div>
|
604 |
-
""", unsafe_allow_html=True)
|
605 |
-
|
606 |
-
with col3:
|
607 |
-
st.markdown("""
|
608 |
-
<div class="metric-card">
|
609 |
-
<h3>๐ฐ Inflation Rate</h3>
|
610 |
-
<h2>3.2%</h2>
|
611 |
-
<p>Annual Rate</p>
|
612 |
-
</div>
|
613 |
-
""", unsafe_allow_html=True)
|
614 |
-
|
615 |
-
with col4:
|
616 |
-
st.markdown("""
|
617 |
-
<div class="metric-card">
|
618 |
-
<h3>๐ผ Unemployment</h3>
|
619 |
-
<h2>3.7%</h2>
|
620 |
-
<p>Current Rate</p>
|
621 |
-
</div>
|
622 |
-
""", unsafe_allow_html=True)
|
623 |
|
624 |
# Recent analysis section
|
625 |
st.markdown("""
|
@@ -699,8 +597,10 @@ def show_advanced_analytics_page(s3_client, config):
|
|
699 |
</div>
|
700 |
""", unsafe_allow_html=True)
|
701 |
|
702 |
-
if
|
703 |
-
st.
|
|
|
|
|
704 |
|
705 |
# Analysis configuration
|
706 |
st.markdown("""
|
@@ -725,6 +625,7 @@ def show_advanced_analytics_page(s3_client, config):
|
|
725 |
)
|
726 |
|
727 |
# Date range
|
|
|
728 |
end_date = datetime.now()
|
729 |
start_date = end_date - timedelta(days=365*5) # 5 years
|
730 |
|
@@ -775,6 +676,9 @@ def show_advanced_analytics_page(s3_client, config):
|
|
775 |
# Run real analysis with FRED API data
|
776 |
with st.spinner(analysis_message):
|
777 |
try:
|
|
|
|
|
|
|
778 |
# Get real economic data
|
779 |
real_data = get_real_economic_data(FRED_API_KEY,
|
780 |
start_date_input.strftime('%Y-%m-%d'),
|
@@ -853,17 +757,10 @@ def show_advanced_analytics_page(s3_client, config):
|
|
853 |
|
854 |
except Exception as e:
|
855 |
st.error(f"โ Real data analysis failed: {e}")
|
856 |
-
st.info("
|
857 |
-
|
858 |
-
# Fallback to demo analysis
|
859 |
-
if DEMO_MODE:
|
860 |
-
run_demo_analysis(analysis_type, selected_indicators)
|
861 |
-
|
862 |
-
elif DEMO_MODE:
|
863 |
-
# Run demo analysis
|
864 |
-
run_demo_analysis(analysis_type, selected_indicators)
|
865 |
else:
|
866 |
-
st.error("
|
|
|
867 |
|
868 |
def generate_analysis_results(analysis_type, real_data, selected_indicators):
|
869 |
"""Generate analysis results based on the selected analysis type"""
|
@@ -993,121 +890,6 @@ def generate_analysis_results(analysis_type, real_data, selected_indicators):
|
|
993 |
|
994 |
return {}
|
995 |
|
996 |
-
def run_demo_analysis(analysis_type, selected_indicators):
|
997 |
-
"""Run demo analysis based on selected type"""
|
998 |
-
with st.spinner(f"Running {analysis_type.lower()} analysis with demo data..."):
|
999 |
-
try:
|
1000 |
-
# Simulate analysis with demo data
|
1001 |
-
import time
|
1002 |
-
time.sleep(2) # Simulate processing time
|
1003 |
-
|
1004 |
-
# Generate demo results based on analysis type
|
1005 |
-
if analysis_type == "Comprehensive":
|
1006 |
-
demo_results = {
|
1007 |
-
'forecasting': {
|
1008 |
-
'GDPC1': {
|
1009 |
-
'backtest': {'mape': 2.1, 'rmse': 0.045},
|
1010 |
-
'forecast': [21847, 22123, 22401, 22682]
|
1011 |
-
},
|
1012 |
-
'INDPRO': {
|
1013 |
-
'backtest': {'mape': 1.8, 'rmse': 0.032},
|
1014 |
-
'forecast': [102.4, 103.1, 103.8, 104.5]
|
1015 |
-
},
|
1016 |
-
'RSAFS': {
|
1017 |
-
'backtest': {'mape': 2.5, 'rmse': 0.078},
|
1018 |
-
'forecast': [579.2, 584.7, 590.3, 595.9]
|
1019 |
-
}
|
1020 |
-
},
|
1021 |
-
'segmentation': {
|
1022 |
-
'time_period_clusters': {'n_clusters': 3},
|
1023 |
-
'series_clusters': {'n_clusters': 4}
|
1024 |
-
},
|
1025 |
-
'statistical_modeling': {
|
1026 |
-
'correlation': {
|
1027 |
-
'significant_correlations': [
|
1028 |
-
'GDPC1-INDPRO: 0.85',
|
1029 |
-
'GDPC1-RSAFS: 0.78',
|
1030 |
-
'CPIAUCSL-FEDFUNDS: 0.65'
|
1031 |
-
]
|
1032 |
-
}
|
1033 |
-
},
|
1034 |
-
'insights': {
|
1035 |
-
'key_findings': [
|
1036 |
-
'Strong correlation between GDP and Industrial Production (0.85)',
|
1037 |
-
'Inflation showing signs of moderation',
|
1038 |
-
'Federal Reserve policy rate at 22-year high',
|
1039 |
-
'Labor market remains tight with low unemployment',
|
1040 |
-
'Consumer spending resilient despite inflation'
|
1041 |
-
]
|
1042 |
-
}
|
1043 |
-
}
|
1044 |
-
elif analysis_type == "Forecasting Only":
|
1045 |
-
demo_results = {
|
1046 |
-
'forecasting': {
|
1047 |
-
'GDPC1': {
|
1048 |
-
'backtest': {'mape': 2.1, 'rmse': 0.045},
|
1049 |
-
'forecast': [21847, 22123, 22401, 22682]
|
1050 |
-
},
|
1051 |
-
'INDPRO': {
|
1052 |
-
'backtest': {'mape': 1.8, 'rmse': 0.032},
|
1053 |
-
'forecast': [102.4, 103.1, 103.8, 104.5]
|
1054 |
-
}
|
1055 |
-
},
|
1056 |
-
'insights': {
|
1057 |
-
'key_findings': [
|
1058 |
-
'Forecasting analysis completed successfully',
|
1059 |
-
'Time series models applied to selected indicators',
|
1060 |
-
'Forecast accuracy metrics calculated',
|
1061 |
-
'Confidence intervals generated'
|
1062 |
-
]
|
1063 |
-
}
|
1064 |
-
}
|
1065 |
-
elif analysis_type == "Segmentation Only":
|
1066 |
-
demo_results = {
|
1067 |
-
'segmentation': {
|
1068 |
-
'time_period_clusters': {'n_clusters': 3},
|
1069 |
-
'series_clusters': {'n_clusters': 4}
|
1070 |
-
},
|
1071 |
-
'insights': {
|
1072 |
-
'key_findings': [
|
1073 |
-
'Segmentation analysis completed successfully',
|
1074 |
-
'Economic regimes identified',
|
1075 |
-
'Series clustering performed',
|
1076 |
-
'Pattern recognition applied'
|
1077 |
-
]
|
1078 |
-
}
|
1079 |
-
}
|
1080 |
-
elif analysis_type == "Statistical Only":
|
1081 |
-
demo_results = {
|
1082 |
-
'statistical_modeling': {
|
1083 |
-
'correlation': {
|
1084 |
-
'significant_correlations': [
|
1085 |
-
'GDPC1-INDPRO: 0.85',
|
1086 |
-
'GDPC1-RSAFS: 0.78',
|
1087 |
-
'CPIAUCSL-FEDFUNDS: 0.65'
|
1088 |
-
]
|
1089 |
-
}
|
1090 |
-
},
|
1091 |
-
'insights': {
|
1092 |
-
'key_findings': [
|
1093 |
-
'Statistical analysis completed successfully',
|
1094 |
-
'Correlation analysis performed',
|
1095 |
-
'Significance testing completed',
|
1096 |
-
'Statistical models validated'
|
1097 |
-
]
|
1098 |
-
}
|
1099 |
-
}
|
1100 |
-
else:
|
1101 |
-
demo_results = {}
|
1102 |
-
|
1103 |
-
st.success(f"โ
Demo {analysis_type.lower()} analysis completed successfully!")
|
1104 |
-
|
1105 |
-
# Display results
|
1106 |
-
display_analysis_results(demo_results)
|
1107 |
-
|
1108 |
-
except Exception as e:
|
1109 |
-
st.error(f"โ Demo analysis failed: {e}")
|
1110 |
-
|
1111 |
def display_analysis_results(results):
|
1112 |
"""Display comprehensive analysis results with download options"""
|
1113 |
st.markdown("""
|
@@ -1179,6 +961,7 @@ def display_analysis_results(results):
|
|
1179 |
# Generate downloadable reports
|
1180 |
import json
|
1181 |
import io
|
|
|
1182 |
|
1183 |
# Create JSON report
|
1184 |
report_data = {
|
@@ -1374,81 +1157,33 @@ def show_reports_page(s3_client, config):
|
|
1374 |
|
1375 |
# Check if AWS clients are available and test bucket access
|
1376 |
if s3_client is None:
|
1377 |
-
st.
|
1378 |
-
st.info("
|
1379 |
-
|
1380 |
else:
|
1381 |
# Test if we can actually access the S3 bucket
|
1382 |
try:
|
1383 |
s3_client.head_bucket(Bucket=config['s3_bucket'])
|
1384 |
st.success(f"โ
Connected to S3 bucket: {config['s3_bucket']}")
|
1385 |
-
show_demo_reports = False
|
1386 |
except Exception as e:
|
1387 |
-
st.
|
1388 |
-
st.info("
|
1389 |
-
|
1390 |
-
|
1391 |
-
#
|
1392 |
-
|
1393 |
-
|
1394 |
-
|
1395 |
-
|
1396 |
-
'date': '2024-12-15',
|
1397 |
-
'summary': 'Comprehensive analysis of economic indicators and forecasts',
|
1398 |
-
'insights': [
|
1399 |
-
'GDP growth expected to moderate to 2.1% in Q4',
|
1400 |
-
'Inflation continuing to moderate from peak levels',
|
1401 |
-
'Federal Reserve likely to maintain current policy stance',
|
1402 |
-
'Labor market remains tight with strong job creation',
|
1403 |
-
'Consumer spending resilient despite inflation pressures'
|
1404 |
-
]
|
1405 |
-
},
|
1406 |
-
{
|
1407 |
-
'title': 'Monetary Policy Analysis',
|
1408 |
-
'date': '2024-12-10',
|
1409 |
-
'summary': 'Analysis of Federal Reserve policy and market implications',
|
1410 |
-
'insights': [
|
1411 |
-
'Federal Funds Rate at 22-year high of 5.25%',
|
1412 |
-
'Yield curve inversion persists, signaling economic uncertainty',
|
1413 |
-
'Inflation expectations well-anchored around 2%',
|
1414 |
-
'Financial conditions tightening as intended',
|
1415 |
-
'Policy normalization expected to begin in 2025'
|
1416 |
-
]
|
1417 |
-
},
|
1418 |
-
{
|
1419 |
-
'title': 'Labor Market Trends',
|
1420 |
-
'date': '2024-12-05',
|
1421 |
-
'summary': 'Analysis of employment and wage trends',
|
1422 |
-
'insights': [
|
1423 |
-
'Unemployment rate at 3.7%, near historic lows',
|
1424 |
-
'Nonfarm payrolls growing at steady pace',
|
1425 |
-
'Wage growth moderating but still above pre-pandemic levels',
|
1426 |
-
'Labor force participation improving gradually',
|
1427 |
-
'Skills mismatch remains a challenge in certain sectors'
|
1428 |
-
]
|
1429 |
-
}
|
1430 |
-
]
|
1431 |
|
1432 |
-
for
|
1433 |
-
with st.expander(f"
|
1434 |
-
|
1435 |
-
|
1436 |
-
|
1437 |
-
st.markdown(f"โข {insight}")
|
1438 |
else:
|
1439 |
-
|
1440 |
-
|
1441 |
-
|
1442 |
-
if reports:
|
1443 |
-
st.subheader("Available Reports")
|
1444 |
-
|
1445 |
-
for report in reports[:5]: # Show last 5 reports
|
1446 |
-
with st.expander(f"Report: {report['key']} - {report['last_modified'].strftime('%Y-%m-%d %H:%M')}"):
|
1447 |
-
report_data = get_report_data(s3_client, config['s3_bucket'], report['key'])
|
1448 |
-
if report_data:
|
1449 |
-
st.json(report_data)
|
1450 |
-
else:
|
1451 |
-
st.info("No reports available. Run an analysis to generate reports.")
|
1452 |
|
1453 |
def show_downloads_page(s3_client, config):
|
1454 |
"""Show comprehensive downloads page with reports and visualizations"""
|
@@ -1459,6 +1194,11 @@ def show_downloads_page(s3_client, config):
|
|
1459 |
</div>
|
1460 |
""", unsafe_allow_html=True)
|
1461 |
|
|
|
|
|
|
|
|
|
|
|
1462 |
# Create tabs for different download types
|
1463 |
tab1, tab2, tab3, tab4 = st.tabs(["๐ Visualizations", "๐ Reports", "๐ Analysis Data", "๐ฆ Bulk Downloads"])
|
1464 |
|
@@ -1566,155 +1306,115 @@ def show_downloads_page(s3_client, config):
|
|
1566 |
st.subheader("๐ Analysis Reports")
|
1567 |
st.info("Download comprehensive analysis reports in various formats")
|
1568 |
|
1569 |
-
|
1570 |
-
|
1571 |
-
|
1572 |
-
|
1573 |
-
|
1574 |
-
# Sample analysis report
|
1575 |
-
sample_report = {
|
1576 |
-
'analysis_timestamp': datetime.now().isoformat(),
|
1577 |
-
'summary': {
|
1578 |
-
'gdp_growth': '2.1%',
|
1579 |
-
'inflation_rate': '3.2%',
|
1580 |
-
'unemployment_rate': '3.7%',
|
1581 |
-
'industrial_production': '+0.8%'
|
1582 |
-
},
|
1583 |
-
'key_findings': [
|
1584 |
-
'GDP growth remains steady at 2.1%',
|
1585 |
-
'Inflation continues to moderate from peak levels',
|
1586 |
-
'Labor market remains tight with strong job creation',
|
1587 |
-
'Industrial production shows positive momentum'
|
1588 |
-
],
|
1589 |
-
'risk_factors': [
|
1590 |
-
'Geopolitical tensions affecting supply chains',
|
1591 |
-
'Federal Reserve policy uncertainty',
|
1592 |
-
'Consumer spending patterns changing'
|
1593 |
-
],
|
1594 |
-
'opportunities': [
|
1595 |
-
'Strong domestic manufacturing growth',
|
1596 |
-
'Technology sector expansion',
|
1597 |
-
'Green energy transition investments'
|
1598 |
-
]
|
1599 |
-
}
|
1600 |
-
|
1601 |
-
col1, col2, col3 = st.columns(3)
|
1602 |
-
|
1603 |
-
with col1:
|
1604 |
-
# JSON Report
|
1605 |
-
json_report = json.dumps(sample_report, indent=2)
|
1606 |
-
st.download_button(
|
1607 |
-
label="๐ Download JSON Report",
|
1608 |
-
data=json_report,
|
1609 |
-
file_name=f"economic_analysis_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json",
|
1610 |
-
mime="application/json"
|
1611 |
-
)
|
1612 |
-
st.write("Comprehensive analysis data in JSON format")
|
1613 |
|
1614 |
-
|
1615 |
-
|
1616 |
-
csv_data = io.StringIO()
|
1617 |
-
csv_data.write("Metric,Value\n")
|
1618 |
-
csv_data.write(f"GDP Growth,{sample_report['summary']['gdp_growth']}\n")
|
1619 |
-
csv_data.write(f"Inflation Rate,{sample_report['summary']['inflation_rate']}\n")
|
1620 |
-
csv_data.write(f"Unemployment Rate,{sample_report['summary']['unemployment_rate']}\n")
|
1621 |
-
csv_data.write(f"Industrial Production,{sample_report['summary']['industrial_production']}\n")
|
1622 |
-
|
1623 |
-
st.download_button(
|
1624 |
-
label="๐ Download CSV Summary",
|
1625 |
-
data=csv_data.getvalue(),
|
1626 |
-
file_name=f"economic_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
1627 |
-
mime="text/csv"
|
1628 |
-
)
|
1629 |
-
st.write("Key metrics in spreadsheet format")
|
1630 |
|
1631 |
-
|
1632 |
-
|
1633 |
-
text_report = f"""
|
1634 |
-
ECONOMIC ANALYSIS REPORT
|
1635 |
-
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
1636 |
-
|
1637 |
-
SUMMARY METRICS:
|
1638 |
-
- GDP Growth: {sample_report['summary']['gdp_growth']}
|
1639 |
-
- Inflation Rate: {sample_report['summary']['inflation_rate']}
|
1640 |
-
- Unemployment Rate: {sample_report['summary']['unemployment_rate']}
|
1641 |
-
- Industrial Production: {sample_report['summary']['industrial_production']}
|
1642 |
-
|
1643 |
-
KEY FINDINGS:
|
1644 |
-
{chr(10).join([f"โข {finding}" for finding in sample_report['key_findings']])}
|
1645 |
-
|
1646 |
-
RISK FACTORS:
|
1647 |
-
{chr(10).join([f"โข {risk}" for risk in sample_report['risk_factors']])}
|
1648 |
-
|
1649 |
-
OPPORTUNITIES:
|
1650 |
-
{chr(10).join([f"โข {opp}" for opp in sample_report['opportunities']])}
|
1651 |
-
"""
|
1652 |
|
1653 |
-
|
1654 |
-
|
1655 |
-
|
1656 |
-
|
1657 |
-
|
1658 |
-
|
1659 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1660 |
|
1661 |
with tab3:
|
1662 |
st.subheader("๐ Analysis Data")
|
1663 |
st.info("Download raw data and analysis results for further processing")
|
1664 |
|
1665 |
-
|
|
|
|
|
|
|
|
|
1666 |
import pandas as pd
|
1667 |
import numpy as np
|
|
|
1668 |
|
1669 |
-
|
1670 |
-
|
1671 |
-
|
1672 |
-
|
1673 |
-
|
1674 |
-
|
1675 |
-
'Industrial_Production': np.random.normal(50, 3, 100)
|
1676 |
-
}, index=dates)
|
1677 |
-
|
1678 |
-
col1, col2 = st.columns(2)
|
1679 |
-
|
1680 |
-
with col1:
|
1681 |
-
# CSV Data
|
1682 |
-
csv_data = economic_data.to_csv()
|
1683 |
-
st.download_button(
|
1684 |
-
label="๐ Download CSV Data",
|
1685 |
-
data=csv_data,
|
1686 |
-
file_name=f"economic_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
1687 |
-
mime="text/csv"
|
1688 |
-
)
|
1689 |
-
st.write("Raw economic time series data")
|
1690 |
-
|
1691 |
-
with col2:
|
1692 |
-
# Excel Data
|
1693 |
-
excel_buffer = io.BytesIO()
|
1694 |
-
with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
|
1695 |
-
economic_data.to_excel(writer, sheet_name='Economic_Data')
|
1696 |
-
# Add summary sheet
|
1697 |
-
summary_df = pd.DataFrame({
|
1698 |
-
'Metric': ['Mean', 'Std', 'Min', 'Max'],
|
1699 |
-
'GDP': [economic_data['GDP'].mean(), economic_data['GDP'].std(), economic_data['GDP'].min(), economic_data['GDP'].max()],
|
1700 |
-
'Inflation': [economic_data['Inflation'].mean(), economic_data['Inflation'].std(), economic_data['Inflation'].min(), economic_data['Inflation'].max()],
|
1701 |
-
'Unemployment': [economic_data['Unemployment'].mean(), economic_data['Unemployment'].std(), economic_data['Unemployment'].min(), economic_data['Unemployment'].max()]
|
1702 |
-
})
|
1703 |
-
summary_df.to_excel(writer, sheet_name='Summary', index=False)
|
1704 |
|
1705 |
-
|
1706 |
-
|
1707 |
-
|
1708 |
-
|
1709 |
-
|
1710 |
-
|
1711 |
-
|
1712 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1713 |
|
1714 |
with tab4:
|
1715 |
st.subheader("๐ฆ Bulk Downloads")
|
1716 |
st.info("Download all available files in one package")
|
1717 |
|
|
|
|
|
|
|
|
|
1718 |
# Create a zip file with all available data
|
1719 |
import zipfile
|
1720 |
import tempfile
|
@@ -1723,15 +1423,31 @@ OPPORTUNITIES:
|
|
1723 |
zip_buffer = io.BytesIO()
|
1724 |
|
1725 |
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
1726 |
-
# Add
|
1727 |
-
|
1728 |
-
|
1729 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1730 |
|
1731 |
-
# Add
|
1732 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1733 |
|
1734 |
-
# Add
|
1735 |
try:
|
1736 |
charts = chart_gen.list_available_charts()
|
1737 |
for i, chart in enumerate(charts[:5]): # Add first 5 charts
|
@@ -1786,8 +1502,8 @@ def show_configuration_page(config):
|
|
1786 |
st.success("โ
FRED API Key Configured")
|
1787 |
st.info("๐ฏ Real economic data is being used for analysis.")
|
1788 |
else:
|
1789 |
-
st.
|
1790 |
-
st.info("๐
|
1791 |
|
1792 |
# Setup instructions
|
1793 |
with st.expander("๐ง How to Set Up FRED API"):
|
@@ -1828,7 +1544,7 @@ def show_configuration_page(config):
|
|
1828 |
st.write(f"API Endpoint: {config['api_endpoint']}")
|
1829 |
st.write(f"Analytics Available: {ANALYTICS_AVAILABLE}")
|
1830 |
st.write(f"Real Data Mode: {REAL_DATA_MODE}")
|
1831 |
-
st.write(f"
|
1832 |
|
1833 |
# Data Source Information
|
1834 |
st.subheader("Data Sources")
|
|
|
37 |
return requests
|
38 |
|
39 |
# Initialize flags
|
|
|
40 |
ANALYTICS_AVAILABLE = False
|
41 |
FRED_API_AVAILABLE = False
|
42 |
CONFIG_AVAILABLE = False
|
|
|
89 |
REAL_DATA_MODE = FRED_API_KEY and FRED_API_KEY != 'your-fred-api-key-here'
|
90 |
return False
|
91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
# Custom CSS for enterprise styling
|
93 |
st.markdown("""
|
94 |
<style>
|
|
|
411 |
# Initialize AWS clients
|
412 |
s3_client, lambda_client = init_aws_clients()
|
413 |
config = load_config()
|
|
|
|
|
|
|
|
|
414 |
|
415 |
# Show data mode info
|
416 |
if REAL_DATA_MODE:
|
417 |
st.success("๐ฏ Using real FRED API data for live economic insights.")
|
418 |
else:
|
419 |
+
st.error("โ FRED API key not configured. Please set FRED_API_KEY environment variable.")
|
420 |
+
st.info("Get a free FRED API key at: https://fred.stlouisfed.org/docs/api/api_key.html")
|
421 |
+
return
|
422 |
|
423 |
# Sidebar
|
424 |
with st.sidebar:
|
|
|
465 |
if REAL_DATA_MODE and FRED_API_AVAILABLE:
|
466 |
# Get real insights from FRED API
|
467 |
try:
|
468 |
+
load_fred_client()
|
469 |
insights = generate_real_insights(FRED_API_KEY)
|
470 |
|
471 |
with col1:
|
|
|
514 |
|
515 |
except Exception as e:
|
516 |
st.error(f"Failed to fetch real data: {e}")
|
517 |
+
st.info("Please check your FRED API key configuration.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
518 |
else:
|
519 |
+
st.error("โ FRED API not available. Please configure your FRED API key.")
|
520 |
+
st.info("Get a free FRED API key at: https://fred.stlouisfed.org/docs/api/api_key.html")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
521 |
|
522 |
# Recent analysis section
|
523 |
st.markdown("""
|
|
|
597 |
</div>
|
598 |
""", unsafe_allow_html=True)
|
599 |
|
600 |
+
if not REAL_DATA_MODE:
|
601 |
+
st.error("โ FRED API key not configured. Please set FRED_API_KEY environment variable.")
|
602 |
+
st.info("Get a free FRED API key at: https://fred.stlouisfed.org/docs/api/api_key.html")
|
603 |
+
return
|
604 |
|
605 |
# Analysis configuration
|
606 |
st.markdown("""
|
|
|
625 |
)
|
626 |
|
627 |
# Date range
|
628 |
+
from datetime import datetime, timedelta
|
629 |
end_date = datetime.now()
|
630 |
start_date = end_date - timedelta(days=365*5) # 5 years
|
631 |
|
|
|
676 |
# Run real analysis with FRED API data
|
677 |
with st.spinner(analysis_message):
|
678 |
try:
|
679 |
+
# Load FRED client
|
680 |
+
load_fred_client()
|
681 |
+
|
682 |
# Get real economic data
|
683 |
real_data = get_real_economic_data(FRED_API_KEY,
|
684 |
start_date_input.strftime('%Y-%m-%d'),
|
|
|
757 |
|
758 |
except Exception as e:
|
759 |
st.error(f"โ Real data analysis failed: {e}")
|
760 |
+
st.info("Please check your FRED API key and try again.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
761 |
else:
|
762 |
+
st.error("โ FRED API not available. Please configure your FRED API key.")
|
763 |
+
st.info("Get a free FRED API key at: https://fred.stlouisfed.org/docs/api/api_key.html")
|
764 |
|
765 |
def generate_analysis_results(analysis_type, real_data, selected_indicators):
|
766 |
"""Generate analysis results based on the selected analysis type"""
|
|
|
890 |
|
891 |
return {}
|
892 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
893 |
def display_analysis_results(results):
|
894 |
"""Display comprehensive analysis results with download options"""
|
895 |
st.markdown("""
|
|
|
961 |
# Generate downloadable reports
|
962 |
import json
|
963 |
import io
|
964 |
+
from datetime import datetime
|
965 |
|
966 |
# Create JSON report
|
967 |
report_data = {
|
|
|
1157 |
|
1158 |
# Check if AWS clients are available and test bucket access
|
1159 |
if s3_client is None:
|
1160 |
+
st.error("โ AWS S3 not configured. Please configure AWS credentials to access reports.")
|
1161 |
+
st.info("Reports are stored in AWS S3. Configure your AWS credentials to access them.")
|
1162 |
+
return
|
1163 |
else:
|
1164 |
# Test if we can actually access the S3 bucket
|
1165 |
try:
|
1166 |
s3_client.head_bucket(Bucket=config['s3_bucket'])
|
1167 |
st.success(f"โ
Connected to S3 bucket: {config['s3_bucket']}")
|
|
|
1168 |
except Exception as e:
|
1169 |
+
st.error(f"โ Cannot access S3 bucket '{config['s3_bucket']}': {str(e)}")
|
1170 |
+
st.info("Please check your AWS credentials and bucket configuration.")
|
1171 |
+
return
|
1172 |
+
|
1173 |
+
# Try to get real reports from S3
|
1174 |
+
reports = get_available_reports(s3_client, config['s3_bucket'])
|
1175 |
+
|
1176 |
+
if reports:
|
1177 |
+
st.subheader("Available Reports")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1178 |
|
1179 |
+
for report in reports[:10]: # Show last 10 reports
|
1180 |
+
with st.expander(f"Report: {report['key']} - {report['last_modified'].strftime('%Y-%m-%d %H:%M')}"):
|
1181 |
+
report_data = get_report_data(s3_client, config['s3_bucket'], report['key'])
|
1182 |
+
if report_data:
|
1183 |
+
st.json(report_data)
|
|
|
1184 |
else:
|
1185 |
+
st.info("No reports available. Run an analysis to generate reports.")
|
1186 |
+
st.info("Reports will be automatically generated when you run advanced analytics.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1187 |
|
1188 |
def show_downloads_page(s3_client, config):
|
1189 |
"""Show comprehensive downloads page with reports and visualizations"""
|
|
|
1194 |
</div>
|
1195 |
""", unsafe_allow_html=True)
|
1196 |
|
1197 |
+
if not REAL_DATA_MODE:
|
1198 |
+
st.error("โ FRED API key not configured. Please set FRED_API_KEY environment variable.")
|
1199 |
+
st.info("Get a free FRED API key at: https://fred.stlouisfed.org/docs/api/api_key.html")
|
1200 |
+
return
|
1201 |
+
|
1202 |
# Create tabs for different download types
|
1203 |
tab1, tab2, tab3, tab4 = st.tabs(["๐ Visualizations", "๐ Reports", "๐ Analysis Data", "๐ฆ Bulk Downloads"])
|
1204 |
|
|
|
1306 |
st.subheader("๐ Analysis Reports")
|
1307 |
st.info("Download comprehensive analysis reports in various formats")
|
1308 |
|
1309 |
+
if s3_client is None:
|
1310 |
+
st.error("โ AWS S3 not configured. Reports are stored in AWS S3.")
|
1311 |
+
st.info("Configure your AWS credentials to access reports.")
|
1312 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1313 |
|
1314 |
+
# Try to get real reports from S3
|
1315 |
+
reports = get_available_reports(s3_client, config['s3_bucket'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1316 |
|
1317 |
+
if reports:
|
1318 |
+
st.success(f"โ
Found {len(reports)} reports available for download")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1319 |
|
1320 |
+
for i, report in enumerate(reports[:10]): # Show last 10 reports
|
1321 |
+
col1, col2 = st.columns([3, 1])
|
1322 |
+
|
1323 |
+
with col1:
|
1324 |
+
st.write(f"**{report['key']}**")
|
1325 |
+
st.write(f"Size: {report['size']:,} bytes | Modified: {report['last_modified'].strftime('%Y-%m-%d %H:%M')}")
|
1326 |
+
|
1327 |
+
with col2:
|
1328 |
+
try:
|
1329 |
+
report_data = get_report_data(s3_client, config['s3_bucket'], report['key'])
|
1330 |
+
if report_data:
|
1331 |
+
import json
|
1332 |
+
json_data = json.dumps(report_data, indent=2)
|
1333 |
+
st.download_button(
|
1334 |
+
label="๐ฅ Download",
|
1335 |
+
data=json_data,
|
1336 |
+
file_name=f"{report['key']}.json",
|
1337 |
+
mime="application/json",
|
1338 |
+
key=f"report_{i}"
|
1339 |
+
)
|
1340 |
+
except Exception as e:
|
1341 |
+
st.error("โ Download failed")
|
1342 |
+
else:
|
1343 |
+
st.info("No reports available. Run an analysis to generate reports.")
|
1344 |
|
1345 |
with tab3:
|
1346 |
st.subheader("๐ Analysis Data")
|
1347 |
st.info("Download raw data and analysis results for further processing")
|
1348 |
|
1349 |
+
if not REAL_DATA_MODE:
|
1350 |
+
st.error("โ No real data available. Please configure your FRED API key.")
|
1351 |
+
return
|
1352 |
+
|
1353 |
+
# Generate real economic data files
|
1354 |
import pandas as pd
|
1355 |
import numpy as np
|
1356 |
+
from datetime import datetime, timedelta
|
1357 |
|
1358 |
+
try:
|
1359 |
+
# Load FRED client and get real data
|
1360 |
+
load_fred_client()
|
1361 |
+
real_data = get_real_economic_data(FRED_API_KEY,
|
1362 |
+
(datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d'),
|
1363 |
+
datetime.now().strftime('%Y-%m-%d'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1364 |
|
1365 |
+
# Convert to DataFrame
|
1366 |
+
if real_data and 'data' in real_data:
|
1367 |
+
economic_data = pd.DataFrame(real_data['data'])
|
1368 |
+
|
1369 |
+
col1, col2 = st.columns(2)
|
1370 |
+
|
1371 |
+
with col1:
|
1372 |
+
# CSV Data
|
1373 |
+
csv_data = economic_data.to_csv()
|
1374 |
+
st.download_button(
|
1375 |
+
label="๐ Download CSV Data",
|
1376 |
+
data=csv_data,
|
1377 |
+
file_name=f"fred_economic_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
|
1378 |
+
mime="text/csv"
|
1379 |
+
)
|
1380 |
+
st.write("Raw FRED economic time series data")
|
1381 |
+
|
1382 |
+
with col2:
|
1383 |
+
# Excel Data
|
1384 |
+
excel_buffer = io.BytesIO()
|
1385 |
+
with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
|
1386 |
+
economic_data.to_excel(writer, sheet_name='Economic_Data')
|
1387 |
+
# Add summary sheet
|
1388 |
+
summary_df = pd.DataFrame({
|
1389 |
+
'Metric': ['Mean', 'Std', 'Min', 'Max'],
|
1390 |
+
'Value': [economic_data.mean().mean(), economic_data.std().mean(), economic_data.min().min(), economic_data.max().max()]
|
1391 |
+
})
|
1392 |
+
summary_df.to_excel(writer, sheet_name='Summary', index=False)
|
1393 |
+
|
1394 |
+
excel_buffer.seek(0)
|
1395 |
+
st.download_button(
|
1396 |
+
label="๐ Download Excel Data",
|
1397 |
+
data=excel_buffer.getvalue(),
|
1398 |
+
file_name=f"fred_economic_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx",
|
1399 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
1400 |
+
)
|
1401 |
+
st.write("Multi-sheet Excel workbook with FRED data and summary")
|
1402 |
+
else:
|
1403 |
+
st.error("โ Could not retrieve real economic data.")
|
1404 |
+
st.info("Please check your FRED API key and try again.")
|
1405 |
+
|
1406 |
+
except Exception as e:
|
1407 |
+
st.error(f"โ Failed to generate data files: {e}")
|
1408 |
+
st.info("Please check your FRED API key and try again.")
|
1409 |
|
1410 |
with tab4:
|
1411 |
st.subheader("๐ฆ Bulk Downloads")
|
1412 |
st.info("Download all available files in one package")
|
1413 |
|
1414 |
+
if not REAL_DATA_MODE:
|
1415 |
+
st.error("โ No real data available for bulk download.")
|
1416 |
+
return
|
1417 |
+
|
1418 |
# Create a zip file with all available data
|
1419 |
import zipfile
|
1420 |
import tempfile
|
|
|
1423 |
zip_buffer = io.BytesIO()
|
1424 |
|
1425 |
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
1426 |
+
# Add real reports if available
|
1427 |
+
if s3_client:
|
1428 |
+
reports = get_available_reports(s3_client, config['s3_bucket'])
|
1429 |
+
for i, report in enumerate(reports[:5]): # Add first 5 reports
|
1430 |
+
try:
|
1431 |
+
report_data = get_report_data(s3_client, config['s3_bucket'], report['key'])
|
1432 |
+
if report_data:
|
1433 |
+
import json
|
1434 |
+
zip_file.writestr(f'reports/{report["key"]}.json', json.dumps(report_data, indent=2))
|
1435 |
+
except Exception:
|
1436 |
+
continue
|
1437 |
|
1438 |
+
# Add real data if available
|
1439 |
+
try:
|
1440 |
+
load_fred_client()
|
1441 |
+
real_data = get_real_economic_data(FRED_API_KEY,
|
1442 |
+
(datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d'),
|
1443 |
+
datetime.now().strftime('%Y-%m-%d'))
|
1444 |
+
if real_data and 'data' in real_data:
|
1445 |
+
economic_data = pd.DataFrame(real_data['data'])
|
1446 |
+
zip_file.writestr('data/fred_economic_data.csv', economic_data.to_csv())
|
1447 |
+
except Exception:
|
1448 |
+
pass
|
1449 |
|
1450 |
+
# Add visualizations if available
|
1451 |
try:
|
1452 |
charts = chart_gen.list_available_charts()
|
1453 |
for i, chart in enumerate(charts[:5]): # Add first 5 charts
|
|
|
1502 |
st.success("โ
FRED API Key Configured")
|
1503 |
st.info("๐ฏ Real economic data is being used for analysis.")
|
1504 |
else:
|
1505 |
+
st.error("โ FRED API Key Not Configured")
|
1506 |
+
st.info("๐ Please configure your FRED API key to access real economic data.")
|
1507 |
|
1508 |
# Setup instructions
|
1509 |
with st.expander("๐ง How to Set Up FRED API"):
|
|
|
1544 |
st.write(f"API Endpoint: {config['api_endpoint']}")
|
1545 |
st.write(f"Analytics Available: {ANALYTICS_AVAILABLE}")
|
1546 |
st.write(f"Real Data Mode: {REAL_DATA_MODE}")
|
1547 |
+
st.write(f"FRED API Available: {FRED_API_AVAILABLE}")
|
1548 |
|
1549 |
# Data Source Information
|
1550 |
st.subheader("Data Sources")
|
frontend/demo_data.py
DELETED
@@ -1,288 +0,0 @@
|
|
1 |
-
"""
|
2 |
-
FRED ML - Demo Data Generator
|
3 |
-
Provides realistic economic data and senior data scientist insights
|
4 |
-
"""
|
5 |
-
|
6 |
-
import pandas as pd
|
7 |
-
import numpy as np
|
8 |
-
from datetime import datetime, timedelta
|
9 |
-
import random
|
10 |
-
|
11 |
-
def generate_economic_data():
|
12 |
-
"""Generate realistic economic data for demonstration"""
|
13 |
-
|
14 |
-
# Generate date range (last 5 years)
|
15 |
-
end_date = datetime.now()
|
16 |
-
start_date = end_date - timedelta(days=365*5)
|
17 |
-
dates = pd.date_range(start=start_date, end=end_date, freq='ME')
|
18 |
-
|
19 |
-
# Base values and trends for realistic economic data
|
20 |
-
base_values = {
|
21 |
-
'GDPC1': 20000, # Real GDP in billions
|
22 |
-
'INDPRO': 100, # Industrial Production Index
|
23 |
-
'RSAFS': 500, # Retail Sales in billions
|
24 |
-
'CPIAUCSL': 250, # Consumer Price Index
|
25 |
-
'FEDFUNDS': 2.5, # Federal Funds Rate
|
26 |
-
'DGS10': 3.0, # 10-Year Treasury Rate
|
27 |
-
'UNRATE': 4.0, # Unemployment Rate
|
28 |
-
'PAYEMS': 150000, # Total Nonfarm Payrolls (thousands)
|
29 |
-
'PCE': 18000, # Personal Consumption Expenditures
|
30 |
-
'M2SL': 21000, # M2 Money Stock
|
31 |
-
'TCU': 75, # Capacity Utilization
|
32 |
-
'DEXUSEU': 1.1 # US/Euro Exchange Rate
|
33 |
-
}
|
34 |
-
|
35 |
-
# Growth rates and volatility for realistic trends
|
36 |
-
growth_rates = {
|
37 |
-
'GDPC1': 0.02, # 2% annual growth
|
38 |
-
'INDPRO': 0.015, # 1.5% annual growth
|
39 |
-
'RSAFS': 0.03, # 3% annual growth
|
40 |
-
'CPIAUCSL': 0.025, # 2.5% annual inflation
|
41 |
-
'FEDFUNDS': 0.0, # Policy rate
|
42 |
-
'DGS10': 0.0, # Market rate
|
43 |
-
'UNRATE': 0.0, # Unemployment
|
44 |
-
'PAYEMS': 0.015, # Employment growth
|
45 |
-
'PCE': 0.025, # Consumption growth
|
46 |
-
'M2SL': 0.04, # Money supply growth
|
47 |
-
'TCU': 0.005, # Capacity utilization
|
48 |
-
'DEXUSEU': 0.0 # Exchange rate
|
49 |
-
}
|
50 |
-
|
51 |
-
# Generate realistic data
|
52 |
-
data = {'Date': dates}
|
53 |
-
|
54 |
-
for indicator, base_value in base_values.items():
|
55 |
-
# Create trend with realistic economic cycles
|
56 |
-
trend = np.linspace(0, len(dates) * growth_rates[indicator], len(dates))
|
57 |
-
|
58 |
-
# Add business cycle effects
|
59 |
-
cycle = 0.05 * np.sin(2 * np.pi * np.arange(len(dates)) / 48) # 4-year cycle
|
60 |
-
|
61 |
-
# Add random noise
|
62 |
-
noise = np.random.normal(0, 0.02, len(dates))
|
63 |
-
|
64 |
-
# Combine components
|
65 |
-
values = base_value * (1 + trend + cycle + noise)
|
66 |
-
|
67 |
-
# Ensure realistic bounds
|
68 |
-
if indicator in ['UNRATE', 'FEDFUNDS', 'DGS10']:
|
69 |
-
values = np.clip(values, 0, 20)
|
70 |
-
elif indicator in ['CPIAUCSL']:
|
71 |
-
values = np.clip(values, 200, 350)
|
72 |
-
elif indicator in ['TCU']:
|
73 |
-
values = np.clip(values, 60, 90)
|
74 |
-
|
75 |
-
data[indicator] = values
|
76 |
-
|
77 |
-
return pd.DataFrame(data)
|
78 |
-
|
79 |
-
def generate_insights():
|
80 |
-
"""Generate senior data scientist insights"""
|
81 |
-
|
82 |
-
insights = {
|
83 |
-
'GDPC1': {
|
84 |
-
'current_value': '$21,847.2B',
|
85 |
-
'growth_rate': '+2.1%',
|
86 |
-
'trend': 'Moderate growth',
|
87 |
-
'forecast': '+2.3% next quarter',
|
88 |
-
'key_insight': 'GDP growth remains resilient despite monetary tightening, supported by strong consumer spending and business investment.',
|
89 |
-
'risk_factors': ['Inflation persistence', 'Geopolitical tensions', 'Supply chain disruptions'],
|
90 |
-
'opportunities': ['Technology sector expansion', 'Infrastructure investment', 'Green energy transition']
|
91 |
-
},
|
92 |
-
'INDPRO': {
|
93 |
-
'current_value': '102.4',
|
94 |
-
'growth_rate': '+0.8%',
|
95 |
-
'trend': 'Recovery phase',
|
96 |
-
'forecast': '+0.6% next month',
|
97 |
-
'key_insight': 'Industrial production shows signs of recovery, with manufacturing leading the rebound. Capacity utilization improving.',
|
98 |
-
'risk_factors': ['Supply chain bottlenecks', 'Labor shortages', 'Energy price volatility'],
|
99 |
-
'opportunities': ['Advanced manufacturing', 'Automation adoption', 'Reshoring initiatives']
|
100 |
-
},
|
101 |
-
'RSAFS': {
|
102 |
-
'current_value': '$579.2B',
|
103 |
-
'growth_rate': '+3.2%',
|
104 |
-
'trend': 'Strong consumer spending',
|
105 |
-
'forecast': '+2.8% next month',
|
106 |
-
'key_insight': 'Retail sales demonstrate robust consumer confidence, with e-commerce continuing to gain market share.',
|
107 |
-
'risk_factors': ['Inflation impact on purchasing power', 'Interest rate sensitivity', 'Supply chain issues'],
|
108 |
-
'opportunities': ['Digital transformation', 'Omnichannel retail', 'Personalization']
|
109 |
-
},
|
110 |
-
'CPIAUCSL': {
|
111 |
-
'current_value': '312.3',
|
112 |
-
'growth_rate': '+3.2%',
|
113 |
-
'trend': 'Moderating inflation',
|
114 |
-
'forecast': '+2.9% next month',
|
115 |
-
'key_insight': 'Inflation continues to moderate from peak levels, with core CPI showing signs of stabilization.',
|
116 |
-
'risk_factors': ['Energy price volatility', 'Wage pressure', 'Supply chain costs'],
|
117 |
-
'opportunities': ['Productivity improvements', 'Technology adoption', 'Supply chain optimization']
|
118 |
-
},
|
119 |
-
'FEDFUNDS': {
|
120 |
-
'current_value': '5.25%',
|
121 |
-
'growth_rate': '0%',
|
122 |
-
'trend': 'Stable policy rate',
|
123 |
-
'forecast': '5.25% next meeting',
|
124 |
-
'key_insight': 'Federal Reserve maintains restrictive stance to combat inflation, with policy rate at 22-year high.',
|
125 |
-
'risk_factors': ['Inflation persistence', 'Economic slowdown', 'Financial stability'],
|
126 |
-
'opportunities': ['Policy normalization', 'Inflation targeting', 'Financial regulation']
|
127 |
-
},
|
128 |
-
'DGS10': {
|
129 |
-
'current_value': '4.12%',
|
130 |
-
'growth_rate': '-0.15%',
|
131 |
-
'trend': 'Declining yields',
|
132 |
-
'forecast': '4.05% next week',
|
133 |
-
'key_insight': '10-year Treasury yields declining on economic uncertainty and flight to quality. Yield curve inversion persists.',
|
134 |
-
'risk_factors': ['Economic recession', 'Inflation expectations', 'Geopolitical risks'],
|
135 |
-
'opportunities': ['Bond market opportunities', 'Portfolio diversification', 'Interest rate hedging']
|
136 |
-
},
|
137 |
-
'UNRATE': {
|
138 |
-
'current_value': '3.7%',
|
139 |
-
'growth_rate': '0%',
|
140 |
-
'trend': 'Stable employment',
|
141 |
-
'forecast': '3.6% next month',
|
142 |
-
'key_insight': 'Unemployment rate remains near historic lows, indicating tight labor market conditions.',
|
143 |
-
'risk_factors': ['Labor force participation', 'Skills mismatch', 'Economic slowdown'],
|
144 |
-
'opportunities': ['Workforce development', 'Technology training', 'Remote work adoption']
|
145 |
-
},
|
146 |
-
'PAYEMS': {
|
147 |
-
'current_value': '156,847K',
|
148 |
-
'growth_rate': '+1.2%',
|
149 |
-
'trend': 'Steady job growth',
|
150 |
-
'forecast': '+0.8% next month',
|
151 |
-
'key_insight': 'Nonfarm payrolls continue steady growth, with healthcare and technology sectors leading job creation.',
|
152 |
-
'risk_factors': ['Labor shortages', 'Wage pressure', 'Economic uncertainty'],
|
153 |
-
'opportunities': ['Skills development', 'Industry partnerships', 'Immigration policy']
|
154 |
-
},
|
155 |
-
'PCE': {
|
156 |
-
'current_value': '$19,847B',
|
157 |
-
'growth_rate': '+2.8%',
|
158 |
-
'trend': 'Strong consumption',
|
159 |
-
'forecast': '+2.5% next quarter',
|
160 |
-
'key_insight': 'Personal consumption expenditures show resilience, supported by strong labor market and wage growth.',
|
161 |
-
'risk_factors': ['Inflation impact', 'Interest rate sensitivity', 'Consumer confidence'],
|
162 |
-
'opportunities': ['Digital commerce', 'Experience economy', 'Sustainable consumption']
|
163 |
-
},
|
164 |
-
'M2SL': {
|
165 |
-
'current_value': '$20,847B',
|
166 |
-
'growth_rate': '+2.1%',
|
167 |
-
'trend': 'Moderate growth',
|
168 |
-
'forecast': '+1.8% next month',
|
169 |
-
'key_insight': 'Money supply growth moderating as Federal Reserve tightens monetary policy to combat inflation.',
|
170 |
-
'risk_factors': ['Inflation expectations', 'Financial stability', 'Economic growth'],
|
171 |
-
'opportunities': ['Digital payments', 'Financial innovation', 'Monetary policy']
|
172 |
-
},
|
173 |
-
'TCU': {
|
174 |
-
'current_value': '78.4%',
|
175 |
-
'growth_rate': '+0.3%',
|
176 |
-
'trend': 'Improving utilization',
|
177 |
-
'forecast': '78.7% next quarter',
|
178 |
-
'key_insight': 'Capacity utilization improving as supply chain issues resolve and demand remains strong.',
|
179 |
-
'risk_factors': ['Supply chain disruptions', 'Labor shortages', 'Energy constraints'],
|
180 |
-
'opportunities': ['Efficiency improvements', 'Technology adoption', 'Process optimization']
|
181 |
-
},
|
182 |
-
'DEXUSEU': {
|
183 |
-
'current_value': '1.087',
|
184 |
-
'growth_rate': '+0.2%',
|
185 |
-
'trend': 'Stable exchange rate',
|
186 |
-
'forecast': '1.085 next week',
|
187 |
-
'key_insight': 'US dollar remains strong against euro, supported by relative economic performance and interest rate differentials.',
|
188 |
-
'risk_factors': ['Economic divergence', 'Geopolitical tensions', 'Trade policies'],
|
189 |
-
'opportunities': ['Currency hedging', 'International trade', 'Investment diversification']
|
190 |
-
}
|
191 |
-
}
|
192 |
-
|
193 |
-
return insights
|
194 |
-
|
195 |
-
def generate_forecast_data():
|
196 |
-
"""Generate forecast data with confidence intervals"""
|
197 |
-
|
198 |
-
# Generate future dates (next 4 quarters)
|
199 |
-
last_date = datetime.now()
|
200 |
-
future_dates = pd.date_range(start=last_date + timedelta(days=90), periods=4, freq='QE')
|
201 |
-
|
202 |
-
forecasts = {}
|
203 |
-
|
204 |
-
# Realistic forecast scenarios
|
205 |
-
forecast_scenarios = {
|
206 |
-
'GDPC1': {'growth': 0.02, 'volatility': 0.01}, # 2% quarterly growth
|
207 |
-
'INDPRO': {'growth': 0.015, 'volatility': 0.008}, # 1.5% monthly growth
|
208 |
-
'RSAFS': {'growth': 0.025, 'volatility': 0.012}, # 2.5% monthly growth
|
209 |
-
'CPIAUCSL': {'growth': 0.006, 'volatility': 0.003}, # 0.6% monthly inflation
|
210 |
-
'FEDFUNDS': {'growth': 0.0, 'volatility': 0.25}, # Stable policy rate
|
211 |
-
'DGS10': {'growth': -0.001, 'volatility': 0.15}, # Slight decline
|
212 |
-
'UNRATE': {'growth': -0.001, 'volatility': 0.1}, # Slight decline
|
213 |
-
'PAYEMS': {'growth': 0.008, 'volatility': 0.005}, # 0.8% monthly growth
|
214 |
-
'PCE': {'growth': 0.02, 'volatility': 0.01}, # 2% quarterly growth
|
215 |
-
'M2SL': {'growth': 0.015, 'volatility': 0.008}, # 1.5% monthly growth
|
216 |
-
'TCU': {'growth': 0.003, 'volatility': 0.002}, # 0.3% quarterly growth
|
217 |
-
'DEXUSEU': {'growth': -0.001, 'volatility': 0.02} # Slight decline
|
218 |
-
}
|
219 |
-
|
220 |
-
for indicator, scenario in forecast_scenarios.items():
|
221 |
-
base_value = 100 # Normalized base value
|
222 |
-
|
223 |
-
# Generate forecast values
|
224 |
-
forecast_values = []
|
225 |
-
confidence_intervals = []
|
226 |
-
|
227 |
-
for i in range(4):
|
228 |
-
# Add trend and noise
|
229 |
-
value = base_value * (1 + scenario['growth'] * (i + 1) +
|
230 |
-
np.random.normal(0, scenario['volatility']))
|
231 |
-
|
232 |
-
# Generate confidence interval
|
233 |
-
lower = value * (1 - 0.05 - np.random.uniform(0, 0.03))
|
234 |
-
upper = value * (1 + 0.05 + np.random.uniform(0, 0.03))
|
235 |
-
|
236 |
-
forecast_values.append(value)
|
237 |
-
confidence_intervals.append({'lower': lower, 'upper': upper})
|
238 |
-
|
239 |
-
forecasts[indicator] = {
|
240 |
-
'forecast': forecast_values,
|
241 |
-
'confidence_intervals': pd.DataFrame(confidence_intervals),
|
242 |
-
'dates': future_dates
|
243 |
-
}
|
244 |
-
|
245 |
-
return forecasts
|
246 |
-
|
247 |
-
def generate_correlation_matrix():
|
248 |
-
"""Generate realistic correlation matrix"""
|
249 |
-
|
250 |
-
# Define realistic correlations between economic indicators
|
251 |
-
correlations = {
|
252 |
-
'GDPC1': {'INDPRO': 0.85, 'RSAFS': 0.78, 'CPIAUCSL': 0.45, 'FEDFUNDS': -0.32, 'DGS10': -0.28},
|
253 |
-
'INDPRO': {'RSAFS': 0.72, 'CPIAUCSL': 0.38, 'FEDFUNDS': -0.25, 'DGS10': -0.22},
|
254 |
-
'RSAFS': {'CPIAUCSL': 0.42, 'FEDFUNDS': -0.28, 'DGS10': -0.25},
|
255 |
-
'CPIAUCSL': {'FEDFUNDS': 0.65, 'DGS10': 0.58},
|
256 |
-
'FEDFUNDS': {'DGS10': 0.82}
|
257 |
-
}
|
258 |
-
|
259 |
-
# Create correlation matrix
|
260 |
-
indicators = ['GDPC1', 'INDPRO', 'RSAFS', 'CPIAUCSL', 'FEDFUNDS', 'DGS10', 'UNRATE', 'PAYEMS', 'PCE', 'M2SL', 'TCU', 'DEXUSEU']
|
261 |
-
corr_matrix = pd.DataFrame(index=indicators, columns=indicators)
|
262 |
-
|
263 |
-
# Fill diagonal with 1
|
264 |
-
for indicator in indicators:
|
265 |
-
corr_matrix.loc[indicator, indicator] = 1.0
|
266 |
-
|
267 |
-
# Fill with realistic correlations
|
268 |
-
for i, indicator1 in enumerate(indicators):
|
269 |
-
for j, indicator2 in enumerate(indicators):
|
270 |
-
if i != j:
|
271 |
-
if indicator1 in correlations and indicator2 in correlations[indicator1]:
|
272 |
-
corr_matrix.loc[indicator1, indicator2] = correlations[indicator1][indicator2]
|
273 |
-
elif indicator2 in correlations and indicator1 in correlations[indicator2]:
|
274 |
-
corr_matrix.loc[indicator1, indicator2] = correlations[indicator2][indicator1]
|
275 |
-
else:
|
276 |
-
# Generate random correlation between -0.3 and 0.3
|
277 |
-
corr_matrix.loc[indicator1, indicator2] = np.random.uniform(-0.3, 0.3)
|
278 |
-
|
279 |
-
return corr_matrix
|
280 |
-
|
281 |
-
def get_demo_data():
|
282 |
-
"""Get comprehensive demo data"""
|
283 |
-
return {
|
284 |
-
'economic_data': generate_economic_data(),
|
285 |
-
'insights': generate_insights(),
|
286 |
-
'forecasts': generate_forecast_data(),
|
287 |
-
'correlation_matrix': generate_correlation_matrix()
|
288 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|