【PYTHON】法人数予測2
こんばんは!法人数予測をより固く!拡張性を持って行います。
元データは他のデータにかえまして、ちゃんと手動でデータを集めてきました。(AIはハレーションしがちなので、みなさん気をつけて!)
データの読み取り
import pandas as pd
import numpy as np
import yfinance as yf
import plotly.graph_objects as go
import itertools
from plotly.subplots import make_subplots
import warnings
warnings.filterwarnings("ignore")
from statsmodels.tsa.arima.model import ARIMA
from sklearn.linear_model import Ridge
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.preprocessing import StandardScaler
# --- 1. 元データの読み込み(年次データのまま処理!) ---
file_path = 'data/20260322macrodata_formatted_all.xlsx'
df_macro_user = pd.read_excel(file_path, sheet_name='全国マクロ_実数・成長率')
if 'year' in df_macro_user.columns:
df_macro_user = df_macro_user.rename(columns={'year': 'Year'})
else:
df_macro_user = df_macro_user.reset_index().rename(columns={'index': 'Year', 'year': 'Year'})
cols_to_keep = [c for c in df_macro_user.columns if '(前年比%)' not in c]
df_macro_user = df_macro_user[cols_to_keep]
df_macro_user = df_macro_user[df_macro_user['Year'] <= 2023]
if '法人数' in df_macro_user.columns:
df_macro_user = df_macro_user.drop(columns=['法人数'])
# 企業統計データの結合
df_corp = pd.read_excel('data/corporate_statistics_historical_series.xlsx')
df_corp['Year'] = df_corp['年月'].str.extract(r'(\d+)').astype(int)
# --- 💡月次補間は完全廃止!ここからすべて「年次」で動きます ---
df_yearly_merged = pd.merge(df_macro_user, df_corp[['Year', '法人企業数', '新設法人件数', '倒産件数', '休廃業・解散件数']], on='Year', how='inner')
df_yearly_merged = df_yearly_merged.apply(pd.to_numeric, errors='coerce')
df_yearly_merged = df_yearly_merged.interpolate(method='linear', limit_direction='both')
# さらに年次のYahoo Financeデータを追加(※平均値を使います)
symbols = {'USD_JPY': 'JPY=X', 'Nikkei225': '^N225', 'Crude_Oil': 'CL=F'}
print("Yahoo Financeから年次データを取得中...")
for name, symbol in symbols.items():
try:
data = yf.download(symbol, start=f"{df_yearly_merged['Year'].min()}-01-01", end="2024-01-01", interval="1mo", progress=False)
close = data[('Close', symbol)] if isinstance(data.columns, pd.MultiIndex) else data['Close'].iloc[:, 0] if len(data.shape)>1 else data['Close']
# 1年の「平均値」にまるめる
yearly_avg = close.resample('YE').mean()
yearly_avg.index = yearly_avg.index.year
df_yearly_merged[name] = df_yearly_merged['Year'].map(yearly_avg).ffill().bfill()
except Exception as e:
print(f"Failed {name}: {e}")
df_yearly_merged = df_yearly_merged.bfill().ffill()
print(f"✅ 年次データ完成(行数: {len(df_yearly_merged)}件、変数: {len(df_yearly_merged.columns)}個)")
# -------------------------------------------------------------
# 実体マクロ指標と「1年前のデータ(ラグ)」の生成(特徴量をあえて増やす)
# -------------------------------------------------------------
# 予測に使うベース変数
base_features = [c for c in df_yearly_merged.columns if c not in ['Year', '法人企業数', '新設法人件数', '倒産件数', '休廃業・解散件数', 'Date']]
# 1年前(昨年の実績)が今年の企業動態にどう影響するか(遅行指標)を探るため、ラグ変数を生成
for col in base_features:
df_yearly_merged[f'{col}_lag1'] = df_yearly_merged[col].shift(1)
# ラグ作成により欠損が発生する1年目(2008年)を除外してクリーンにする
df_clean = df_yearly_merged.dropna()
all_features = [c for c in df_clean.columns if c not in ['Year', '法人企業数', '新設法人件数', '倒産件数', '休廃業・解散件数', 'Date']]
print(f"✅ 特徴量を {len(all_features)}個(今年の実績+1年前の実績)に拡張し、AI選定の準備が完了しました")
ARIMAモデルの自動最適化
flow_targets = ['新設法人件数', '倒産件数', '休廃業・解散件数']
# 探索するパラメーターの候補 (p: 0~2, d: 0~1, q: 0~2, trend: None / 't'(トレンドあり))
p_vals = [0, 1, 2]
d_vals = [0, 1]
q_vals = [0, 1, 2]
t_vals = ['n', 't'] # 'n'=トレンドなし, 't'=直線トレンドあり
best_arima_models = {}
import sys
# 不要なStatsmodelsの警告を出力させない
import warnings
from statsmodels.tools.sm_exceptions import ConvergenceWarning
warnings.simplefilter('ignore', ConvergenceWarning)
print("--- ARIMA モデルの総当り最適化 (Grid Search) ---")
for target in flow_targets:
y_train = df_yearly_merged[target].values.astype(float)
best_aic = np.inf
best_order = None
best_trend = None
best_model_fit = None
# 総当りでループ (全36パターン)
for p, d, q, t in itertools.product(p_vals, d_vals, q_vals, t_vals):
try:
model = ARIMA(y_train, order=(p,d,q), trend=t)
results = model.fit()
# AICが低い(予測の誤差が少なく、かつ複雑すぎない)モデルを「最高」とする
if results.aic < best_aic:
best_aic = results.aic
best_order = (p, d, q)
best_trend = t
best_model_fit = results
except:
continue
best_arima_models[target] = best_model_fit
trend_str = "直線トレンドあり" if best_trend == 't' else "トレンドなし(収束)"
print(f"🎯 【{target}】の最適モデル決定: ARIMA{best_order} (推移: {trend_str}) - スコア(AIC): {best_aic:.1f}")
# ARIMAだけでの予測グラフを確認(テスト)
years_future = list(range(2024, 2031))
fig_arima = make_subplots(rows=1, cols=3, subplot_titles=flow_targets)
for i, target in enumerate(flow_targets):
hist_y = df_yearly_merged[target]
pred_y = np.maximum(0, best_arima_models[target].forecast(steps=len(years_future)))
fig_arima.add_trace(go.Scatter(x=df_yearly_merged['Year'], y=hist_y, mode='lines+markers', name='実績', line=dict(color='black')), row=1, col=i+1)
fig_arima.add_trace(go.Scatter(x=years_future, y=pred_y, mode='lines+markers', line=dict(dash='dash'), name=f'最適ARIMA予測'), row=1, col=i+1)
fig_arima.update_layout(title='<b>【自動最適化】ベストなARIMAモデル単体の予測推移を見る</b>', height=400, template='plotly_white', showlegend=False)
fig_arima.show()
機械学習の自動特徴量選定
from sklearn.feature_selection import SelectFromModel
flow_targets = ['新設法人件数', '倒産件数', '休廃業・解散件数']
selected_features_dict = {}
fig_rf = make_subplots(rows=1, cols=3, subplot_titles=flow_targets, horizontal_spacing=0.15)
for i, target in enumerate(flow_targets):
X = df_clean[all_features]
y = df_clean[target]
# 特徴量評価用のAI(ランダムフォレスト)
selector_rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)
selector_rf.fit(X, y)
# 重要度ランキング
df_imp = pd.DataFrame({'Feature': all_features, 'Importance': selector_rf.feature_importances_})
df_imp = df_imp.sort_values('Importance', ascending=False)
# 上位 5 個(年次データの過学習を防ぐため、厳選したトップ要因のみ)を本番予測の武器として採用
top_n = 5
best_features = df_imp.head(top_n)['Feature'].tolist()
selected_features_dict[target] = best_features
print(f"🎯 【{target}】の予測にAIが最終選抜したTop{top_n}変数: {best_features}")
# グラフ描画(全変数のうち上位10個を表示)
fig_rf.add_trace(go.Bar(
x=df_imp.head(10)['Importance'], y=df_imp.head(10)['Feature'], orientation='h',
marker=dict(color=df_imp.head(10)['Importance'], colorscale='Viridis'), name=target
), row=1, col=i+1)
fig_rf.update_layout(title='<b>【AIによる特徴量選択】各予測モデルが実際に使う「最強のマクロ要因」一覧</b>', height=500, template='plotly_white', showlegend=False)
fig_rf.update_yaxes(autorange="reversed")
fig_rf.show()
将来シナリオ予測
last_row = df_clean.iloc[-1]
future_scenarios = {'Base': [], 'Good': [], 'Bad': []}
for i, y in enumerate(years_future):
base_dict = {col: last_row.get(col, 0) for col in df_clean.columns}
good_dict = base_dict.copy()
bad_dict = base_dict.copy()
# シナリオ変動(主要指標のみ操作)
base_dict['国内総生産(支出側)(10億円)'] = last_row['国内総生産(支出側)(10億円)'] * (1.01**(i+1))
base_dict['Nikkei225'] = last_row.get('Nikkei225', 30000) * (1.03**(i+1))
base_dict['無担保コールレート・O/N 月平均/金利'] = last_row['無担保コールレート・O/N 月平均/金利'] + 0.1*(i+1)
good_dict['国内総生産(支出側)(10億円)'] = last_row['国内総生産(支出側)(10億円)'] * (1.025**(i+1))
good_dict['有効求人数(万人)'] = last_row.get('有効求人数(万人)', 1) * (1.02**(i+1))
good_dict['完全失業率'] = last_row.get('完全失業率', 2.0) * 0.95
good_dict['Nikkei225'] = last_row.get('Nikkei225', 30000) * (1.07**(i+1))
good_dict['無担保コールレート・O/N 月平均/金利'] = last_row['無担保コールレート・O/N 月平均/金利'] + 0.2*(i+1)
bad_dict['国内総生産(支出側)(10億円)'] = last_row['国内総生産(支出側)(10億円)'] * (0.99**(i+1))
bad_dict['有効求人数(万人)'] = last_row.get('有効求人数(万人)', 1) * (0.95**(i+1))
bad_dict['完全失業率'] = last_row.get('完全失業率', 2.0) * 1.05
bad_dict['Nikkei225'] = last_row.get('Nikkei225', 30000) * (0.95**(i+1))
bad_dict['Crude_Oil'] = last_row.get('Crude_Oil', 80) * (1.05**(i+1))
# 1年前ラグ変数 (_lag1) の動的シミュレーション(近似)
for col in all_features:
if '_lag1' in col:
orig = col.replace('_lag1', '')
# 簡易的に未来でも「その年の現状」に連動するように引き継ぐ
if orig in base_dict:
base_dict[col] = base_dict[orig]
good_dict[col] = good_dict[orig]
bad_dict[col] = bad_dict[orig]
future_scenarios['Base'].append(base_dict)
future_scenarios['Good'].append(good_dict)
future_scenarios['Bad'].append(bad_dict)
predictions_flow = {target: {'ARIMA': {}, 'ML': {}, 'Hybrid': {}} for target in flow_targets}
ml_models_robust = {
'Ridge': Ridge(alpha=1.0),
'RF': RandomForestRegressor(n_estimators=100, max_depth=4, random_state=42)
}
scaler = StandardScaler()
for target in flow_targets:
y_train = df_clean[target].values.astype(float)
last_val = y_train[-1]
# Step 3の「AIが厳選したTop5の専用特徴量」だけを取り出す!
best_features = selected_features_dict[target]
X_train_raw = df_clean[best_features]
X_train_scaled = scaler.fit_transform(X_train_raw)
# ARIMAの予測結果 (Step 2で見つけた最強ARIMA)
preds_arima = np.maximum(0, best_arima_models[target].forecast(steps=len(years_future)))
for sc_name in ['Base', 'Good', 'Bad']:
df_sc = pd.DataFrame(future_scenarios[sc_name])
# 未来シナリオも、選ばれたTop5の特徴量だけを入力に使う
X_sc_raw = df_sc[best_features]
X_sc_scaled = scaler.transform(X_sc_raw)
ml_preds = []
for name, model in ml_models_robust.items():
model.fit(X_train_scaled, y_train)
shift = last_val - model.predict(X_train_scaled)[-1]
pred = model.predict(X_sc_scaled) + shift
ml_preds.append(pred)
ml_ens = np.mean(np.array(ml_preds), axis=0)
predictions_flow[target]['ARIMA'][sc_name] = preds_arima
predictions_flow[target]['ML'][sc_name] = np.maximum(0, ml_ens)
predictions_flow[target]['Hybrid'][sc_name] = np.maximum(0, (preds_arima + np.maximum(0, ml_ens)) / 2.0)
# ストック積み上げ
initial_stock = df_clean['法人企業数'].iloc[-1]
compiled = []
for model_type in ['ARIMA', 'ML', 'Hybrid']:
for sc_name in ['Base', 'Good', 'Bad']:
current_stock = initial_stock
for i, year in enumerate(years_future):
new_corps = list(predictions_flow['新設法人件数'][model_type][sc_name])[i]
bankrupts = list(predictions_flow['倒産件数'][model_type][sc_name])[i]
closures = list(predictions_flow['休廃業・解散件数'][model_type][sc_name])[i]
next_stock = current_stock + new_corps - bankrupts - closures
compiled.append({'モデル': model_type, 'シナリオ': sc_name, '予測年度': year, '推計法人数': next_stock, '新設(増)': new_corps, '倒産(減)': bankrupts, '休廃業(減)': closures})
current_stock = next_stock
df_stock = pd.DataFrame(compiled)
fig_stock = go.Figure()
fig_stock.add_trace(go.Scatter(x=df_clean['Year'], y=df_clean['法人企業数'], mode='lines+markers', name='実績', line=dict(color='black', width=4)))
colors = {'Base': '#1f77b4', 'Good': '#2ca02c', 'Bad': '#d62728'}
names_sc = {'Base': 'Base', 'Good': 'Good', 'Bad': 'Bad'}
dashes = {'ARIMA': 'dot', 'ML': 'dash', 'Hybrid': 'solid'}
for model_type in ['ARIMA', 'ML', 'Hybrid']:
for sc_name in ['Base', 'Good', 'Bad']:
df_sc = df_stock[(df_stock['モデル'] == model_type) & (df_stock['シナリオ'] == sc_name)]
fig_stock.add_trace(go.Scatter(
x=[df_clean['Year'].iloc[-1]] + df_sc['予測年度'].tolist(),
y=[initial_stock] + df_sc['推計法人数'].tolist(),
mode='lines+markers',
name=f'{names_sc[sc_name]} ({model_type})',
line=dict(color=colors[sc_name], dash=dashes[model_type], width=2 if model_type != 'Hybrid' else 3)
))
fig_stock.update_layout(title='<b>【最強ARIMA × AI厳選変数ML】総法人企業数の長期予測(全9シナリオ)</b>', template='plotly_white', hovermode='x unified')
fig_stock.show()
エクセル出力
export_rows = []
all_targets = flow_targets + ['法人企業数']
for target in all_targets:
for model_type in ['ARIMA', 'ML', 'Hybrid']:
for sc_name in ['Base', 'Good', 'Bad']:
hist_years = df_clean['Year'].tolist()
hist_vals = df_clean[target].tolist()
if target == '法人企業数':
df_sc = df_stock[(df_stock['モデル'] == model_type) & (df_stock['シナリオ'] == sc_name)]
pred_years = df_sc['予測年度'].tolist()
pred_vals = df_sc['推計法人数'].tolist()
pred_ranges = ["-" for _ in pred_years]
else:
pred_years = years_future
pred_vals = predictions_flow[target][model_type][sc_name]
pred_ranges = []
for i, y in enumerate(years_future):
val = pred_vals[i]
err_margin = val * 0.10
v_min, v_max = max(0, val - err_margin), val + err_margin
pred_ranges.append(f"{int(v_min):,} 〜 {int(v_max):,}")
all_years = hist_years + pred_years
all_vals = hist_vals + list(pred_vals)
for data_type in ['推定値', '前年との増加率', '増減', 'レンジ']:
row_dict = {
'地域詳細': '', '大分類': '', '売上規模': '',
'モデル': model_type, '指標': target, 'シナリオ': sc_name, '数値': data_type
}
#各年の計算
for y_idx, y_val in enumerate(pred_years):
full_idx = all_years.index(y_val)
val_current = all_vals[full_idx]
val_prev = all_vals[full_idx - 1]
if data_type == '推定値': row_dict[f'{y_val}年'] = int(val_current)
elif data_type == '増減': row_dict[f'{y_val}年'] = int(val_current - val_prev)
elif data_type == '前年との増加率':
rate = ((val_current - val_prev) / val_prev) * 100 if val_prev > 0 else 0
row_dict[f'{y_val}年'] = f"{rate:+.2f}%"
elif data_type == 'レンジ': row_dict[f'{y_val}年'] = pred_ranges[y_idx]
export_rows.append(row_dict)
df_export = pd.DataFrame(export_rows)
columns_order = ['地域詳細', '大分類', '売上規模', 'モデル', '指標', 'シナリオ', '数値', '2024年', '2025年', '2026年', '2027年', '2028年', '2029年', '2030年']
columns_order = [c for c in columns_order if c in df_export.columns]
df_export = df_export[columns_order]
out_file = 'data/corporation_forecast_robust_format.xlsx'
df_export.to_excel(out_file, index=False)
print(f"✅ Excel出力完了: {out_file}")
地域、大分類への拡張アプローチ
# ==========================================
# 拡張分析(ブレイクダウン分析)のプレースホルダー
# ==========================================
print("【今後の拡張分析に向けたデータの準備】")
file_path = 'data/20260322macrodata_formatted_all.xlsx'
# 1. 各都道府県の実数・成長率・構成比を取り込むことができます。
df_pref_ratio = pd.read_excel(file_path, sheet_name='有効求人数_都道府県_構成比%')
print("■ 都道府県ごとの求人パイアプローチの基礎データ:")
display(df_pref_ratio.head(3))
# 2. 産業(大分類)ごとの実数・成長率・構成比を取り込むことができます。
df_ind_ratio = pd.read_excel(file_path, sheet_name='有効求人数_大分類_構成比%')
print("\n■ 大分類(産業)ごとの求人パイアプローチの基礎データ:")
display(df_ind_ratio.head(3))
# → 次のフェーズ:
# Step 4で予測した「全国の倒産件数」や「全新設数」を、この地域構成比・産業成長率のトレンドを使って、
# 「東京のIT分野の新設法人数はどうなるか?」といった細かなマトリクス(DataFrame)へと展開するロジックをここに記述します。
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
# ==========================================
# 1. ユーザーが持っている「実際の詳細データ(全国・中部5県)」のダミーモック
# ※ここに本物のデータを読み込んで差し替えます
# ==========================================
years_hist = df_clean['Year'].tolist()
national_history = df_clean['法人企業数'].tolist()
# 対象の5県
prefectures = ['静岡', '愛知', '長野', '岐阜', '三重']
# ※以下は本物のデータを取り込むまでのシミュレーション用ダミーシェアです
dummy_breakdown = []
for y, total in zip(years_hist, national_history):
dummy_breakdown.append({
'Year': y,
'全国': total,
'静岡': total * 0.030, # 約3.0%
'愛知': total * 0.070, # 約7.0%
'長野': total * 0.020, # 約2.0%
'岐阜': total * 0.018, # 約1.8%
'三重': total * 0.015 # 約1.5%
# 中部はこれらの合計として後で自動算出します
})
df_real_breakdown = pd.DataFrame(dummy_breakdown)
# ------------------------------------------
# 2. 5県のシェア(対全国構成比)の計算と、未来のシェア予測(線形トレンド)
# ------------------------------------------
df_share = pd.DataFrame({'Year': years_hist})
for pref in prefectures:
# 各県の全国に対するシェア
df_share[pref + '_share'] = df_real_breakdown[pref] / df_real_breakdown['全国']
future_years_arr = np.array(years_future).reshape(-1, 1)
hist_years_arr = np.array(years_hist).reshape(-1, 1)
projected_shares = {'Year': years_future}
for pref in prefectures:
lr = LinearRegression()
# 過去のシェアトレンドを学習 (直近5年分などに合わせるのが実務ではオススメです)
lr.fit(hist_years_arr[-5:], df_share[pref + '_share'].tail(5))
pred_share = lr.predict(future_years_arr)
# マイナスにならないよう下限0.001でクリップ
projected_shares[pref + '_share'] = np.clip(pred_share, 0.001, 1.0)
df_future_share = pd.DataFrame(projected_shares)
# ------------------------------------------
# 3. 予測推移(全国)に未来シェアを掛け合わせてブレイクダウン
# ------------------------------------------
df_national_base = df_stock[df_stock['シナリオ'] == 'Base'].copy()
final_predictions = []
for i, row in df_national_base.iterrows():
y = row['予測年度']
nat_total = row['推計法人数']
# 【全国】
final_predictions.append({
'地域詳細': '全国', '大分類': '全産業', '指標': '法人企業数',
'シナリオ': 'Base', '年度': y, '推定構成比': '100.00%', '予測企業数': int(nat_total)
})
share_row = df_future_share[df_future_share['Year'] == y]
chubu_total = 0
chubu_share_sum = 0
# 【各県】
for pref in prefectures:
pref_share = share_row[pref + '_share'].values[0]
pref_pred = nat_total * pref_share
chubu_total += pref_pred
chubu_share_sum += pref_share
final_predictions.append({
'地域詳細': pref, '大分類': '全産業', '指標': '法人企業数',
'シナリオ': 'Base', '年度': y, '推定構成比': f"{pref_share*100:.2f}%", '予測企業数': int(pref_pred)
})
# 【中部 (5県合計)】
final_predictions.append({
'地域詳細': '中部 (5県合算)', '大分類': '全産業', '指標': '法人企業数',
'シナリオ': 'Base', '年度': y, '推定構成比': f"{chubu_share_sum*100:.2f}%", '予測企業数': int(chubu_total)
})
df_regional_forecast = pd.DataFrame(final_predictions)
# 表示用のクロス集計(年度ヨコ展開)
df_pivot = df_regional_forecast.pivot(index=['地域詳細', '大分類', '指標', 'シナリオ'], columns='年度', values='予測企業数').reset_index()
# 順番を見やすくソート(全国 → 中部 → 各県)
sorter = ['全国', '中部 (5県合算)', '静岡', '愛知', '長野', '岐阜', '三重']
df_pivot['sorter'] = df_pivot['地域詳細'].map(lambda x: sorter.index(x) if x in sorter else 99)
df_pivot = df_pivot.sort_values('sorter').drop('sorter', axis=1)
print("🎯 【完成】トップダウン配分による将来予測(全国・中部・5県の詳細)")
display(df_pivot)
# グラフ化:各県の予測推移
import plotly.express as px
df_plot = df_regional_forecast[df_regional_forecast['地域詳細'] != '全国'] # 全国はスケールが違いすぎるのでグラフから除外
fig_region = px.line(df_plot, x='年度', y='予測企業数', color='地域詳細', markers=True,
title="<b>【拡張】トップダウン方式による各地域の法人数予測 (Baseシナリオ)</b>")
fig_region.update_layout(template='plotly_white')
fig_region.show()
print("\n💡 次のアクション:ダミーで入れている「df_real_breakdown」の部分をお手持ちの本物のExcelデータに差し替えるだけで、")
print("そのまま完璧な未来予測シートが完成し、Excelへ出力可能になります!")