経済学のための数学コード


```
from scipy.optimize import minimize

# 利益関数の定義
def profit_function(x):
    # 例として利益関数 = - (x^2 - 4x + 4) （ここで -1 をかけて最大化問題にする）
    return -(x**2 - 4*x + 4)

# 最適化の実行
result_profit = minimize(profit_function, x0=0)  # 初期値として0

# 結果の表示
print(f"Maximum profit: {-result_profit.fun}")
print(f"Optimal quantity: {result_profit.x}")

# グラフの描画
import matplotlib.pyplot as plt
import numpy as np

x_vals = np.linspace(-1, 5, 400)
y_vals = -(x_vals**2 - 4*x_vals + 4)

plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals, label='Profit Function')
plt.scatter(result_profit.x, -result_profit.fun, color='red', label='Optimal Point')
plt.xlabel('Quantity')
plt.ylabel('Profit')
plt.title('Profit Maximization')
plt.legend()
plt.grid(True)
plt.show()

```


```
from scipy.optimize import minimize

# コスト関数の定義
def cost_function(x):
    # 例としてコスト関数 = x^2 + 2x + 1
    return x**2 + 2*x + 1

# 最適化の実行
result_cost = minimize(cost_function, x0=0)  # 初期値として0

# 結果の表示
print(f"Minimum cost: {result_cost.fun}")
print(f"Optimal quantity: {result_cost.x}")

# グラフの描画
import matplotlib.pyplot as plt
import numpy as np

x_vals = np.linspace(-2, 2, 400)
y_vals = x_vals**2 + 2*x_vals + 1

plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals, label='Cost Function')
plt.scatter(result_cost.x, result_cost.fun, color='red', label='Optimal Point')
plt.xlabel('Quantity')
plt.ylabel('Cost')
plt.title('Cost Minimization')
plt.legend()
plt.grid(True)
plt.show()


```



```

import numpy as np
import matplotlib.pyplot as plt

# 需要と供給の関数の定義
def demand(p):
    return 100 - 2*p  # 例: 需要関数 = 100 - 2p

def supply(p):
    return 20 + 3*p  # 例: 供給関数 = 20 + 3p

# 均衡点の計算
from scipy.optimize import fsolve

def equilibrium_price(p):
    return demand(p) - supply(p)

# 均衡価格の計算
price_eq = fsolve(equilibrium_price, 10)[0]
quantity_eq = demand(price_eq)

# 結果の表示
print(f"Equilibrium Price: {price_eq}")
print(f"Equilibrium Quantity: {quantity_eq}")

# グラフの描画
p_vals = np.linspace(0, 50, 400)
d_vals = demand(p_vals)
s_vals = supply(p_vals)

plt.figure(figsize=(10, 6))
plt.plot(p_vals, d_vals, label='Demand Function')
plt.plot(p_vals, s_vals, label='Supply Function')
plt.scatter(price_eq, quantity_eq, color='red', label='Equilibrium Point')
plt.xlabel('Price')
plt.ylabel('Quantity')
plt.title('Demand and Supply Analysis')
plt.legend()
plt.grid(True)
plt.show()


```



```
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris

# Load the Iris dataset
data = load_iris()
X = data.data
y = data.target

# Perform PCA
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)

# Plot the results
plt.figure(figsize=(10, 6))
scatter = plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis', edgecolor='k', s=40)
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.title('PCA of Iris Dataset')
plt.colorbar(scatter, label='Target')
plt.grid(True)
plt.show()

# Print explained variance ratio
print(f"Explained variance ratio: {pca.explained_variance_ratio_}")



```




