sugitora's picture
Update app.R
23a654d verified
# Required Packages
if (!require(shiny)) install.packages("shiny")
if (!require(ggplot2)) install.packages("ggplot2")
library(shiny)
library(ggplot2)
# Vectorized Black-Scholes Call Option Formula
bs_call_price_vec <- Vectorize(function(S, T, K, r, sigma){
d1 <- (log(S/K) + (r + 0.5*sigma^2)*T) / (sigma*sqrt(T))
d2 <- d1 - sigma*sqrt(T)
S * pnorm(d1) - K * exp(-r*T) * pnorm(d2)
})
# UI
ui <- fluidPage(
titlePanel("カーボンプライシング × ブラック=ショールズモデル (Shiny版)"),
sidebarLayout(
sidebarPanel(
numericInput("S0", "初期カーボン価格 ($/t-CO2)", value = 50, min = 1, max = 200),
numericInput("mu", "ドリフト (期待成長率)", value = 0.05, step = 0.01),
numericInput("sigma", "ボラティリティ", value = 0.2, step = 0.01),
numericInput("K", "行使価格 ($)", value = 55, min = 1),
numericInput("r", "無リスク金利", value = 0.01, step = 0.005),
sliderInput("T", "満期 (年)", min = 0.1, max = 2, value = 1, step = 0.1),
actionButton("simulate", "シミュレーション開始")
),
mainPanel(
plotOutput("carbonPlot"),
plotOutput("optionPlot")
)
)
)
# Server
server <- function(input, output) {
observeEvent(input$simulate, {
set.seed(123)
steps <- 252
dt <- input$T / steps
carbon_price <- numeric(steps + 1)
carbon_price[1] <- input$S0
for (i in 2:(steps + 1)) {
carbon_price[i] <- carbon_price[i-1] * exp((input$mu - 0.5 * input$sigma^2) * dt + input$sigma * sqrt(dt) * rnorm(1))
}
time_to_maturity <- seq(input$T, 0, length.out = steps + 1)
option_prices <- bs_call_price_vec(S = carbon_price, T = time_to_maturity, K = input$K, r = input$r, sigma = input$sigma)
df <- data.frame(
Day = 0:steps,
CarbonPrice = carbon_price,
OptionPrice = option_prices
)
output$carbonPlot <- renderPlot({
ggplot(df, aes(x = Day, y = CarbonPrice)) +
geom_line(color = "blue", size = 1) +
labs(title = "Carbon Price Path",
x = "Days",
y = "Carbon Price ($/t-CO2)") +
theme_minimal()
})
output$optionPlot <- renderPlot({
ggplot(df, aes(x = Day, y = OptionPrice)) +
geom_line(color = "darkgreen", size = 1) +
labs(title = "European Call Option Price",
x = "Days",
y = "Option Price ($)") +
theme_minimal()
})
})
}
# Run App
shinyApp(ui = ui, server = server)