PDFからインタラクティブダッシュボードへのプロンプト
フリーのプロンプト百科事典 Wikiprompt より
PDFからインタラクティブダッシュボードへのプロンプト Plotly Dashを使用して、PDFまたはデータファイルからインタラクティブなダッシュボードを作成するためのPythonスクリプトを生成するプロンプト。チャート、フィルター、動的機能を備えています。
プロンプト内容保存
🌐
# -*- coding: utf-8 -*-
"""
Interactive Financial Dashboard
================================
A modern, data-driven dashboard built with Plotly Dash.
Displays key financial figures evolution with interactive filters,
hover effects, and year-based comparisons.
Compatible with Replit environment.
"""
import dash
from dash import dcc, html, Input, Output, callback
import plotly.graph_objs as go
import plotly.express as px
import pandas as pd
import numpy as np
from datetime import datetime
# ============================================================================
# 1. DATA PREPARATION
# ============================================================================
# Simulated financial data based on typical PDF report structure
# In production, replace with actual PDF parsing (e.g., pdfplumber, PyPDF2)
np.random.seed(42)
years = list(range(2018, 2024))
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
# Generate synthetic financial data
data = []
for year in years:
for quarter in quarters:
revenue = np.random.uniform(80, 150) * (1 + (year - 2018) * 0.15)
expenses = revenue * np.random.uniform(0.55, 0.75)
profit = revenue - expenses
cash_flow = profit * np.random.uniform(0.8, 1.2)
data.append({
'Year': year,
'Quarter': quarter,
'Revenue': round(revenue, 2),
'Expenses': round(expenses, 2),
'Profit': round(profit, 2),
'CashFlow': round(cash_flow, 2),
'Employees': int(np.random.uniform(50, 200) * (1 + (year - 2018) * 0.1)),
'Customers': int(np.random.uniform(1000, 5000) * (1 + (year - 2018) * 0.2))
})
df = pd.DataFrame(data)
# Add period label for better display
df['Period'] = df['Year'].astype(str) + ' ' + df['Quarter']
# Calculate year-over-year metrics for comparison
df['YoY_Revenue'] = df.groupby('Quarter')['Revenue'].pct_change() * 100
df['YoY_Profit'] = df.groupby('Quarter')['Profit'].pct_change() * 100
# ============================================================================
# 2. DASHBOARD INITIALIZATION
# ============================================================================
app = dash.Dash(__name__)
app.title = "Financial Performance Dashboard"
# Modern color palette
COLORS = {
'background': '#f8f9fa',
'text': '#2c3e50',
'primary': '#3498db',
'secondary': '#2ecc71',
'accent': '#e74c3c',
'grid': '#ecf0f1'
}
# ============================================================================
# 3. LAYOUT DEFINITION
# ============================================================================
app.layout = html.Div(
style={
'backgroundColor': COLORS['background'],
'fontFamily': 'Inter, -apple-system, BlinkMacSystemFont, sans-serif',
'padding': '20px',
'minHeight': '100vh'
},
children=[
# Header Section
html.Div(
style={
'textAlign': 'center',
'marginBottom': '30px',
'padding': '20px',
'backgroundColor': 'white',
'borderRadius': '10px',
'boxShadow': '0 2px 10px rgba(0,0,0,0.1)'
},
children=[
html.H1(
"Financial Performance Dashboard",
style={
'color': COLORS['text'],
'fontSize': '2.5rem',
'fontWeight': '700',
'marginBottom': '10px'
}
),
html.P(
"Key Financial Indicators Evolution (2018-2023)",
style={
'color': '#7f8c8d',
'fontSize': '1.1rem'
}
)
]
),
# Filters Section
html.Div(
style={
'backgroundColor': 'white',
'padding': '20px',
'borderRadius': '10px',
'boxShadow': '0 2px 10px rgba(0,0,0,0.1)',
'marginBottom': '20px'
},
children=[
html.Label(
"Select Year Range:",
style={'fontWeight': '600', 'color': COLORS['text']}
),
dcc.RangeSlider(
id='year-slider',
min=min(years),
max=max(years),
value=[min(years), max(years)],
marks={year: str(year) for year in years},
step=1,
tooltip={"placement": "bottom", "always_visible": True}
),
html.Div(
style={'marginTop': '15px'},
children=[
html.Label(
"Select Quarters:",
style={'fontWeight': '600', 'color': COLORS['text']}
),
dcc.Dropdown(
id='quarter-filter',
options=[{'label': q, 'value': q} for q in quarters],
value=quarters,
multi=True,
placeholder="Select quarters to display",
style={'marginTop': '5px'}
)
]
)
]
),
# Charts Container
html.Div(
id='charts-container',
style={'display': 'flex', 'flexDirection': 'column', 'gap': '20px'}
)
]
)
# ============================================================================
# 4. CALLBACKS AND CHART GENERATION
# ============================================================================
@callback(
Output('charts-container', 'children'),
[Input('year-slider', 'value'),
Input('quarter-filter', 'value')]
)
def update_dashboard(year_range, selected_quarters):
"""
Main callback that updates all charts based on selected filters.
"""
# Filter data based on selections
filtered_df = df[
(df['Year'] >= year_range[0]) &
(df['Year'] <= year_range[1]) &
(df['Quarter'].isin(selected_quarters))
].copy()
if filtered_df.empty:
return html.Div("No data available for selected filters",
style={'textAlign': 'center', 'padding': '50px'})
charts = []
# ------------------------------------------------------------------------
# Chart 1: Revenue and Expenses Trend (Line Chart)
# ------------------------------------------------------------------------
fig1 = go.Figure()
fig1.add_trace(go.Scatter(
x=filtered_df['Period'],
y=filtered_df['Revenue'],
name='Revenue',
mode='lines+markers',
line=dict(color=COLORS['primary'], width=3),
marker=dict(size=8),
hovertemplate='<b>%{x}</b><br>Revenue: $%{y:.2f}M<extra></extra>'
))
fig1.add_trace(go.Scatter(
x=filtered_df['Period'],
y=filtered_df['Expenses'],
name='Expenses',
mode='lines+markers',
line=dict(color=COLORS['accent'], width=3),
marker=dict(size=8),
hovertemplate='<b>%{x}</b><br>Expenses: $%{y:.2f}M<extra></extra>'
))
fig1.update_layout(
title="Revenue vs Expenses Evolution",
xaxis_title="Period",
yaxis_title="Amount (Million $)",
template='plotly_white',
hovermode='x unified',
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family="Inter, sans-serif", color=COLORS['text'])
)
charts.append(dcc.Graph(figure=fig1))
# ------------------------------------------------------------------------
# Chart 2: Profit and Cash Flow (Bar Chart with comparison)
# ------------------------------------------------------------------------
fig2 = go.Figure()
fig2.add_trace(go.Bar(
x=filtered_df['Period'],
y=filtered_df['Profit'],
name='Profit',
marker_color=COLORS['secondary'],
hovertemplate='<b>%{x}</b><br>Profit: $%{y:.2f}M<extra></extra>'
))
fig2.add_trace(go.Bar(
x=filtered_df['Period'],
y=filtered_df['CashFlow'],
name='Cash Flow',
marker_color=COLORS['primary'],
hovertemplate='<b>%{x}</b><br>Cash Flow: $%{y:.2f}M<extra></extra>'
))
fig2.update_layout(
title="Profit and Cash Flow Analysis",
xaxis_title="Period",
yaxis_title="Amount (Million $)",
barmode='group',
template='plotly_white',
hovermode='x unified',
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family="Inter, sans-serif", color=COLORS['text'])
)
charts.append(dcc.Graph(figure=fig2))
# ------------------------------------------------------------------------
# Chart 3: Year-over-Year Growth (Line Chart)
# ------------------------------------------------------------------------
yoy_df = filtered_df.dropna(subset=['YoY_Revenue', 'YoY_Profit'])
if not yoy_df.empty:
fig3 = go.Figure()
fig3.add_trace(go.Scatter(
x=yoy_df['Period'],
y=yoy_df['YoY_Revenue'],
name='Revenue Growth %',
mode='lines+markers',
line=dict(color=COLORS['primary'], width=3, dash='solid'),
marker=dict(size=8),
hovertemplate='<b>%{x}</b><br>Revenue Growth: %{y:.1f}%<extra></extra>'
))
fig3.add_trace(go.Scatter(
x=yoy_df['Period'],
y=yoy_df['YoY_Profit'],
name='Profit Growth %',
mode='lines+markers',
line=dict(color=COLORS['accent'], width=3, dash='dash'),
marker=dict(size=8),
hovertemplate='<b>%{x}</b><br>Profit Growth: %{y:.1f}%<extra></extra>'
))
fig3.update_layout(
title="Year-over-Year Growth Rates",
xaxis_title="Period",
yaxis_title="Growth Rate (%)",
template='plotly_white',
hovermode='x unified',
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family="Inter, sans-serif", color=COLORS['text'])
)
charts.append(dcc.Graph(figure=fig3))
# ------------------------------------------------------------------------
# Chart 4: Operational Metrics (Area Chart)
# ------------------------------------------------------------------------
fig4 = go.Figure()
fig4.add_trace(go.Scatter(
x=filtered_df['Period'],
y=filtered_df['Employees'],
name='Employees',
mode='lines',
fill='tozeroy',
line=dict(color=COLORS['primary'], width=2),
hovertemplate='<b>%{x}</b><br>Employees: %{y}<extra></extra>'
))
fig4.add_trace(go.Scatter(
x=filtered_df['Period'],
y=filtered_df['Customers'],
name='Customers',
mode='lines',
fill='tozeroy',
line=dict(color=COLORS['secondary'], width=2),
hovertemplate='<b>%{x}</b><br>Customers: %{y}<extra></extra>'
))
fig4.update_layout(
title="Operational Growth Metrics",
xaxis_title="Period",
yaxis_title="Count",
template='plotly_white',
hovermode='x unified',
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family="Inter, sans-serif", color=COLORS['text'])
)
charts.append(dcc.Graph(figure=fig4))
# ------------------------------------------------------------------------
# Chart 5: Profit Margin Analysis (Pie Chart)
# ------------------------------------------------------------------------
# Aggregate data for pie chart
pie_data = filtered_df.groupby('Year').agg({
'Profit': 'sum',
'Revenue': 'sum'
}).reset_index()
pie_data['Margin'] = (pie_data['Profit'] / pie_data['Revenue']) * 100
fig5 = go.Figure(data=[go.Pie(
labels=pie_data['Year'],
values=pie_data['Margin'],
hole=0.4,
marker=dict(colors=px.colors.qualitative.Set3),
textinfo='label+percent',
hovertemplate='<b>Year %{label}</b><br>Profit Margin: %{value:.1f}%<extra></extra>'
)])
fig5.update_layout(
title="Profit Margin Distribution by Year",
template='plotly_white',
showlegend=True,
legend=dict(orientation="h", yanchor="bottom", y=-0.2),
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family="Inter, sans-serif", color=COLORS['text'])
)
charts.append(dcc.Graph(figure=fig5))
# ------------------------------------------------------------------------
# Chart 6: Quarterly Performance Heatmap
# ------------------------------------------------------------------------
pivot_df = filtered_df.pivot_table(
values='Revenue',
index='Year',
columns='Quarter',
aggfunc='mean'
).fillna(0)
fig6 = go.Figure(data=go.Heatmap(
z=pivot_df.values,
x=pivot_df.columns,
y=pivot_df.index,
colorscale='Viridis',
hovertemplate='<b>%{y} %{x}</b><br>Revenue: $%{z:.2f}M<extra></extra>',
colorbar=dict(title="Revenue (M$)")
))
fig6.update_layout(
title="Revenue Heatmap by Quarter",
xaxis_title="Quarter",
yaxis_title="Year",
template='plotly_white',
plot_bgcolor='white',
paper_bgcolor='white',
font=dict(family="Inter, sans-serif", color=COLORS['text'])
)
charts.append(dcc.Graph(figure=fig6))
return charts
# ============================================================================
# 5. APPLICATION ENTRY POINT
# ============================================================================
if __name__ == '__main__':
# For Replit compatibility
app.run_server(
host='0.0.0.0',
port=8080,
debug=True
)
ログインして完全なプロンプトを表示
次で続行:
ログインすると、次に同意したことになります: 利用規約 と プライバシーポリシー
使い方
このプロンプトは coding 向けに設計されています。上の内容をコピーして、お好みの AI ツールに貼り付けてください。
最良の結果を得るには、プレースホルダー(角括弧や大文字で示された部分)を具体的な要件に置き換えてください。
ノート
0 件のコメント