```

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# サンプル経済データの作成
data = pd.DataFrame({
    'GDP': np.random.rand(100) * 1000,
    'Unemployment': np.random.rand(100) * 10,
    'Inflation': np.random.rand(100) * 5
})

# 説明変数と目的変数
X = data[['GDP', 'Unemployment']]
y = data['Inflation']

# データの分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

# 線形回帰モデルの作成と適合
model = LinearRegression()
model.fit(X_train, y_train)

# 予測と評価
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)

# 結果の表示
plt.figure(figsize=(8, 6))
plt.scatter(y_test, y_pred, color='blue')
plt.xlabel('Actual Inflation')
plt.ylabel('Predicted Inflation')
plt.title('Inflation Prediction')
plt.grid(True)
plt.show()


```
```

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import linprog

# 経済モデルの線形化
# 例: 目的関数の最小化
c = [-1, -2]  # コスト関数の係数（最小化したい関数）
A = [[2, 1], [1, 2]]  # 制約条件の係数
b = [20, 16]  # 制約条件の右辺

# 線形計画法の実行
result = linprog(c, A_ub=A, b_ub=b, method='highs')

# 結果の表示
print("Optimal value:", result.fun)
print("Optimal solution:", result.x)

# グラフの描画
plt.figure(figsize=(8, 6))
x = np.linspace(0, 10, 400)
y1 = (20 - 2*x)
y2 = (16 - x)/2

plt.plot(x, y1, label='Constraint 1')
plt.plot(x, y2, label='Constraint 2')
plt.fill_between(x, np.minimum(y1, y2), color='gray', alpha=0.5)
plt.scatter(result.x[0], result.x[1], color='red', label='Optimal Solution')
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('Linear Programming')
plt.legend()
plt.grid(True)
plt.show()

```


```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# サンプル経済データの生成
np.random.seed(0)
data_size = 100
advertising_expense = np.random.rand(data_size, 1) * 5000  # 広告費
promotion_expense = np.random.rand(data_size, 1) * 3000  # 販売促進費
sales = 3 * advertising_expense.squeeze() + 2 * promotion_expense.squeeze() + np.random.randn(data_size) * 1000  # 売上

# データフレームの作成
df = pd.DataFrame({
    'Advertising Expense': advertising_expense.squeeze(),
    'Promotion Expense': promotion_expense.squeeze(),
    'Sales': sales
})

# 1. 記述統計
mean = df['Sales'].mean()
median = df['Sales'].median()
variance = df['Sales'].var()
std_dev = df['Sales'].std()

print("Descriptive Statistics:")
print(f"Mean: ${mean:.2f}")
print(f"Median: ${median:.2f}")
print(f"Variance: ${variance:.2f}")
print(f"Standard Deviation: ${std_dev:.2f}")

# 2. 推測統計
# 仮説検定: 売上が100000ドル以上であるかどうか
t_stat, p_value = stats.ttest_1samp(sales, popmean=100000)
print("\nHypothesis Testing:")
print(f"T-statistic: {t_stat:.2f}")
print(f"P-value: {p_value:.2f}")

# 信頼区間の計算
confidence = 0.95
mean = np.mean(sales)
sem = stats.sem(sales)  # 標準誤差
h = sem * stats.t.ppf((1 + confidence) / 2., len(sales) - 1)
print(f"\n{confidence*100}% Confidence Interval: (${mean - h:.2f}, ${mean + h:.2f})")

# 3. 回帰分析
# 単回帰分析: 広告費と売上の関係
model = LinearRegression()
model.fit(advertising_expense, sales)
print("\nSimple Linear Regression:")
print(f"Slope: {model.coef_[0]:.2f}")
print(f"Intercept: {model.intercept_:.2f}")

# グラフの描画
plt.figure(figsize=(12, 6))

# 単回帰分析のプロット
plt.subplot(1, 2, 1)
plt.scatter(advertising_expense, sales, color='blue', label='Data points')
plt.plot(advertising_expense, model.predict(advertising_expense), color='red', linewidth=2, label='Regression Line')
plt.xlabel('Advertising Expense ($)')
plt.ylabel('Sales ($)')
plt.title('Simple Linear Regression')
plt.legend()
plt.grid(True)

# 重回帰分析のプロット
X = np.hstack([advertising_expense, promotion_expense])
X_train, X_test, y_train, y_test = train_test_split(X, sales, test_size=0.2, random_state=0)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("\nMultiple Linear Regression:")
print(f"Mean Squared Error: {mse:.2f}")

plt.subplot(1, 2, 2)
plt.scatter(y_test, y_pred, color='blue')
plt.xlabel('Actual Sales ($)')
plt.ylabel('Predicted Sales ($)')
plt.title('Multiple Linear Regression')
plt.grid(True)

plt.tight_layout()
plt.show()


```


