mytest_app / app.py
cryman38's picture
Upload app.py
a0138b8 verified
import math
import requests
from bs4 import BeautifulSoup
import FinanceDataReader as fdr
import ssl
import io
import base64
import gradio as gr
import matplotlib.pyplot as plt
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
import pytz
import yfinance as yf
from datetime import datetime, timedelta # timedelta μΆ”κ°€
import gradio as gr
from gradio.components import Dataset
import matplotlib.pyplot as plt
import FinanceDataReader as fdr
import gradio as gr
import pandas as pd
from concurrent.futures import ThreadPoolExecutor, as_completed
import io
import base64
# ν•œκ΅­ ν‘œμ€€μ‹œ (KST) μ‹œκ°„λŒ€ μ„€μ •
kst = pytz.timezone('Asia/Seoul')
# SSL μΈμ¦μ„œ 검증 λΉ„ν™œμ„±ν™”
ssl._create_default_https_context = ssl._create_unverified_context
def parse_input(text, cash_amount, cash_ratio):
lines = text.strip().split(',')
stock_inputs = []
total_target_weight = 0
for line in lines:
parts = line.split()
if len(parts) == 4:
stock_code, currency_code, quantity_expr, target_weight_expr = parts
quantity = math.floor(eval(quantity_expr.replace(' ', '')))
target_weight = eval(target_weight_expr.replace(' ', ''))
target_ratio = (1 - cash_ratio / 100) * target_weight
stock_inputs.append((currency_code, stock_code, quantity, target_weight, target_ratio))
total_target_weight += target_weight
cash_amount = math.floor(cash_amount) if cash_amount else 0
krw_cash = {'amount': cash_amount, 'target_weight': cash_ratio / 100.0}
stock_total_weight = total_target_weight
for i in range(len(stock_inputs)):
stock_inputs[i] = (stock_inputs[i][0], stock_inputs[i][1], stock_inputs[i][2], stock_inputs[i][3], (1 - krw_cash['target_weight']) * stock_inputs[i][3] / stock_total_weight)
return stock_inputs, krw_cash
def get_exchange_rate(currency_code):
if currency_code.lower() == 'krw':
return 1.0
ticker = f"{currency_code.upper()}KRW=X"
data = yf.download(ticker, period='1d')
if not data.empty:
return data['Close'].iloc[0]
else:
raise ValueError("Failed to retrieve exchange rate data.")
def get_exchange_reflected_stock_price(stock_code, currency_code):
new_price = get_current_stock_price(stock_code)
exchange_rate = get_exchange_rate(currency_code)
return math.floor(new_price * exchange_rate)
def get_current_stock_price(stock_code):
df = fdr.DataReader(stock_code)
return df['Close'].iloc[-1]
def build_portfolio(stock_inputs, krw_cash):
portfolio = {}
target_weights = {}
with ThreadPoolExecutor() as executor:
results = executor.map(lambda x: (x[1], get_exchange_reflected_stock_price(x[1], x[0]), x[2], x[3], x[4], x[0]), stock_inputs)
for stock_code, new_price, quantity, target_weight, target_ratio, currency_code in results:
portfolio[stock_code] = {'quantity': quantity, 'price': new_price, 'target_weight': target_weight, 'currency': currency_code}
target_weights[stock_code] = target_ratio
return portfolio, target_weights, krw_cash
def format_quantity(quantity):
if quantity < 0:
return f"({-quantity:,})"
else:
return f"{quantity:,}"
def get_portfolio_rebalancing_info(portfolio, target_weights, krw_cash):
with open('portfolio.html', 'r', encoding='utf-8') as file:
css = file.read()
kst = pytz.timezone('Asia/Seoul')
current_time = datetime.now(kst).strftime("%I:%M %p %b-%d-%Y")
total_value = sum(stock['price'] * stock['quantity'] for stock in portfolio.values()) + krw_cash['amount']
total_new_stock_value = 0
total_trade_value = 0
adjustments = []
# Calculate current weights and values
current_weights = {stock_code: (stock['price'] * stock['quantity'] / total_value) * 100 for stock_code, stock in portfolio.items()}
current_values = {stock_code: stock['price'] * stock['quantity'] for stock_code, stock in portfolio.items()}
# Include cash in current weights and values
current_weights['CASH'] = (krw_cash['amount'] / total_value) * 100
current_values['CASH'] = krw_cash['amount']
# Sort stocks by current weight in descending order
sorted_stocks = sorted(current_weights.items(), key=lambda x: x[1], reverse=True)
# Display current weights and values section
current_info_html = "<h3>Your Portfolio Holdings</h3><div class='table-container'><table style='border-collapse: collapse;'>"
current_info_html += "<thead><tr><th style='border: 1px hidden #ddd; text-align: center;'>Stock Code</th><th style='border: 1px hidden #ddd; text-align: center;'>Current Weight (%)</th><th style='border: 1px hidden #ddd; text-align: center;'>Current Value</th></tr></thead><tbody>"
for stock_code, weight in sorted_stocks:
current_info_html += (
f"<tr>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{stock_code.upper()}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{weight:.1f}%</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>β‚©{current_values[stock_code]:,.0f}</td>"
f"</tr>"
)
current_info_html += "</tbody></table></div><br>"
for stock_code, stock_data in portfolio.items():
current_value = stock_data['price'] * stock_data['quantity']
target_value = total_value * target_weights.get(stock_code, 0)
difference = target_value - current_value
trade_quantity = math.floor(difference / stock_data['price']) if difference > 0 else -math.ceil(-difference / stock_data['price'])
new_quantity = trade_quantity + stock_data['quantity']
new_value = new_quantity * stock_data['price']
trade_value = trade_quantity * stock_data['price']
total_trade_value += abs(trade_value)
total_new_stock_value += new_value
current_value_pct = (current_value / total_value) * 100
new_value_pct = (new_value / total_value) * 100
adjustments.append((difference, current_value, target_value, current_value_pct, trade_quantity, stock_code, stock_data['price'], new_value, trade_value, stock_data['quantity'], new_quantity, target_weights[stock_code], new_value_pct, stock_data['target_weight'], stock_data['currency']))
krw_new_amount = total_value - total_new_stock_value
krw_target_value = total_value * krw_cash['target_weight']
krw_difference = krw_new_amount - krw_cash['amount']
trade_quantity = krw_difference
new_quantity = krw_cash['amount'] + trade_quantity
new_value = new_quantity
trade_value = trade_quantity
current_value = krw_cash['amount']
current_value_pct = (current_value / total_value) * 100
new_value_pct = (new_value / total_value) * 100
adjustments.append((krw_difference, current_value, krw_target_value, current_value_pct, trade_quantity, 'CASH', 1, new_value, trade_value, krw_cash['amount'], new_quantity, krw_cash['target_weight'], new_value_pct, '', 'KRW'))
portfolio_info = css + f"""
<div><br>
<p><span style='font-size: 1.6rem; font-weight: bold;'>β‚©{total_value:,.0f}</span> as of <span style='color: #6e6e73;'>{current_time}</span></p>
<br></div>
"""
currency_totals = {stock_data['currency']: {'amount': 0, 'weight': 0} for stock_data in portfolio.values()}
for stock_code, stock_data in portfolio.items():
currency = stock_data['currency']
current_value = stock_data['price'] * stock_data['quantity']
currency_totals[currency]['amount'] += current_value
currency_totals[currency]['weight'] += current_value / total_value
currency_totals['CASH'] = {'amount': krw_cash['amount'], 'weight': krw_cash['amount'] / total_value}
sorted_currencies = sorted(currency_totals.items(), key=lambda x: x[1]['weight'], reverse=True)
currency_table = "<h3>Your Portfolio by Currency</h3><div class='table-container'><table style='border-collapse: collapse;'>"
currency_table += "<thead><tr><th style='border: 1px hidden #ddd; text-align: center;'>Currency</th><th style='border: 1px hidden #ddd; text-align: center;'>Total Weight (%)</th><th style='border: 1px hidden #ddd; text-align: center;'>Total Value</th></tr></thead><tbody>"
for currency, data in sorted_currencies:
currency_table += (
f"<tr>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{currency.upper()}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{data['weight'] * 100:.1f}%</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>β‚©{data['amount']:,}</td>"
f"</tr>"
)
currency_table += "</tbody></table></div><br>"
result_message = portfolio_info + current_info_html + currency_table + "<h3>Re-Balancing Analysis</h3><div class='table-container'><table style='border-collapse: collapse;'>"
result_message += "<thead><tr><th style='border: 1px hidden #ddd; text-align: center;'>Stock Code</th><th style='border: 1px hidden #ddd; text-align: center;'>Target Weight</th><th style='border: 1px hidden #ddd; text-align: center;'>Target Ratio (%)</th><th style='border: 1px hidden #ddd; text-align: center;'>Buy or Sell?</th><th style='border: 1px hidden #ddd; text-align: center;'>Trade Amount</th><th style='border: 1px hidden #ddd; text-align: center;'>Current Price per Share</th><th style='border: 1px hidden #ddd; text-align: center;'>Estimated # of<br> Shares to Buy or Sell</th><th style='border: 1px hidden #ddd; text-align: center;'>Quantity of Units</th><th style='border: 1px hidden #ddd; text-align: center;'>Market Value</th><th style='border: 1px hidden #ddd; text-align: center;'>% Asset Allocation</th></tr></thead><tbody>"
for adj in adjustments:
difference, current_value, target_value, current_value_pct, trade_quantity, stock_code, price, new_value, trade_value, old_quantity, new_quantity, target_ratio, new_value_pct, target_weight, currency = adj
Buy_or_Sell = ""
if trade_quantity > 0:
Buy_or_Sell = f"<span class='buy-sell buy'>Buy</span>"
elif trade_quantity < 0:
Buy_or_Sell = f"<span class='buy-sell sell'>Sell</span>"
else:
Buy_or_Sell = f"<span></span>"
price_str = f"β‚©{price:,.0f}" if stock_code != 'CASH' else ''
target_weight_str = f"<span class='highlight-edit'>{target_weight}</span>" if stock_code != 'CASH' else ''
target_ratio_str = f"<span class='highlight-edit'>{target_ratio * 100:.1f}%</span>" if stock_code == 'CASH' else f"{target_ratio * 100:.1f}%"
old_quantity_str = f"{old_quantity:,.0f} β†’ {new_quantity:,.0f}" if stock_code != 'CASH' else ''
trade_value_str = f"<span class='highlight-sky'>{format_quantity(trade_value)}</span>" if trade_value != 0 else ''
trade_quantity_str = (
f"<span class='highlight-sky'>{format_quantity(trade_quantity)}</span>"
if stock_code != 'CASH' and trade_value != 0 else ''
)
new_value_str = f"β‚©{new_value:,.0f}"
new_value_pct_str = f"{new_value_pct:.1f}%"
result_message += (
f"<tr>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{stock_code.upper()}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{target_weight_str}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{target_ratio_str}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{Buy_or_Sell}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{trade_value_str}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{price_str}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{trade_quantity_str}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{old_quantity_str}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{new_value_str}</td>"
f"<td style='border: 1px hidden #ddd; text-align: center;'>{new_value_pct_str}</td>"
f"</tr>"
)
result_message += "</tbody></table></div>"
return result_message
def rebalancing_tool(user_input, cash_amount, cash_ratio):
try:
stock_inputs, krw_cash = parse_input(user_input, cash_amount, cash_ratio)
portfolio, target_weights, krw_cash = build_portfolio(stock_inputs, krw_cash)
result = get_portfolio_rebalancing_info(portfolio, target_weights, krw_cash)
return result
except Exception as e:
return str(e)
def get_stock_prices(stock_code, days):
try:
df = fdr.DataReader(stock_code, end=pd.Timestamp.now().date(), data_source='yahoo')
df = df[df.index >= df.index.max() - pd.DateOffset(days=days)] # 졜근 days일 λ°μ΄ν„°λ‘œ μ œν•œ
return df['Close']
except Exception as e:
print(f"Failed to fetch data for {stock_code}: {e}")
return None
def plot_stock_prices(stock_codes, days):
# 주식 κ·Έλž˜ν”„ 생성을 μœ„ν•œ 병렬 처리
stock_prices = {}
with ThreadPoolExecutor() as executor:
futures = {executor.submit(get_stock_prices, stock_code.strip(), int(days)): stock_code.strip() for stock_code in stock_codes.split(',')}
for future in as_completed(futures):
stock_code = futures[future]
try:
prices = future.result()
if prices is not None:
stock_prices[stock_code] = prices
except Exception as e:
print(f"Failed to fetch data for {stock_code}: {e}")
# 각 주식에 λŒ€ν•œ κ·Έλž˜ν”„λ₯Ό κ·Έλ¦Ό
plt.figure(figsize=(10, 6))
for stock_code, prices in stock_prices.items():
relative_prices = prices / prices.iloc[0] # 첫 번째 데이터 포인트λ₯Ό κΈ°μ€€μœΌλ‘œ μƒλŒ€μ  가격 계산
plt.plot(prices.index, relative_prices, label=stock_code.upper()) # 주식 μ½”λ“œλ₯Ό λŒ€λ¬Έμžλ‘œ ν‘œμ‹œ
plt.xlabel('Date')
plt.ylabel('Relative Price (Normalized to 1)')
plt.title(f'Relative Stock Prices Over the Last {days} Days')
plt.legend()
# κ·Έλž˜ν”„λ₯Ό HTML둜 λ³€ν™˜ν•˜μ—¬ λ°˜ν™˜
html_graph = io.BytesIO()
plt.savefig(html_graph, format='png', dpi=300)
html_graph.seek(0)
graph_encoded = base64.b64encode(html_graph.getvalue()).decode()
graph_html = f'<img src="data:image/png;base64,{graph_encoded}"/>'
return graph_html
def cost_averaging(old_avg_price, old_quantity, new_price, new_quantity):
# μž…λ ₯값을 숫자둜 λ³€ν™˜
old_avg_price = float(old_avg_price) if old_avg_price else 0.0
old_quantity = float(old_quantity) if old_quantity else 0.0
new_price = float(new_price) if new_price else 0.0
new_quantity = float(new_quantity) if new_quantity else 0.0
# ν˜„μž¬ 투자 κΈˆμ•‘ 계산
current_investment = old_avg_price * old_quantity
# μΆ”κ°€ 투자 κΈˆμ•‘ 계산
additional_investment = new_price * new_quantity
# 총 투자 κΈˆμ•‘
total_investment = current_investment + additional_investment
# 총 주식 수
total_shares = old_quantity + new_quantity
# μƒˆ 평균 가격 계산
new_avg_price = total_investment / total_shares if total_shares != 0 else 0.0
# ν˜„μž¬ 수읡λ₯  계산
current_return = (new_price - old_avg_price) / old_avg_price * 100 if old_avg_price != 0 else 0.0
# μƒˆλ‘œμš΄ 수읡λ₯  계산
new_return = (new_price / new_avg_price - 1 ) * 100 if new_avg_price != 0 else 0.0
return new_avg_price, total_shares, total_investment, current_return, new_return, additional_investment
def gradio_cost_averaging(old_avg_price, old_quantity, new_price, new_quantity):
with open('portfolio.html', 'r', encoding='utf-8') as file:
css = file.read()
# μž…λ ₯값을 숫자둜 λ³€ν™˜
old_avg_price = float(old_avg_price) if old_avg_price else 0.0
old_quantity = float(old_quantity) if old_quantity else 0.0
new_price = float(new_price) if new_price else 0.0
new_quantity = float(new_quantity) if new_quantity else 0.0
new_avg_price, total_shares, total_investment, current_return, new_return, additional_investment = cost_averaging(old_avg_price, old_quantity, new_price, new_quantity)
current_return_class = ""
if current_return > 0:
current_return_class = f"<span style='color: #4caf50; font-weight: bold;'>{current_return:+,.2f}%</span>"
elif current_return < 0:
current_return_class = f"<span style='color: #f44336; font-weight: bold;'>{current_return:,.2f}%</span>"
else:
current_return_class = f"<span><strong>0</strong></span>"
new_return_class = ""
if new_return > 0:
new_return_class = f"<span style='color: #4caf50; font-weight: bold;'>{new_return:+,.2f}%</span>"
elif current_return < 0:
new_return_class = f"<span style='color: #f44336; font-weight: bold;'>{new_return:,.2f}%</span>"
else:
new_return_class = f"<span><strong>0</strong></span>"
# Construct the HTML string with the appropriate class
result_html = css+ f"""
<div style="box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); border-radius: 8px; padding: 48px; position: relative; width: 100%; padding: 24px;">
<div>
<div style="margin-bottom: 24px;">
<div style="font-size: 24px; margin-bottom: 24px;">Average Price</div>
<div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
<span></span>
<span>{new_avg_price:,.0f}</span>
</div>
<hr style="margin: 24px 0;">
</div>
</div>
<div>
<div style="margin-bottom: 24px;">
<div style="font-size: 24px; margin-bottom: 24px;">Total Quantity</div>
<div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
<span>{total_shares:,.0f}</span>
</div>
<hr style="margin: 24px 0;">
</div>
</div>
<div>
<div style="margin-bottom: 24px;">
<div style="font-size: 24px; margin-bottom: 24px;">Total Investment</div>
<div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
<span></span>
<span>{total_investment:,.0f}</span>
</div>
<hr style="margin: 24px 0;">
</div>
</div>
<div style='display: flex; justify-content: space-around; align-items: center;'>
<div style='text-align: center;'>
<div style="margin-bottom: 24px;">
<div style="font-size: 24px; margin-bottom: 24px;"></div>
<div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
<p></p>
<p>{current_return_class}</p>
<p>{old_avg_price:,.0f}</p>
</div>
</div>
</div>
<div style='text-align: center; margin-bottom: 24px; font-size: 24px;'>➜</div>
<div style='text-align: center;'>
<div style="margin-bottom: 24px;">
<div style="font-size: 24px; margin-bottom: 24px;"></div>
<div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
<p></p>
<p>{new_return_class}</p>
<p>{new_avg_price:,.0f}</p>
</div>
</div>
</div>
</div>
<p style='text-align: center;'>총 μΆ”κ°€ κΈˆμ•‘: <strong>{additional_investment:,.0f}</strong></p>
</div>
"""
return result_html
# Define the interface for the Portfolio tab
def portfolio_interface(input_text, cash_amount, cash_ratio):
result = rebalancing_tool(input_text, cash_amount, cash_ratio)
return result
portfolio_inputs = [
gr.Textbox(label="πŸ”₯ Holdings", lines=2, placeholder="Format: [stock code currency quantity target weight, ...]"),
gr.Number(label="πŸͺ΅ Cash", value=""),
gr.Slider(label="βš–οΈ Cash Ratio (%)", minimum=0, maximum=100, step=1)
]
portfolio_interface = gr.Interface(
fn=portfolio_interface,
inputs=portfolio_inputs,
outputs=gr.HTML(),
# examples = [
# ["458730 krw 571 8,\n368590 krw 80 2", 17172, 0],
# ["SCHD USD 400 8,\nQQQ USD 40 2", 1000000, 25],
# ["458730 krw 571 8,\n368590 krw 80 2,\nSCHD USD 400 8,\nQQQ USD 40 2", 1000000, 25]
# ],
live=True
)
# Define the interface for the Compare tab
def compare_interface(stock_codes, period):
result = plot_stock_prices(stock_codes, period)
return result
compare_inputs = [
gr.Textbox(label="πŸ“ˆ Stock Codes", lines=2, placeholder="Enter stock codes separated by comma (e.g., AAPL,GOOGL,MSFT)"),
gr.Number(label="πŸ“† Period (days)", value=90)
]
compare_interface = gr.Interface(
fn=compare_interface,
inputs=compare_inputs,
outputs=gr.HTML(),
# examples = [
# ["SCHD,QQQ", 90],
# ["458730,368590", 90],
# ["AAPL,GOOGL,MSFT", 90]
# ],
live=False
)
# Define the interface for the Cost Averaging tab
def cost_averaging_interface(old_avg_price, old_quantity, new_price, new_quantity):
result = gradio_cost_averaging(old_avg_price, old_quantity, new_price, new_quantity)
return result
cost_averaging_inputs = [
gr.Number(label="Old Price", value=""),
gr.Number(label="Quantity", value=""),
gr.Number(label="New Price", value=""),
gr.Number(label="Quantity", value="")
]
cost_averaging_interface = gr.Interface(
fn=cost_averaging_interface,
inputs=cost_averaging_inputs,
outputs=gr.HTML(),
# examples = [
# [78.15, 6.024272, 77.11, 1]
# ],
live=True
)
# Combine all interfaces into a tabbed interface
with gr.Blocks(css='style.css') as demo:
with gr.Column(elem_id="col-container"):
with gr.Tabs():
with gr.TabItem("Portfolio"):
portfolio_interface.render()
with gr.TabItem("Compare"):
compare_interface.render()
with gr.TabItem("Cost Averaging"):
cost_averaging_interface.render()
with gr.TabItem("πŸ“„ About"):
gr.Markdown("""
# About This Application
Welcome to the Portfolio Management Tool! This application provides a comprehensive suite of tools to help you manage and analyze your investment portfolio. Below is a brief overview of each feature available in this tool.
## πŸ“Š Portfolio
**Description:**
This section allows you to analyze and rebalance your investment portfolio. You can input your current holdings, cash amount, and desired cash ratio, and the tool will calculate the necessary trades to achieve your target allocation.
**How to Use:**
1. Enter your holdings in the format: `[stock code currency quantity target weight]`.
2. Specify your cash amount and desired cash ratio.
3. Click the "Analyze Data" button to see the rebalancing analysis.
4. View the detailed breakdown of your current portfolio and suggested trades.
## πŸ“ˆ Compare
**Description:**
This feature enables you to compare the historical prices of multiple stocks over a specified period. It provides a visual comparison to help you understand the performance of different stocks.
**How to Use:**
1. Enter the stock codes separated by commas (e.g., AAPL, GOOGL, MSFT).
2. Specify the period in days for which you want to compare the stock prices.
3. Click the "Compare Stock Prices" button to generate the comparison graph.
4. View the relative price changes of the selected stocks over the chosen period.
## πŸ’Ή Cost Averaging
**Description:**
This section helps you calculate the new average price of a stock when you make additional purchases. It also provides insights into the current and new return rates based on your investments.
**How to Use:**
1. Enter the average price and quantity of your initial purchase in the "First Purchase" section.
2. Enter the price and quantity of your subsequent purchase in the "Second Purchase" section.
3. Click the "Calculate Cost Averaging" button to see the results.
4. View the new average price, total quantity, total investment, and return rates.
## πŸ“„ About
**Description:**
This section provides an overview of the application, explaining its features and how to use them. It serves as a guide for new users to understand the functionalities available in the tool.
**How to Use:**
Simply read through the information provided to get acquainted with the application's capabilities.
## Disclaimer
Please note that this tool is for informational purposes only and does not constitute financial advice. Always conduct your own research or consult with a financial advisor before making investment decisions.
---
We hope you find this tool useful for managing your investments. If you have any feedback or suggestions, feel free to reach out!
Happy Investing!
""")
demo.launch(share=True)