一、代码结构概览
该代码构建了一个包含经济数据生成、可视化分析和政策模拟的交互式经济系统仿真平台,主要包括三大模块:
-
多部门经济数据生成:模拟包含产业关联的复杂经济数据
-
增强型可视化:提供多维度的经济数据分析视图
-
Dash交互应用:实现政策参数的动态模拟与效果展示
二、数据生成模块 (generate_multi_sector_data
)
1. 基础设置
dates = pd.date_range(start=datetime(2020, 1, 1), periods=years*12, freq='ME')
t = np.arange(len(dates))
-
生成每月末的日期序列(
freq='ME'
) -
创建时间索引数组
t
用于周期函数计算
2. 波动生成函数
def modulated_wave(base_freq, noise=0):
return np.sin(base_freq*t)*(1+0.2*np.sin(0.3*t)) + noise*np.random.randn(len(t))
- 复合波动模型:包含:
-
基础正弦波(
np.sin(base_freq*t)
) -
振幅调制波(
0.2*np.sin(0.3*t)
) -
高斯白噪声(
noise
参数控制强度)
3. 部门经济模型
定义8个产业部门,每个部门采用不同的数学模型体现行业特性:
部门 | 模型特征 | 关键公式组件 |
---|---|---|
农业 | 气候周期性 | signal.square() 方波模拟季节影响 |
采矿业 | 资源衰减 | -0.005*(t**1.5) 模拟资源枯竭 |
制造业 | S型增长 | 1-1/(1+np.exp(...)) 逻辑斯蒂曲线 |
科技服务业 | 指数增长 | np.exp(0.005*t) 指数函数 |
金融地产 | 复合增长 | (1+0.01*t)**2 二次增长 |
4. 产业关联计算
sector_links = np.array([...]) # 8x8矩阵
for _ in range(2): # 两轮交互
for i in range(8):
impact = (df @ sector_links[i])
df.iloc[:,i] += 0.1 * impact.mean()
- 投入产出矩阵:8x8矩阵定义部门间供给关系
- 动态传播:进行两轮关联计算,每个部门接收来自其他部门的加权影响
5. 宏观指标
df['domestic_cycle'] = 0.4*df['manufacturing'] + ... # 国内周期
df['external_cycle'] = 0.6*df['mining'] + ... # 外部周期
-
通过加权组合关键部门数据生成综合指标
三、可视化模块
1. 平行坐标分析
px.parallel_coordinates(
df.resample('Q').mean(), # 季度平均
color='domestic_cycle', # 颜色映射
dimensions=df.columns[:8]
)
- 功能:展示多部门间的关联关系
- 设计:
-
使用发散色系
Tealrose
突出对比 -
季度降采样避免过度波动
2. 雷达图分析
go.Scatterpolar(
r=latest/(base+1e-6), # 相对增长率
theta=df.columns[:8] # 部门角度分布
)
- 功能:可视化部门协同发展程度
- 设计:
-
显示当前值相对于基期的倍数关系
-
灰色基准线标记1倍水平
四、Dash交互应用
1. 界面布局
app.layout = html.Div([
html.H1("仿真平台", style={'textAlign':'center'}),
dcc.Graph(id='parallel-coords'), # 左侧视图
dcc.Graph(id='radar-chart'), # 右侧视图
dcc.Slider(id='manuf-tax', ...), # 政策滑块
html.Div(id='sector-simulation') # 结果展示区
])
- 响应式布局:使用CSS Grid实现双列视图
- 组件设计
-
政策滑块带有百分比刻度
-
阴影和圆角提升视觉层次
2. 政策模拟引擎
@callback(
Output('sector-simulation', 'children'),
[Input('manuf-tax', 'value'), ...]
)
def simulate_simpact(tax_rate, tech_sub, green_inv):
# 动态响应参数计算
tax_effect = 0.8/(1+np.exp(15*(tax_rate-0.25))) # S型曲线
tech_multiplier = 1 + 2.5*tech_sub*(1-0.3*tax_rate)
# 构建8x8影响矩阵
impact_matrix = np.array([...])
# 计算增长率
base_values = economy_df.iloc[-1].values[:8]
impact = base_values @ impact_matrix
growth_rates = (impact - base_values)/base_values
- 核心算法:
-
使用矩阵乘法模拟政策冲击传导
-
各政策参数非线性叠加(如
tech_sub
与tax_rate
的相互作用)
-
可视化反馈:
- 红/绿色区分正负增长
网格布局展示8部门结果
import pandas as pd
import numpy as np
from datetime import datetime
from scipy import signal
import plotly.express as px
import plotly.graph_objects as go
from dash import Dash, html, dcc, Input, Output, callback# ========================
# 多部门经济数据生成(8大产业部门)
# ========================
def generate_multi_sector_data(years=5):"""生成包含复杂产业关联的经济数据"""dates = pd.date_range(start=datetime(2020, 1, 1), periods=years * 12, freq='ME')t = np.arange(len(dates))# 基础波动模型def modulated_wave(base_freq, noise=0):return np.sin(base_freq * t) * (1 + 0.2 * np.sin(0.3 * t)) + noise * np.random.randn(len(t))# 部门定义(8大产业)sectors = {# 农业:受气候和政策影响'agriculture': 50 * (1 + 0.01 * t) + 10 * modulated_wave(2 * np.pi / 24) * (1 + 0.3 * signal.square(2 * np.pi * t / 36)),# 采矿业:资源依赖型'mining': 80 * (1 + 0.008 * t) - 0.005 * (t ** 1.5) + 15 * modulated_wave(2 * np.pi / 36, 0.2),# 制造业:核心生产部门'manufacturing': 100 * (1 + 0.015 * t) * (1 - 1 / (1 + np.exp(0.1 * (t - 30)))) + 20 * modulated_wave(2 * np.pi / 12),# 公用事业:稳定增长'utilities': 60 * (1 + 0.012 * t) + 5 * np.random.randn(len(t)),# 建筑业:周期性波动'construction': 70 * (1 + 0.01 * t) + 25 * modulated_wave(2 * np.pi / 18) + 0.2 * signal.sawtooth(2 * np.pi * t / 60),# 科技服务业:指数增长'tech_services': 40 * np.exp(0.005 * t) * (1 + 0.3 * modulated_wave(2 * np.pi / 24, 0.15)),# 金融地产:复合增长'finance_realestate': 90 * (1 + 0.01 * t) ** 2 + 30 * modulated_wave(2 * np.pi / 24, 0.2),# 消费服务业:需求驱动'consumer_services': 80 * (1 + 0.008 * t) + 20 * modulated_wave(2 * np.pi / 12) * (1 + 0.4 * np.random.beta(2, 5, len(t)))}df = pd.DataFrame(sectors, index=dates)# 部门间关联投入产出关系sector_links = np.array([[0, 0.1, 0.2, 0, 0.05, 0, 0, 0], # 农业[0.05, 0, 0.3, 0.1, 0.15, 0, 0, 0], # 采矿业[0.1, 0.4, 0, 0.2, 0.25, 0.3, 0.1, 0.2], # 制造业[0, 0, 0.1, 0.05, 0, 0.05, 0, 0], # 公用事业[0, 0.1, 0.35, 0.05, 0, 0.1, 0.15, 0.3], # 建筑业[0, 0, 0.2, 0.1, 0.1, 0, 0.3, 0.2], # 科技服务[0, 0, 0.1, 0.05, 0.2, 0.4, 0, 0.5], # 金融地产[0.2, 0, 0.15, 0, 0.1, 0.25, 0.3, 0] # 消费服务])# 动态投入产出计算for _ in range(2): # 两轮交互for i in range(8):impact = (df @ sector_links[i])df.iloc[:, i] += 0.1 * impact.mean()# 宏观指标计算df['domestic_cycle'] = 0.4 * df['manufacturing'] + 0.3 * df['consumer_services'] + 0.3 * df['construction']df['external_cycle'] = 0.6 * df['mining'] + 0.4 * df['tech_services'] - 0.2 * df['finance_realestate']return dfeconomy_df = generate_multi_sector_data()# ========================
# 增强型可视化(多维度分析)
# ========================
def create_parallel_coordinates(df):"""产业关联平行坐标分析"""fig = px.parallel_coordinates(df.resample('Q').mean(),color='domestic_cycle',dimensions=df.columns[:8],color_continuous_scale=px.colors.diverging.Tealrose,title="产业关联度多维分析")fig.update_layout(height=500)return figdef create_radar_chart(df):"""部门协同效应雷达图"""latest = df.iloc[-1].values[:8]base = df.iloc[0].values[:8]fig = go.Figure()fig.add_trace(go.Scatterpolar(r=latest / (base + 1e-6),theta=df.columns[:8],fill='toself',name='当前值',line_color='indigo'))fig.add_trace(go.Scatterpolar(r=np.ones(8),theta=df.columns[:8],name='基准线',line_color='gray'))fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0.5, 2])),showlegend=True,height=450,title="部门发展协同效应雷达图")return fig# ========================
# 增强型Dash应用(多政策模拟)
# ========================
app = Dash(__name__)app.layout = html.Div([html.H1("多部门经济系统动力学仿真平台", style={'textAlign': 'center', 'color': '#2c3e50'}),html.Div([dcc.Graph(id='parallel-coords', figure=create_parallel_coordinates(economy_df)),dcc.Graph(id='radar-chart', figure=create_radar_chart(economy_df))], style={'display': 'grid', 'gridTemplateColumns': '1fr 1fr', 'gap': '20px'}),html.Div([html.Div([html.H3("产业政策模拟器", style={'borderBottom': '2px solid #3498db'}),html.Div([html.Div([html.Label("制造业增值税", style={'color': '#2980b9'}),dcc.Slider(id='manuf-tax', min=0.1, max=0.4, value=0.25, step=0.05,marks={i: f"{int(i * 100)}%" for i in [0.1, 0.2, 0.3, 0.4]}),], style={'flex': 1, 'padding': 10}),html.Div([html.Label("科技研发补贴", style={'color': '#27ae60'}),dcc.Slider(id='tech-subsidy', min=0, max=0.2, value=0.05, step=0.02,marks={i: f"{int(i * 100)}%" for i in [0, 0.05, 0.1, 0.15, 0.2]}),], style={'flex': 1, 'padding': 10}),html.Div([html.Label("绿色转型投资", style={'color': '#2ecc71'}),dcc.Slider(id='green-invest', min=0, max=0.15, value=0.03, step=0.03,marks={i: f"{int(i * 100)}%" for i in [0, 0.03, 0.06, 0.09, 0.12, 0.15]}),], style={'flex': 1, 'padding': 10})], style={'display': 'flex', 'gap': '15px'})], style={'padding': 25,'borderRadius': 10,'boxShadow': '0 2px 15px rgba(0,0,0,0.1)','background': '#f9f9f9','marginBottom': '20px'})], style={'width': '90%', 'margin': 'auto'}),html.Div(id='sector-simulation', style={'padding': 20,'margin': '20px auto','borderRadius': 8,'background': '#f0f4f8','width': '85%'})
])# ========================
# 产业政策模拟引擎
# ========================
@callback(Output('sector-simulation', 'children'),[Input('manuf-tax', 'value'),Input('tech-subsidy', 'value'),Input('green-invest', 'value')]
)
def simulate_simpact(tax_rate, tech_sub, green_inv):"""多政策协同作用模拟"""# 动态响应参数tax_effect = 0.8 / (1 + np.exp(15 * (tax_rate - 0.25))) # S型税收响应tech_multiplier = 1 + 2.5 * tech_sub * (1 - 0.3 * tax_rate)green_synergy = 0.6 * green_inv * (1 + 0.4 * tech_sub)# 部门间传播矩阵impact_matrix = np.array([[1.0, 0.2, 0.5, 0.1, 0.3, 0.4, 0.1, 0.2],[0.3, 1.0, 0.6, 0.2, 0.4, 0.1, 0.3, 0.1],[0.7, 0.8, tax_effect, 0.5, 0.6, tech_multiplier, 0.4, 0.5],[0.1, 0.2, 0.3, 1.0, 0.2, 0.3, 0.1, 0.2],[0.4, 0.3, 0.7, 0.2, 1.0, 0.5, green_synergy, 0.6],[0.5, 0.1, 0.9, 0.3, 0.8, 1.0, 0.7, 0.4],[0.2, 0.4, 0.6, 0.1, 0.5, 0.8, 1.0, 0.3],[0.3, 0.1, 0.4, 0.2, 0.7, 0.6, 0.5, 1.0]])# 计算部门影响base_values = economy_df.iloc[-1].values[:8]impact = base_values @ impact_matrixgrowth_rates = (impact - base_values) / base_values# 生成可视化结果return html.Div([html.H4("政策冲击传导效应预测", style={'color': '#2c3e50'}),html.Div([html.Div([html.P(f"{sector}:", style={'fontWeight': 'bold'}),html.P(f"{100 * growth:.1f}%",style={'color': '#e74c3c' if growth < 0 else '#27ae60'})])for sector, growth in zip(economy_df.columns[:8], growth_rates)], style={'display': 'grid', 'gridTemplateColumns': 'repeat(4, 1fr)', 'gap': '15px'})])if __name__ == '__main__':app.run(debug=True, port=8050)