```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm, expon
from sklearn.utils import shuffle

# Parameters for the simulation
np.random.seed(0)
num_simulations = 10000
mean_return = 0.07
std_dev_return = 0.15
investment_amount = 100000

# 1. Risk Evaluation using Normal Distribution
returns = np.random.normal(loc=mean_return, scale=std_dev_return, size=num_simulations)
final_values = investment_amount * (1 + returns)

# Risk metrics
mean_final_value = np.mean(final_values)
std_dev_final_value = np.std(final_values)
value_at_risk_95 = np.percentile(final_values, 5)

print("Risk Evaluation:")
print(f"Mean Final Value: ${mean_final_value:.2f}")
print(f"Standard Deviation of Final Value: ${std_dev_final_value:.2f}")
print(f"Value at Risk (95% Confidence): ${value_at_risk_95:.2f}")

# 2. Forecasting using Exponential Distribution
# Simulate the time until an event (e.g., default or failure) occurs
failure_times = np.random.exponential(scale=5, size=num_simulations)

# Forecast metrics
mean_failure_time = np.mean(failure_times)
std_dev_failure_time = np.std(failure_times)

print("\nForecasting:")
print(f"Mean Failure Time: {mean_failure_time:.2f} years")
print(f"Standard Deviation of Failure Time: {std_dev_failure_time:.2f} years")

# Plotting the distributions
plt.figure(figsize=(12, 6))

# Risk Evaluation Plot
plt.subplot(1, 2, 1)
plt.hist(final_values, bins=50, color='skyblue', edgecolor='black')
plt.axvline(value_at_risk_95, color='red', linestyle='dashed', linewidth=1, label='Value at Risk (95%)')
plt.xlabel('Final Investment Value ($)')
plt.ylabel('Frequency')
plt.title('Investment Final Value Distribution')
plt.legend()
plt.grid(True)

# Forecasting Plot
plt.subplot(1, 2, 2)
plt.hist(failure_times, bins=50, color='salmon', edgecolor='black')
plt.xlabel('Failure Time (years)')
plt.ylabel('Frequency')
plt.title('Failure Time Distribution')
plt.grid(True)

plt.tight_layout()
plt.show()


```




