import gradio as gr
import numpy as np
import requests
import cohere
from dotenv import load_dotenv
import os
from gradio_pdf import PDF
load_dotenv(verbose=True)
coherekey = os.environ.get("COHERE_API_KEY")
co = cohere.ClientV2(api_key=coherekey)
cresponse = requests.get("https://www.ryhintl.com/chatgpt/dynamic.php")
cohere_doc = cresponse.json()
setsumei = '''
需要と供給の均衡点
需要と供給の均衡点
最も基本的な方法は、需要曲線と供給曲線の交点を見つけることです。この交点が市場の均衡価格を示します。
需要曲線 = Qd = a - bP
供給曲線 = Qs = c + dP
ここで、P は価格、a, b, c, d は定数です。均衡点では Qd = Qs となるため、次の方程式を解きます:
a - bP = c + dP
P = (a - c) / (b + d)
この P が均衡価格です。
利潤最大化
企業が利潤を最大化するための価格設定も重要です。利潤 π は次のように表されます:
ここで、TR は総収入、TC は総費用です。総収入 TR は価格 P と販売量 Q の積で表されます:
総費用 TC は固定費用 FC と変動費用 VC の和です:
利潤を最大化するためには、次の条件を満たす価格 P を見つけます:
価格弾力性を考慮した価格設定
価格弾力性を考慮することで、価格変更が需要に与える影響を評価できます。価格弾力性 ϵ は次のように定義されます:
ΔQ は需要の変化量、ΔP は価格の変化量です。価格弾力性が高い場合、価格を下げることで需要が大幅に増加し、総収入が増える可能性があります。
これらの方法を組み合わせることで、より精度の高い最適価格を導出することができます。具体的な状況に応じて適切な手法を選択することが重要です。
価格弾力性が高い場合
- メリット:
- 価格変更の影響: 価格を下げると需要が大幅に増加するため、売上を増やすことができます。
- 競争力: 価格を柔軟に調整することで、競合他社に対して優位に立つことができます。
- デメリット:
- 収益の不安定性: 価格を上げると需要が大幅に減少するため、収益が不安定になる可能性があります。
- 価格競争: 価格弾力性が高い市場では、価格競争が激化し、利益率が低下することがあります。
価格弾力性が低い場合
- メリット:
- 収益の安定性: 価格変更が需要に与える影響が小さいため、収益が安定しやすいです。
- 価格設定の自由度: 価格を上げても需要が大きく減少しないため、利益率を維持しやすいです。
- デメリット:
- 需要の増加: 価格を下げても需要が大幅に増加しないため、売上を増やすのが難しいです。
- 競争力: 価格を柔軟に調整することで競争力を高めるのが難しいです。
企業の戦略や市場の特性に応じて、価格弾力性の高低がどちらが良いかを判断することが重要です。具体的な状況に応じて、適切な価格戦略を選択することが求められます。
需要曲線と供給曲線の切片と傾き
1. 需要曲線の切片
需要曲線の切片は、需要曲線が価格軸(縦軸)と交わる点を指します。需要曲線は通常、次のような線形方程式で表されます:
ここで、
- Qdは需要量
- Pは価格
- aは需要曲線の切片
- bは価格に対する需要の変化率(傾き)
切片aは、価格がゼロのときの需要量を示します。つまり、価格がゼロの場合に消費者が購入する量です。この値は、需要曲線が価格軸と交わる点の需要量を表します。
例えば、需要曲線がQd = 50 − 2Pである場合、切片aは50です。これは、価格がゼロのときに需要量が50であることを意味します。
需要曲線の切片は、消費者の基本的な需要を示し、価格が変動する際の需要の変化を理解するための重要な要素です。
2. 需要曲線の傾き
需要曲線の傾きは、価格の変化に対する需要量の変化を示す重要な指標です。需要曲線は通常、次のような線形方程式で表されます:
ここで、
- Qdは需要量
- Pは価格
- aは需要曲線の切片
- bは価格に対する需要の変化率(傾き)
傾きbは、価格が1単位変化したときに需要量がどれだけ変化するかを示します。具体的には、傾きは次のように計算されます:
ここで、ΔQdは需要量の変化、ΔPは価格の変化です。
例えば、需要曲線がQd = 50 - 2Pである場合、傾きbは2です。これは、価格が1単位上昇すると需要量が2単位減少することを意味します。
3. 供給曲線の切片
供給曲線の切片は、供給曲線が価格軸(縦軸)と交わる点を指します。供給曲線は通常、次のような線形方程式で表されます:
ここで、
- Qsは供給量
- Pは価格
- cは供給曲線の切片
- dは価格に対する供給の変化率(傾き)
切片cは、価格がゼロのときの供給量を示します。つまり、価格がゼロの場合に供給者が提供する量です。この値は、供給曲線が価格軸と交わる点の供給量を表します。
例えば、供給曲線がQs = 10 + 3Pである場合、切片cは10です。これは、価格がゼロのときに供給量が10であることを意味します。
供給曲線の切片は、供給者の基本的な供給意欲を示し、価格が変動する際の供給の変化を理解するための重要な要素です。
4. 供給曲線の傾き
供給曲線の傾きは、価格の変化に対する供給量の変化を示す重要な指標です。供給曲線は通常、次のような線形方程式で表されます:
ここで、
- Qsは供給量
- Pは価格
- cは供給曲線の切片
- dは供給曲線の傾き
傾きdは、価格が1単位変化したときに供給量がどれだけ変化するかを示します。具体的には、傾きは次のように計算されます:
ここで、ΔQsは供給量の変化、ΔPは価格の変化です。
例えば、供給曲線がQs = 10 + 3Pである場合、傾きdは3です。これは、価格が1単位上昇すると供給量が3単位増加することを意味します。
傾きが大きいほど、価格の変化に対する供給の反応が大きくなります。逆に、傾きが小さい場合、価格の変化に対する供給の反応は小さくなります。
供給曲線の傾きは、価格弾力性の分析や市場の動向を理解するために重要な要素です。
'''
js = """
function createGradioAnimation() {
var container = document.createElement('div');
container.id = 'gradio-animation';
container.style.fontSize = '2em';
container.style.fontWeight = 'bold';
container.style.textAlign = 'center';
container.style.marginBottom = '20px';
var text = 'ダイナミック・プライシング';
for (var i = 0; i < text.length; i++) {
(function(i){
setTimeout(function(){
var letter = document.createElement('span');
var randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16);
letter.style.color = randomColor;
letter.style.opacity = '0';
letter.style.transition = 'opacity 0.5s';
letter.innerText = text[i];
container.appendChild(letter);
setTimeout(function() {
letter.style.opacity = '1';
}, 50);
}, i * 250);
})(i);
}
var gradioContainer = document.querySelector('.gradio-container');
gradioContainer.insertBefore(container, gradioContainer.firstChild);
return 'Animation created';
}
"""
def process_cohere(prompt):
if prompt == "":
return "プロンプトを入力してください。", "プロンプトは必須です。"
else:
system_message = """## あなたは、LLMのスペシャリストです。"""
prompt_message = prompt+" 結果をわかりやすく要約してください。"
messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": prompt_message},
]
# Step 2: Tool planning and calling
response = co.chat(
model="command-r-plus-08-2024",
messages=messages,
documents=cohere_doc
)
return response.message.content[0].text
def display_pdf(filename):
return filename
def download_pdf():
response = requests.get("https://www.ryhintl.com/dynamic-pricing.pdf")
file_path = "dynamic-pricing.pdf"
with open(file_path, "wb") as f:
f.write(response.content)
return file_path
def dyn_chart(p1,p2,p3,p4,p5):
# 需要曲線と供給曲線のパラメータ
a = p1 # 需要曲線の切片
b = p2 # 需要曲線の傾き
c = p3 # 供給曲線の切片
d = p4 # 供給曲線の傾き
# 価格の範囲
P = np.linspace(0, p5, p5)
# 需要曲線と供給曲線の計算
Q_d = a - b * P
Q_s = c + d * P
# 均衡点の計算
equilibrium_price = (a - c) / (b + d)
equilibrium_quantity = a - b * equilibrium_price
print(f"均衡価格: {equilibrium_price}")
print(f"均衡数量: {equilibrium_quantity}")
# グラフのプロット
pplot = f'''
import numpy as np
import matplotlib.pyplot as plt
import japanize_matplotlib
# 需要曲線と供給曲線のパラメータ
a = {p1} # 需要曲線の切片
b = {p2} # 需要曲線の傾き
c = {p3} # 供給曲線の切片
d = {p4} # 供給曲線の傾き
# 価格の範囲
P = np.linspace(0, {p5}, {p5})
# 需要曲線と供給曲線の計算
Q_d = a - b * P
Q_s = c + d * P
# 均衡点の計算
equilibrium_price = (a - c) / (b + d)
equilibrium_quantity = a - b * equilibrium_price
plt.figure(figsize=(10, 6))
plt.plot(P, Q_d, label='需要曲線')
plt.plot(P, Q_s, label='供給曲線')
plt.axvline(x={equilibrium_price}, color='r', linestyle='--', label='均衡価格')
plt.axhline(y={equilibrium_quantity}, color='r', linestyle='--', label='均衡数量')
plt.xlabel('価格')
plt.ylabel('数量')
plt.title('需要と供給の均衡点')
plt.legend()
plt.grid(True)
plt.savefig('plot.png')
plt.show()'''
return pplot
def load_css():
with open('theme.css', 'r') as file:
css_content = file.read()
return css_content
# 価格弾力性を計算する関数
def calculate_price_elasticity(prices, quantities):
# 価格と需要の変化率を計算
delta_p = np.diff(prices) / prices[:-1]
delta_q = np.diff(quantities) / quantities[:-1]
# 価格弾力性を計算
elasticity = delta_q / delta_p
return elasticity
# Gradioインターフェース用の関数
def gradio_calculate_price_elasticity(prices_str, quantities_str):
# 文字列を数値の配列に変換
prices = np.array([float(p) for p in prices_str.split(',')])
quantities = np.array([float(q) for q in quantities_str.split(',')])
# 価格弾力性を計算
price_elasticity = calculate_price_elasticity(prices, quantities)
# 結果を表示
results = []
for i, e in enumerate(price_elasticity):
results.append(f"価格 {prices[i]} から {prices[i+1]} への変化に対する価格弾力性: {e}")
# 平均価格弾力性を計算
average_elasticity = np.mean(price_elasticity)
results.append(f"平均価格弾力性: {average_elasticity}")
return "\n".join(results)
# 利潤を計算する関数
def calculate_profit(price, quantity, fixed_cost, variable_cost_per_unit):
# 総収入 (TR) を計算
total_revenue = price * quantity
print("Total revenue: ",total_revenue)
# 総費用 (TC) を計算
total_cost = (fixed_cost * quantity) + (variable_cost_per_unit * quantity)
print("Total cost: ",total_cost)
# 利潤 (π) を計算
profit = total_revenue - total_cost
print("Profit: ",profit)
return profit
# Gradioインターフェース用の関数
def gradio_calculate_profit(price, quantity, fixed_cost, variable_cost_per_unit):
profit = calculate_profit(int(price), int(quantity), int(fixed_cost), int(variable_cost_per_unit))
return f"利潤 (π): {profit}"
# 価格弾力性を用いて適正な価格を計算する関数
def calculate_optimal_price(current_price, current_quantity, price_elasticity, target_quantity):
# 価格弾力性の公式を利用して新しい価格を計算
optimal_price = current_price * (1 + (target_quantity - current_quantity) / (price_elasticity * current_quantity))
return optimal_price
# Gradioインターフェース用の関数
def gradio_calculate_optimal_price(current_price, current_quantity, price_elasticity, target_quantity):
optimal_price = calculate_optimal_price(current_price, current_quantity, price_elasticity, target_quantity)
return f"適正な価格: {optimal_price}"
# Custom CSS for the Groq badge and color scheme (feel free to edit however you wish)
custom_css = """
.gradio-container {
background-color: #f5f5f5;
}
.gr-button-primary {
background-color: #f55036 !important;
border-color: #f55036 !important;
}
.gr-button-secondary {
color: #f55036 !important;
border-color: #f55036 !important;
}
#groq-badge {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
}
"""
#with gr.Blocks(theme=gr.themes.Default()) as llm:
with gr.Blocks(css=load_css(),js=js,title="ダイナミック・プライシング",theme=gr.themes.Soft()) as llm:
with gr.Tab("価格弾力性"):
gr.Markdown("# 🗞️ 価格弾力性")
with gr.Row():
price_input = gr.Textbox(label="価格 (カンマ区切り)",value="100000, 120000, 140000, 160000, 180000")
demand_input = gr.Textbox(label="需要量 (カンマ区切り)",value="1000, 900, 800, 700, 600")
with gr.Row():
response_output = gr.Textbox(label="AIアシスタントの応答")
submit_button = gr.Button("価格弾力性プロセス", variant="primary")
# Add the Groq badge
gr.HTML("""
""")
submit_button.click(
gradio_calculate_price_elasticity,
inputs=[price_input, demand_input],
outputs=[response_output]
)
with gr.Tab("利潤"):
gr.Markdown("# 🗞️ 利潤")
with gr.Row():
price_input = gr.Number(label="価格",value="150000")
quantity_input = gr.Number(label="販売量",value="150")
fixed_input = gr.Number(label="固定費用",value="80000")
var_unit = gr.Number(label="単位あたりの変動費用",value="1000")
with gr.Row():
dynamic_output = gr.Textbox(label="AIアシスタントの応答")
submit_button = gr.Button("利潤プロセス", variant="primary")
submit_button.click(
gradio_calculate_profit,
inputs=[price_input,quantity_input,fixed_input,var_unit],
outputs=[dynamic_output]
)
# Add the Groq badge
gr.HTML("""
""")
with gr.Tab("適正価格"):
gr.Markdown("# 🗞️ 適正価格")
with gr.Row():
current_price_input = gr.Number(label="現在の価格",value=150000)
current_demand_input = gr.Number(label="現在の需要量",value=1000)
elasticity_input = gr.Number(label="価格弾力性",value=-1.5)
target_demand_input = gr.Number(label="目標とする需要量",value=1200)
with gr.Row():
price_output = gr.Textbox(label="AIアシスタントの応答")
submit_button = gr.Button("適正価格プロセス", variant="primary")
submit_button.click(
gradio_calculate_optimal_price,
inputs=[current_price_input,current_demand_input,elasticity_input,target_demand_input],
outputs=[price_output]
)
# Add the Groq badge
gr.HTML("""
""")
with gr.Tab("ダイナミック・プライシング"):
gr.Markdown("# 🗞️ ダイナミック・プライシング")
with gr.Row():
#logout_output = gr.Textbox(label="AIアシスタントの応答")
dyn_input1 = gr.Number(label="需要曲線の切片",value=100)
dyn_input2 = gr.Number(label="需要曲線の傾き",value=2)
dyn_input3 = gr.Number(label="供給曲線の切片",value=20)
dyn_input4 = gr.Number(label="供給曲線の傾き",value=1)
dyn_input5 = gr.Number(label="価格の範囲",value=10000)
logout_output = gr.HTML(label="AIアシスタントの応答")
submit_button = gr.Button("ダイナミック・プライシング", variant="primary")
submit_button.click(
dyn_chart,
inputs=[dyn_input1,dyn_input2,dyn_input3,dyn_input4,dyn_input5],
outputs=[logout_output]
)
gr.Markdown("""
## 使い方:
上記のPythonコードをコピーして、ファイル保存して実行してください。
""")
# Add the Groq badge
gr.HTML("""
""")
with gr.Tab("RAG"):
gr.Markdown("# 🗞️ RAG")
with gr.Row():
rag_input = gr.Textbox(label="プロンプト",value="最適価格導出のアプローチについて詳しく教えてください。")
with gr.Row():
rag_output = gr.Textbox(label="AIアシスタントの応答")
submit_button = gr.Button("RAGプロセス", variant="primary")
submit_button.click(
process_cohere,
inputs=[rag_input],
outputs=[rag_output]
)
# Add the Groq badge
gr.HTML("""
""")
with gr.Tab("解説"):
gr.Markdown("# 📄 解説")
with gr.Row():
#logout_output = gr.Textbox(label="AIアシスタントの応答")
gr.HTML(label="解説",value=setsumei)
with gr.Tab("資料"):
gr.Markdown("# 📄 資料")
with gr.Row():
if os.path.exists("./dynamic-pricing.pdf"):
pdf_output = PDF(label="資料",value="./dynamic-pricing.pdf")
else:
download_pdf()
pdf_output = PDF(label="資料",value="./dynamic-pricing.pdf")
#pdf = PDF(label="Upload PDF",visible=False)
#pdf_output = gr.File(visible=False)
#pdf_output = PDF(label="資料",value="./dynamic-pricing.pdf")
#pdf.upload(display_pdf, inputs=pdf, outputs=pdf_output)
llm.launch(share=True,pwa=True,favicon_path="favicon.ico")