-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
443 lines (369 loc) · 17.4 KB
/
Copy pathapp.py
File metadata and controls
443 lines (369 loc) · 17.4 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
# streamlit run app.py
#pip install streamlit pandas openai
#pip install scikit-learn
import os
import streamlit as st
import pandas as pd
from collections import defaultdict
# Optional AI (OpenAI)
try:
import openai
OPENAI_AVAILABLE = True
except:
OPENAI_AVAILABLE = False
# -------------------------
# Page settings
# -------------------------
st.set_page_config(page_title="財務シミュレーター", layout="wide")
TITLE = "財務シミュレーター"
# -------------------------
# CSS / styling
# -------------------------
st.markdown("""
<style>
body { background: linear-gradient(135deg, #E8F0FF 0%, #FFFFFF 40%, #F9ECFF 100%); }
.app-title { color: #123A8A; font-size:28px; font-weight:700; margin-bottom:6px; }
.card {
background: linear-gradient(180deg, rgba(255,255,255,0.95), rgba(250,250,250,0.95));
padding: 18px; border-radius:12px;
box-shadow: 0 6px 18px rgba(15,23,42,0.08);
margin-bottom:18px;
}
.section-bar { width:100%; height:6px; background:#3B82F6; border-radius:4px; margin:18px 0 32px 0; }
.bs-table { width:100%; border-collapse: collapse; margin-top:10px; font-size:14px; }
.bs-table th { background:#e8f2ff; color:#0b3a66; padding:8px; border:1px solid #9aa6b2; text-align:left; }
.bs-table td { padding:8px; border:1px solid #c8d2db; }
.bs-total { background:#eef5ff; font-weight:700; }
.bs-section { background:#f3f7fb; font-weight:700; }
.section-title { margin-top:0px; font-size:22px; font-weight:600; color:#123A8A; }
.card {
margin-top:0px !important;
}
input[type=number] { background-color:#ffffff !important; color:#000000 !important; }
.muted { color:#6b7280; font-size:13px; }
</style>
""", unsafe_allow_html=True)
st.markdown("""
<style>
.card:empty {
display: none !important;
visibility: hidden !important;
height: 0 !important;
padding: 0 !important;
margin: 0 !important;
}
</style>
""", unsafe_allow_html=True)
# -------------------------
# Account master
# -------------------------
ACCOUNT_TYPES = {
# 資産
"現金": "資産", "預金": "資産", "売掛金": "資産", "棚卸資産": "資産",
"有形固定資産": "資産", "無形資産": "資産", "前払費用": "資産", "投資有価証券": "資産",
# 負債
"買掛金": "負債", "短期借入金": "負債", "長期借入金": "負債", "未払金": "負債",
"未払費用": "負債", "前受金": "負債",
# 純資産
"資本金": "純資産", "利益剰余金": "純資産", "資本剰余金": "純資産",
# 収益
"売上": "収益", "受取利息": "収益",
# 費用
"仕入": "費用", "給与": "費用", "旅費交通費": "費用", "通信費": "費用", "減価償却費": "費用",
}
# -------------------------
# Helper functions
# -------------------------
def create_initial_balances():
return defaultdict(float)
def apply_journal_entries(balances, journal_entries):
b = balances.copy()
for j in journal_entries:
d = j["借方"]; c = j["貸方"]; amt = j["金額"]
b[d] += amt
b[c] -= amt
return b
def create_balance_sheet(balances):
bs = {"資産": {}, "負債": {}, "純資産": {}}
for acct, val in balances.items():
typ = ACCOUNT_TYPES.get(acct)
if typ in bs:
bs[typ][acct] = val
return bs
def create_profit_loss(balances):
revenue = {}; expenses = {}
for acct, val in balances.items():
typ = ACCOUNT_TYPES.get(acct)
if typ == "収益":
revenue[acct] = abs(val)
elif typ == "費用":
expenses[acct] = abs(val)
profit = sum(revenue.values()) - sum(expenses.values())
return {"収益": revenue, "費用": expenses, "利益": profit}
def bs_totals(bs):
totals = {}
for k, v in bs.items():
totals[k] = sum(v.values()) if isinstance(v, dict) else 0
return totals
def format_yen(x):
return f"{x:,.0f}"
# -------------------------
# UI: Header
# -------------------------
st.markdown(f"<div class='app-title'>{TITLE}</div>", unsafe_allow_html=True)
st.markdown("<div class='muted'>予想される仕訳を入力すると、貸借対照表(B/S)・損益計算書(P/L)が更新されます。AIは仕訳説明・簡易分析に使えます(APIキー任意)。</div>", unsafe_allow_html=True)
# -------------------------
# UI: B/S input
# -------------------------
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.markdown("<div class='section-title'>貸借対照表(B/S)入力</div>", unsafe_allow_html=True)
col_l, col_r = st.columns([1,1])
with col_l:
st.subheader("資産の部(現在・百万円単位)")
cash = st.number_input("現金", value=0, step=1, key="in_cash")
deposit = st.number_input("預金", value=0, step=1, key="in_deposit")
ar = st.number_input("売掛金", value=0, step=1, key="in_ar")
inventory = st.number_input("棚卸資産", value=0, step=1, key="in_inventory")
ppe = st.number_input("有形固定資産",value=0, step=1, key="in_ppe")
intangible = st.number_input("無形資産", value=0, step=1, key="in_intangible")
prepay = st.number_input("前払費用", value=0, step=1, key="in_prepay")
invest = st.number_input("投資有価証券", value=0, step=1, key="in_invest")
with col_r:
st.subheader("負債・純資産の部")
ap = st.number_input("買掛金", value=0, step=1, key="in_ap")
short_loan = st.number_input("短期借入金", value=0, step=1, key="in_shortloan")
long_loan = st.number_input("長期借入金", value=0, step=1, key="in_longloan")
unpaid = st.number_input("未払金", value=0, step=1, key="in_unpaid")
capital = st.number_input("資本金", value=0, step=1, key="in_capital")
retained = st.number_input("利益剰余金", value=0, step=1, key="in_retained")
capital_surplus = st.number_input("資本剰余金", value=0, step=1, key="in_capital_surplus")
st.markdown("</div>", unsafe_allow_html=True)
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.markdown("<div class='section-title'>損益計算書(P/L)入力</div>", unsafe_allow_html=True)
col_l, col_r = st.columns([1, 1])
with st.container():
st.subheader("損益計算書(P/L)(現在・百万円単位)")
col1, col2 = st.columns(2)
with col1:
sales = st.number_input("売上高", value=0, step=1, key="pl_sales")
cogs = st.number_input("売上原価", value=0, step=1, key="pl_cogs")
sga = st.number_input("販管費", value=0, step=1, key="pl_sga")
with col2:
non_op_income = st.number_input("営業外収益", value=0, step=1, key="pl_non_op_income")
non_op_expense = st.number_input("営業外費用", value=0, step=1, key="pl_non_op_expense")
extraordinary_gain = st.number_input("特別利益", value=0, step=1, key="pl_extra_gain")
extraordinary_loss = st.number_input("特別損失", value=0, step=1, key="pl_extra_loss")
gross_profit = sales - cogs
operating_profit = gross_profit - sga
ordinary_profit = operating_profit + non_op_income - non_op_expense
profit_before_tax = ordinary_profit + extraordinary_gain - extraordinary_loss
net_income = profit_before_tax # 今は税金を簡略化
# -------------------------
# UI: Journal Entries
# -------------------------
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.markdown("<div class='section-title'>仕訳(Journal Entries)</div>", unsafe_allow_html=True)
st.markdown("<div class='muted'>借方・貸方・金額を入力して追加。複数行対応。</div>", unsafe_allow_html=True)
if "journal_entries" not in st.session_state:
st.session_state.journal_entries = []
cols = st.columns([2,2,1,1])
with cols[0]:
sel_debit = st.selectbox("借方科目", options=list(ACCOUNT_TYPES.keys()), key="sel_debit")
with cols[1]:
sel_credit = st.selectbox("貸方科目", options=list(ACCOUNT_TYPES.keys()), key="sel_credit")
with cols[2]:
sel_amount = st.number_input("金額", min_value=0, value=0, step=1, key="je_amount")
with cols[3]:
if st.button("追加"):
if sel_amount <= 0:
st.warning("金額は0より大きくしてください。")
else:
st.session_state.journal_entries.append({"借方": sel_debit, "貸方": sel_credit, "金額": float(sel_amount)})
st.success("仕訳を追加しました。")
st.markdown("<div class='muted'>現在の仕訳一覧</div>", unsafe_allow_html=True)
if st.session_state.journal_entries:
st.table(pd.DataFrame(st.session_state.journal_entries))
if st.button("仕訳を全て消す"):
st.session_state.journal_entries = []
else:
st.info("仕訳はまだ追加されていません。")
st.markdown("</div>", unsafe_allow_html=True)
# -------------------------
# Build balances dict
# -------------------------
initial_balances = create_initial_balances()
initial_balances["現金"] = cash
initial_balances["預金"] = deposit
initial_balances["売掛金"] = ar
initial_balances["棚卸資産"] = inventory
initial_balances["有形固定資産"] = ppe
initial_balances["無形資産"] = intangible
initial_balances["前払費用"] = prepay
initial_balances["投資有価証券"] = invest
initial_balances["買掛金"] = ap
initial_balances["短期借入金"] = short_loan
initial_balances["長期借入金"] = long_loan
initial_balances["未払金"] = unpaid
initial_balances["資本金"] = capital
initial_balances["利益剰余金"] = retained
initial_balances["資本剰余金"] = capital_surplus
# -------------------------
# UI: Statements
# -------------------------
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.markdown("<div class='section-title'>B/S、P/Lを予想</div>", unsafe_allow_html=True)
total_debit = sum(j["金額"] for j in st.session_state.journal_entries) if st.session_state.journal_entries else 0.0
st.markdown(f"<div class='muted'>仕訳合計(借方): {format_yen(total_debit)}</div>", unsafe_allow_html=True)
if st.button("予想"):
after_balances = apply_journal_entries(initial_balances, st.session_state.journal_entries)
bs_after = create_balance_sheet(after_balances)
totals = bs_totals(bs_after)
assets_total = totals.get("資産",0)
liabilities_total = totals.get("負債",0)
equity_total = totals.get("純資産",0)
right_total = liabilities_total + equity_total
# 借方・貸方チェック
if assets_total != right_total:
st.warning(f"⚠️ 資産合計 ({format_yen(assets_total)}) と 負債・純資産合計 ({format_yen(right_total)}) が一致していません。")
# --- B/S
st.markdown("<h3>貸借対照表</h3>", unsafe_allow_html=True)
st.markdown("<div style='overflow-x:auto'>", unsafe_allow_html=True)
bs_html = "<table class='bs-table'>"
for section in ["資産","負債","純資産"]:
bs_html += f"<tr><th colspan='2'>{section}の部</th></tr>"
for k,v in bs_after[section].items():
bs_html += f"<tr><td>{k}</td><td style='text-align:right'>{format_yen(v)}</td></tr>"
bs_html += f"<tr class='bs-total'><td>【{section}合計】</td><td style='text-align:right'>{format_yen(totals[section])}</td></tr>"
bs_html += f"<tr class='bs-total' style='background:#dfe8ff'><td>【負債・純資産合計】</td><td style='text-align:right'>{format_yen(right_total)}</td></tr>"
bs_html += "</table>"
st.markdown(bs_html, unsafe_allow_html=True)
st.markdown("</div>", unsafe_allow_html=True)
# --- P/L
st.markdown("<h3>損益計算書(P/L)</h3>", unsafe_allow_html=True)
pl_after = pl_df.copy()
# 仕訳で反映された収益/費用を優先して P/L を組み立てる
sales_val = pl_after["収益"].get("売上", 0)
cogs_val = pl_after["費用"].get("仕入", 0)
sga_val = pl_after["費用"].get("販管費", 0)
non_op_income_val = pl_after["収益"].get("営業外収益", 0)
non_op_expense_val = pl_after["費用"].get("営業外費用", 0)
extra_gain_val = pl_after["収益"].get("特別利益", 0)
extra_loss_val = pl_after["費用"].get("特別損失", 0)
gross_profit = sales_val - cogs_val
operating_profit = gross_profit - sga_val
ordinary_profit = operating_profit + non_op_income_val - non_op_expense_val
profit_before_tax = ordinary_profit + extra_gain_val - extra_loss_val
net_income_val = profit_before_tax # 税考慮は省略
pl_df = pd.DataFrame({
"項目": [
"売上高",
"売上原価",
"売上総利益",
"販管費",
"営業利益",
"営業外収益",
"営業外費用",
"経常利益",
"特別利益",
"特別損失",
"税引前当期純利益",
"当期純利益"
],
"金額": [
sales_val,
cogs_val,
gross_profit,
sga_val,
operating_profit,
non_op_income_val,
non_op_expense_val,
ordinary_profit,
extra_gain_val,
extra_loss_val,
profit_before_tax,
net_income_val
]
})
# 表示を整数にそろえる:ここで必ず pl_df が存在するので安全
pl_df["金額"] = pl_df["金額"].astype(int)
st.table(pl_df)
# -------------------------
# 回帰予測と異常値検知(修正版)
# -------------------------
import numpy as np
import warnings
warnings.filterwarnings("ignore", category=UserWarning)
# sklearn が無ければ親切に教える
try:
from sklearn.ensemble import IsolationForest
SKL_AVAILABLE = True
except Exception:
SKL_AVAILABLE = False
# 1. 履歴 DataFrame 作成
if st.session_state.get("journal_entries"):
df_journal = pd.DataFrame(st.session_state.journal_entries)
# 安全化:列が存在するか、型変換
if "金額" in df_journal.columns:
df_journal["金額"] = pd.to_numeric(df_journal["金額"], errors="coerce").fillna(0.0)
else:
df_journal["金額"] = 0.0
else:
df_journal = pd.DataFrame(columns=["借方", "貸方", "金額"])
# 2. 科目別の集計(借方はプラス、貸方はマイナス)
df_summary = pd.DataFrame(index=list(ACCOUNT_TYPES.keys()))
df_summary["金額"] = 0.0
for _, row in df_journal.iterrows():
d = row.get("借方")
c = row.get("貸方")
amt = float(row.get("金額", 0.0))
if d in df_summary.index:
df_summary.loc[d, "金額"] += amt
if c in df_summary.index:
df_summary.loc[c, "金額"] -= amt
# 3. 回帰予測(簡易:ここでは直近値を使う。時系列が整えば本格回帰へ差し替え)
predictions = {}
for acct in df_summary.index:
# ここでは履歴があまりないため、現状値をそのまま予測値とする
val = df_summary.loc[acct, "金額"]
predictions[acct] = float(val)
# 4. 異常値検知(IsolationForest) — sklearn が無ければスキップして通知
df_summary["異常"] = 0 # デフォルト 0(正常)
if SKL_AVAILABLE and len(df_summary) > 0:
X = df_summary["金額"].values.reshape(-1, 1)
# variance check: 常に同じ値だと IsolationForest は不安定なのでガード
if np.nanstd(X) > 0:
iso = IsolationForest(contamination=0.05, random_state=42)
try:
iso.fit(X)
out = iso.predict(X) # 1: normal, -1: outlier
df_summary["異常"] = out
except Exception:
# 万が一失敗したらすべて正常扱いにする
df_summary["異常"] = 1
else:
# 分散がゼロ(すべて同値)の場合は異常検知しない
df_summary["異常"] = 1
else:
if not SKL_AVAILABLE:
st.info("※ 異常値検知には scikit-learn が必要です(pip install scikit-learn)。現在はスキップしています。")
# 5. 予測 P/L 作成(表示用 DataFrame を必ず作る)
pl_pred_items = ["売上", "受取利息", "仕入", "給与", "旅費交通費", "通信費", "減価償却費"]
pl_pred_values = [ predictions.get(x, 0.0) for x in pl_pred_items ]
pred_pl_df = pd.DataFrame({
"項目": pl_pred_items,
"予測金額": pl_pred_values
})
# 表示形式を整数に揃える(画面上は 0 表示になる)
# 浮動小数の負荷が無ければ int cast、負の値も扱うため int() で丸める
pred_pl_df["予測金額"] = pred_pl_df["予測金額"].apply(lambda x: int(round(x)))
# 6. 結果表示(カード内)
st.markdown("<div class='card'>", unsafe_allow_html=True)
st.markdown("<div class='section-title'>予測 P/L & 異常値</div>", unsafe_allow_html=True)
st.markdown("<div style='margin-bottom:8px;'><strong>予測 P/L(簡易)</strong></div>", unsafe_allow_html=True)
st.table(pred_pl_df)
st.markdown("<div style='margin-top:10px; margin-bottom:6px;'><strong>異常値チェック(1=正常, -1=外れ値)</strong></div>", unsafe_allow_html=True)
# 金額列を整数にして表示(df_summary は index が科目)
display_df = df_summary.reset_index().rename(columns={"index": "科目"})
display_df["金額"] = display_df["金額"].apply(lambda x: int(round(x)))
st.table(display_df[["科目", "金額", "異常"]])
st.markdown("</div>", unsafe_allow_html=True)