```
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# ブラック-ショールズモデルのオプション価格計算
def black_scholes_call_price(S, K, T, r, sigma):
    """
    ブラック-ショールズモデルによるコールオプション価格の計算

    Parameters:
    S (float): 現在の株価
    K (float): 行使価格
    T (float): 満期までの時間（年）
    r (float): 無リスク金利
    sigma (float): ボラティリティ

    Returns:
    float: コールオプション価格
    """
    d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
    d2 = d1 - sigma * np.sqrt(T)
    call_price = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
    return call_price

def black_scholes_vega(S, K, T, r, sigma):
    """
    ブラック-ショールズモデルによるヴェガの計算

    Parameters:
    S (float): 現在の株価
    K (float): 行使価格
    T (float): 満期までの時間（年）
    r (float): 無リスク金利
    sigma (float): ボラティリティ

    Returns:
    float: ヴェガ
    """
    d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
    vega = S * norm.pdf(d1) * np.sqrt(T)
    return vega

# ヘッジ戦略のシミュレーション
def hedge_strategy_simulation(S0, K, T, r, sigma, delta_s, num_steps):
    """
    ヘッジ戦略のシミュレーション

    Parameters:
    S0 (float): 初期株価
    K (float): 行使価格
    T (float): 満期までの時間（年）
    r (float): 無リスク金利
    sigma (float): ボラティリティ
    delta_s (float): 株価の変動幅
    num_steps (int): シミュレーションステップ数

    Returns:
    tuple: シミュレーション結果（株価、ポートフォリオ価値）
    """
    dt = T / num_steps
    S = np.zeros(num_steps + 1)
    portfolio_value = np.zeros(num_steps + 1)
    
    S[0] = S0
    portfolio_value[0] = black_scholes_call_price(S0, K, T, r, sigma)
    
    for i in range(1, num_steps + 1):
        S[i] = S[i-1] + delta_s
        vega = black_scholes_vega(S[i-1], K, T - (i * dt), r, sigma)
        portfolio_value[i] = black_scholes_call_price(S[i], K, T - (i * dt), r, sigma) - vega * delta_s
    
    return S, portfolio_value

# パラメータ設定
S0 = 100        # 現在の株価
K = 100         # 行使価格
T = 1           # 満期までの時間（年）
r = 0.05        # 無リスク金利
sigma = 0.2     # ボラティリティ
delta_s = 0.5   # 株価の変動幅
num_steps = 100 # シミュレーションステップ数

# オプション価格の計算
call_price = black_scholes_call_price(S0, K, T, r, sigma)
print(f"Call Option Price: ${call_price:.2f}")

# ヘッジ戦略のシミュレーション
S, portfolio_value = hedge_strategy_simulation(S0, K, T, r, sigma, delta_s, num_steps)

# プロット
plt.figure(figsize=(12, 6))

# 株価の変動
plt.subplot(1, 2, 1)
plt.plot(S, label='Stock Price')
plt.xlabel('Step')
plt.ylabel('Stock Price')
plt.title('Stock Price Simulation')
plt.grid(True)
plt.legend()

# ポートフォリオ価値
plt.subplot(1, 2, 2)
plt.plot(portfolio_value, label='Portfolio Value', color='orange')
plt.xlabel('Step')
plt.ylabel('Portfolio Value')
plt.title('Portfolio Value Simulation')
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()



```

