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 = "
Your Portfolio Holdings
"
current_info_html += "Stock Code | Current Weight (%) | Current Value |
"
for stock_code, weight in sorted_stocks:
current_info_html += (
f""
f"{stock_code.upper()} | "
f"{weight:.1f}% | "
f"₩{current_values[stock_code]:,.0f} | "
f"
"
)
current_info_html += "
"
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"""
₩{total_value:,.0f} as of {current_time}
"""
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 = "Your Portfolio by Currency
"
currency_table += "Currency | Total Weight (%) | Total Value |
"
for currency, data in sorted_currencies:
currency_table += (
f""
f"{currency.upper()} | "
f"{data['weight'] * 100:.1f}% | "
f"₩{data['amount']:,} | "
f"
"
)
currency_table += "
"
result_message = portfolio_info + current_info_html + currency_table + "Re-Balancing Analysis
"
result_message += "Stock Code | Target Weight | Target Ratio (%) | Buy or Sell? | Trade Amount | Current Price per Share | Estimated # of Shares to Buy or Sell | Quantity of Units | Market Value | % Asset Allocation |
"
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"Buy"
elif trade_quantity < 0:
Buy_or_Sell = f"Sell"
else:
Buy_or_Sell = f""
price_str = f"₩{price:,.0f}" if stock_code != 'CASH' else ''
target_weight_str = f"{target_weight}" if stock_code != 'CASH' else ''
target_ratio_str = f"{target_ratio * 100:.1f}%" 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"{format_quantity(trade_value)}" if trade_value != 0 else ''
trade_quantity_str = (
f"{format_quantity(trade_quantity)}"
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""
f"{stock_code.upper()} | "
f"{target_weight_str} | "
f"{target_ratio_str} | "
f"{Buy_or_Sell} | "
f"{trade_value_str} | "
f"{price_str} | "
f"{trade_quantity_str} | "
f"{old_quantity_str} | "
f"{new_value_str} | "
f"{new_value_pct_str} | "
f"
"
)
result_message += "
"
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'
'
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"{current_return:+,.2f}%"
elif current_return < 0:
current_return_class = f"{current_return:,.2f}%"
else:
current_return_class = f"0"
new_return_class = ""
if new_return > 0:
new_return_class = f"{new_return:+,.2f}%"
elif current_return < 0:
new_return_class = f"{new_return:,.2f}%"
else:
new_return_class = f"0"
# Construct the HTML string with the appropriate class
result_html = css+ f"""
Average Price
{new_avg_price:,.0f}
Total Quantity
{total_shares:,.0f}
Total Investment
{total_investment:,.0f}
{current_return_class}
{old_avg_price:,.0f}
➜
{new_return_class}
{new_avg_price:,.0f}
총 추가 금액: {additional_investment:,.0f}
"""
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)