```
import numpy as np
import matplotlib.pyplot as plt

# 時間価値の計算
def present_value(future_value, rate, periods):
    """
    割引現在価値の計算

    Parameters:
    future_value (float): 未来価値
    rate (float): 割引率
    periods (int): 割引期間

    Returns:
    float: 現在価値
    """
    return future_value / (1 + rate) ** periods

def future_value(present_value, rate, periods):
    """
    未来価値の計算

    Parameters:
    present_value (float): 現在価値
    rate (float): 利率
    periods (int): 期間

    Returns:
    float: 未来価値
    """
    return present_value * (1 + rate) ** periods

# 金利計算
def compound_interest(principal, rate, periods, compounding_per_year):
    """
    複利計算

    Parameters:
    principal (float): 元本
    rate (float): 年利率
    periods (int): 投資期間（年）
    compounding_per_year (int): 年間の複利回数

    Returns:
    float: 最終的な金額
    """
    return principal * (1 + rate / compounding_per_year) ** (compounding_per_year * periods)

def continuous_compound_interest(principal, rate, periods):
    """
    連続複利計算

    Parameters:
    principal (float): 元本
    rate (float): 年利率
    periods (int): 投資期間（年）

    Returns:
    float: 最終的な金額
    """
    return principal * np.exp(rate * periods)

# リスクとリターン
def portfolio_return(weights, returns):
    """
    ポートフォリオリターンの計算

    Parameters:
    weights (list): 投資配分
    returns (list): 各資産のリターン

    Returns:
    float: ポートフォリオリターン
    """
    return np.dot(weights, returns)

def portfolio_risk(cov_matrix, weights):
    """
    ポートフォリオリスクの計算（標準偏差）

    Parameters:
    cov_matrix (np.ndarray): 共分散行列
    weights (list): 投資配分

    Returns:
    float: ポートフォリオリスク
    """
    return np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))

# パラメータ設定
principal = 1000     # 元本
rate = 0.05          # 利率
periods = 10          # 投資期間（年）
compounding_per_year = 4  # 年間の複利回数

# 時間価値の計算
pv = present_value(1500, rate, periods)
fv = future_value(principal, rate, periods)
print(f"Present Value: ${pv:.2f}")
print(f"Future Value: ${fv:.2f}")

# 金利計算
compound_amount = compound_interest(principal, rate, periods, compounding_per_year)
continuous_amount = continuous_compound_interest(principal, rate, periods)
print(f"Compound Interest Amount: ${compound_amount:.2f}")
print(f"Continuous Compound Interest Amount: ${continuous_amount:.2f}")

# ポートフォリオ理論
returns = np.array([0.08, 0.12, 0.15])  # 各資産のリターン
weights = np.array([0.4, 0.4, 0.2])    # 投資配分
cov_matrix = np.array([[0.0004, 0.0001, 0.0002],
                       [0.0001, 0.0003, 0.00015],
                       [0.0002, 0.00015, 0.0005]])

port_return = portfolio_return(weights, returns)
port_risk = portfolio_risk(cov_matrix, weights)
print(f"Portfolio Return: {port_return:.2f}")
print(f"Portfolio Risk (Standard Deviation): {port_risk:.2f}")

# ポートフォリオのリスクとリターンをプロット
num_portfolios = 10000
results = np.zeros((3, num_portfolios))

for i in range(num_portfolios):
    weights = np.random.random(len(returns))
    weights /= np.sum(weights)
    
    port_return = portfolio_return(weights, returns)
    port_risk = portfolio_risk(cov_matrix, weights)
    
    results[0,i] = port_return
    results[1,i] = port_risk
    results[2,i] = port_return / port_risk

plt.figure(figsize=(12, 6))

# リスクとリターンのプロット
plt.scatter(results[1,:], results[0,:], c=results[2,:], cmap='viridis')
plt.xlabel('Risk (Standard Deviation)')
plt.ylabel('Return')
plt.title('Portfolio Optimization')
plt.colorbar(label='Sharpe Ratio')
plt.grid(True)
plt.show()

```



```

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

# 経済均衡モデル: 供給と需要の均衡
def supply_demand_eq(price, demand_params, supply_params):
    """
    供給と需要の均衡を求める

    Parameters:
    price (float): 価格
    demand_params (tuple): 需要関数のパラメータ
    supply_params (tuple): 供給関数のパラメータ

    Returns:
    float: 需要と供給の差
    """
    demand = demand_params[0] - demand_params[1] * price
    supply = supply_params[0] + supply_params[1] * price
    return demand - supply

# ゲーム理論: ナッシュ均衡の計算
def nash_equilibrium(payoff_matrix):
    """
    ナッシュ均衡を求める

    Parameters:
    payoff_matrix (np.ndarray): 各プレイヤーの報酬行列

    Returns:
    tuple: ナッシュ均衡の戦略
    """
    num_actions = payoff_matrix.shape[0]

    def objective(x):
        return -np.sum(x * np.log(x))

    constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}]
    
    results = []
    for i in range(num_actions):
        constraints.append({'type': 'ineq', 'fun': lambda x, i=i: np.sum(payoff_matrix[i, :] * x) - np.sum(payoff_matrix[i, :])})

    for i in range(num_actions):
        initial_guess = np.ones(num_actions) / num_actions
        res = minimize(objective, initial_guess, constraints=constraints)
        results.append(res.x)

    return results

# パラメータ設定
price_range = np.linspace(0, 10, 100)
demand_params = (100, 2)  # 需要関数のパラメータ (a, b)
supply_params = (20, 1)   # 供給関数のパラメータ (c, d)

# 供給と需要の均衡をプロット
demand = demand_params[0] - demand_params[1] * price_range
supply = supply_params[0] + supply_params[1] * price_range
equilibrium_price = minimize(lambda p: supply_demand_eq(p, demand_params, supply_params), 5).x[0]

plt.figure(figsize=(10, 6))
plt.plot(price_range, demand, label='Demand')
plt.plot(price_range, supply, label='Supply')
plt.axvline(equilibrium_price, color='r', linestyle='--', label='Equilibrium Price')
plt.xlabel('Price')
plt.ylabel('Quantity')
plt.title('Supply and Demand Equilibrium')
plt.legend()
plt.grid(True)
plt.show()

# ゲーム理論: ナッシュ均衡の計算
payoff_matrix = np.array([[3, 2], [4, 1]])  # 2x2の報酬行列
nash_eq = nash_equilibrium(payoff_matrix)

print("Nash Equilibrium Strategies:")
for strategy in nash_eq:
    print(strategy)

```


```
import numpy as np
import matplotlib.pyplot as plt

# パラメータの設定
N = 100  # 時間ステップ
V = np.zeros(N + 1)
r = 0.1  # 割引率
reward = 1  # 報酬

# ベルマン方程式の適用
for t in reversed(range(N)):
    V[t] = reward + r * V[t + 1]

# 結果の表示
plt.plot(range(N + 1), V, marker='o')
plt.xlabel('Time')
plt.ylabel('Value Function')
plt.title('Dynamic Programming Value Function')
plt.grid(True)
plt.show()


```

```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# --- Market Research Statistical Methods ---

# Sample Data
np.random.seed(0)
sample_data = np.random.normal(loc=50, scale=10, size=100)

# Sample Mean and Standard Deviation
mean_estimate = np.mean(sample_data)
std_estimate = np.std(sample_data, ddof=1)

# Confidence Interval
confidence = 0.95
z = stats.norm.ppf((1 + confidence) / 2)
margin_of_error = z * (std_estimate / np.sqrt(len(sample_data)))
confidence_interval = (mean_estimate - margin_of_error, mean_estimate + margin_of_error)

# Plot Histogram with Confidence Interval
plt.figure(figsize=(12, 6))
plt.hist(sample_data, bins=20, alpha=0.7, color='blue', edgecolor='black')
plt.axvline(mean_estimate, color='red', linestyle='dashed', linewidth=1)
plt.axvline(confidence_interval[0], color='green', linestyle='dashed', linewidth=1)
plt.axvline(confidence_interval[1], color='green', linestyle='dashed', linewidth=1)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Sample Survey Data with Confidence Interval')
plt.legend(['Mean Estimate', 'Confidence Interval'])
plt.show()

# Hypothesis Testing
group1 = np.random.normal(loc=100, scale=15, size=50)
group2 = np.random.normal(loc=110, scale=15, size=50)
t_stat, p_value = stats.ttest_ind(group1, group2)

print(f"T-statistic: {t_stat:.2f}")
print(f"P-value: {p_value:.4f}")

alpha = 0.05
if p_value < alpha:
    print("Reject the null hypothesis: There is a significant difference between the two groups.")
else:
    print("Fail to reject the null hypothesis: There is no significant difference between the two groups.")

# --- Consumer Behavior Analysis ---

# Demand Forecasting Model
time = np.arange(1, 13)
demand = 200 + 15 * time + np.random.normal(scale=10, size=time.shape[0])
data = pd.DataFrame({'Month': time, 'Demand': demand})

# Fit Linear Regression Model
X = data[['Month']]
y = data['Demand']
model = LinearRegression()
model.fit(X, y)
data['Predicted_Demand'] = model.predict(X)

# Plot Results
plt.figure(figsize=(12, 6))
plt.plot(data['Month'], data['Demand'], label='Actual Demand', marker='o')
plt.plot(data['Month'], data['Predicted_Demand'], label='Predicted Demand', linestyle='--')
plt.xlabel('Month')
plt.ylabel('Demand')
plt.title('Demand Forecasting Model')
plt.legend()
plt.grid(True)
plt.show()

# Print Model Performance
mse = mean_squared_error(y, data['Predicted_Demand'])
print(f"Mean Squared Error: {mse:.2f}")


```