cryman38 commited on
Commit
db90530
Β·
verified Β·
1 Parent(s): 8ed2a14

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +535 -27
app.py CHANGED
@@ -1,32 +1,540 @@
 
 
 
 
 
 
 
1
  import gradio as gr
2
- import shutil
3
- import os
4
- import csv
5
-
6
- # CSV ν•„λ“œ 크기 μ œν•œ 늘리기
7
- csv.field_size_limit(10**6)
8
-
9
- # μΊμ‹œ 파일 μ‚­μ œ ν•¨μˆ˜
10
- def clear_cache():
11
- cache_dir_14 = "/home/user/app/gradio_cached_examples/14"
12
- cache_dir_28 = "/home/user/app/gradio_cached_examples/28"
13
-
14
- removed_dirs = []
15
- for cache_dir in [cache_dir_14, cache_dir_28]:
16
- if os.path.exists(cache_dir):
17
- shutil.rmtree(cache_dir)
18
- removed_dirs.append(f"{cache_dir} has been removed.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  else:
20
- removed_dirs.append(f"{cache_dir} does not exist.")
21
- return "\n".join(removed_dirs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- # Gradio μΈν„°νŽ˜μ΄μŠ€
24
- with gr.Blocks() as demo:
25
- gr.Markdown("## Gradio Cache Cleaner")
26
- clear_button = gr.Button("Clear Cache")
27
- output = gr.Textbox()
28
 
29
- clear_button.click(fn=clear_cache, outputs=output)
 
30
 
31
- if __name__ == "__main__":
32
- demo.launch()
 
1
+ import math
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import FinanceDataReader as fdr
5
+ import ssl
6
+ import io
7
+ import base64
8
  import gradio as gr
9
+ import matplotlib.pyplot as plt
10
+ from datetime import datetime
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ import pytz
13
+ import yfinance as yf
14
+ from datetime import datetime, timedelta # timedelta μΆ”κ°€
15
+ import gradio as gr
16
+ from gradio.components import Dataset
17
+ import matplotlib.pyplot as plt
18
+ import FinanceDataReader as fdr
19
+ import gradio as gr
20
+ import pandas as pd
21
+ from concurrent.futures import ThreadPoolExecutor, as_completed
22
+ import io
23
+ import base64
24
+
25
+
26
+
27
+ # ν•œκ΅­ ν‘œμ€€μ‹œ (KST) μ‹œκ°„λŒ€ μ„€μ •
28
+ kst = pytz.timezone('Asia/Seoul')
29
+
30
+ # SSL μΈμ¦μ„œ 검증 λΉ„ν™œμ„±ν™”
31
+ ssl._create_default_https_context = ssl._create_unverified_context
32
+
33
+ def parse_input(text, cash_amount, cash_ratio):
34
+ lines = text.strip().split(',')
35
+ stock_inputs = []
36
+ total_target_weight = 0
37
+
38
+ for line in lines:
39
+ parts = line.split()
40
+ if len(parts) == 4:
41
+ stock_code, currency_code, quantity_expr, target_weight_expr = parts
42
+ quantity = math.floor(eval(quantity_expr.replace(' ', '')))
43
+ target_weight = eval(target_weight_expr.replace(' ', ''))
44
+ target_ratio = (1 - cash_ratio / 100) * target_weight
45
+ stock_inputs.append((currency_code, stock_code, quantity, target_weight, target_ratio))
46
+ total_target_weight += target_weight
47
+
48
+ cash_amount = math.floor(cash_amount) if cash_amount else 0
49
+ krw_cash = {'amount': cash_amount, 'target_weight': cash_ratio / 100.0}
50
+
51
+ stock_total_weight = total_target_weight
52
+
53
+ for i in range(len(stock_inputs)):
54
+ 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)
55
+
56
+ return stock_inputs, krw_cash
57
+
58
+ def get_exchange_rate(currency_code):
59
+ if currency_code.lower() == 'krw':
60
+ return 1.0
61
+
62
+ ticker = f"{currency_code.upper()}KRW=X"
63
+ data = yf.download(ticker, period='1d')
64
+ if not data.empty:
65
+ return data['Close'].iloc[0]
66
+ else:
67
+ raise ValueError("Failed to retrieve exchange rate data.")
68
+
69
+ def get_exchange_reflected_stock_price(stock_code, currency_code):
70
+ new_price = get_current_stock_price(stock_code)
71
+ exchange_rate = get_exchange_rate(currency_code)
72
+ return math.floor(new_price * exchange_rate)
73
+
74
+ def get_current_stock_price(stock_code):
75
+ df = fdr.DataReader(stock_code)
76
+ return df['Close'].iloc[-1]
77
+
78
+ def build_portfolio(stock_inputs, krw_cash):
79
+ portfolio = {}
80
+ target_weights = {}
81
+
82
+ with ThreadPoolExecutor() as executor:
83
+ 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)
84
+
85
+ for stock_code, new_price, quantity, target_weight, target_ratio, currency_code in results:
86
+ portfolio[stock_code] = {'quantity': quantity, 'price': new_price, 'target_weight': target_weight, 'currency': currency_code}
87
+ target_weights[stock_code] = target_ratio
88
+
89
+ return portfolio, target_weights, krw_cash
90
+
91
+ def format_quantity(quantity):
92
+ if quantity < 0:
93
+ return f"({-quantity:,})"
94
+ else:
95
+ return f"{quantity:,}"
96
+
97
+ def get_portfolio_rebalancing_info(portfolio, target_weights, krw_cash):
98
+ with open('portfolio.html', 'r', encoding='utf-8') as file:
99
+ css = file.read()
100
+
101
+ kst = pytz.timezone('Asia/Seoul')
102
+ current_time = datetime.now(kst).strftime("%I:%M %p %b-%d-%Y")
103
+
104
+ total_value = sum(stock['price'] * stock['quantity'] for stock in portfolio.values()) + krw_cash['amount']
105
+ total_new_stock_value = 0
106
+ total_trade_value = 0
107
+ adjustments = []
108
+
109
+ # Calculate current weights and values
110
+ current_weights = {stock_code: (stock['price'] * stock['quantity'] / total_value) * 100 for stock_code, stock in portfolio.items()}
111
+ current_values = {stock_code: stock['price'] * stock['quantity'] for stock_code, stock in portfolio.items()}
112
+
113
+ # Include cash in current weights and values
114
+ current_weights['CASH'] = (krw_cash['amount'] / total_value) * 100
115
+ current_values['CASH'] = krw_cash['amount']
116
+
117
+ # Sort stocks by current weight in descending order
118
+ sorted_stocks = sorted(current_weights.items(), key=lambda x: x[1], reverse=True)
119
+
120
+ # Display current weights and values section
121
+ current_info_html = "<h3>Your Portfolio Holdings</h3><div class='table-container'><table style='border-collapse: collapse;'>"
122
+ 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>"
123
+ for stock_code, weight in sorted_stocks:
124
+ current_info_html += (
125
+ f"<tr>"
126
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{stock_code.upper()}</td>"
127
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{weight:.1f}%</td>"
128
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>β‚©{current_values[stock_code]:,.0f}</td>"
129
+ f"</tr>"
130
+ )
131
+ current_info_html += "</tbody></table></div><br>"
132
+
133
+ for stock_code, stock_data in portfolio.items():
134
+ current_value = stock_data['price'] * stock_data['quantity']
135
+ target_value = total_value * target_weights.get(stock_code, 0)
136
+ difference = target_value - current_value
137
+ trade_quantity = math.floor(difference / stock_data['price']) if difference > 0 else -math.ceil(-difference / stock_data['price'])
138
+ new_quantity = trade_quantity + stock_data['quantity']
139
+ new_value = new_quantity * stock_data['price']
140
+ trade_value = trade_quantity * stock_data['price']
141
+ total_trade_value += abs(trade_value)
142
+ total_new_stock_value += new_value
143
+ current_value_pct = (current_value / total_value) * 100
144
+ new_value_pct = (new_value / total_value) * 100
145
+
146
+ 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']))
147
+
148
+ krw_new_amount = total_value - total_new_stock_value
149
+ krw_target_value = total_value * krw_cash['target_weight']
150
+ krw_difference = krw_new_amount - krw_cash['amount']
151
+ trade_quantity = krw_difference
152
+ new_quantity = krw_cash['amount'] + trade_quantity
153
+ new_value = new_quantity
154
+ trade_value = trade_quantity
155
+ current_value = krw_cash['amount']
156
+ current_value_pct = (current_value / total_value) * 100
157
+ new_value_pct = (new_value / total_value) * 100
158
+
159
+ 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'))
160
+
161
+ portfolio_info = css + f"""
162
+ <div><br>
163
+ <p><span style='font-size: 1.6rem; font-weight: bold;'>β‚©{total_value:,.0f}</span> as of <span style='color: #6e6e73;'>{current_time}</span></p>
164
+ <br></div>
165
+ """
166
+
167
+ currency_totals = {stock_data['currency']: {'amount': 0, 'weight': 0} for stock_data in portfolio.values()}
168
+
169
+ for stock_code, stock_data in portfolio.items():
170
+ currency = stock_data['currency']
171
+ current_value = stock_data['price'] * stock_data['quantity']
172
+ currency_totals[currency]['amount'] += current_value
173
+ currency_totals[currency]['weight'] += current_value / total_value
174
+
175
+ currency_totals['CASH'] = {'amount': krw_cash['amount'], 'weight': krw_cash['amount'] / total_value}
176
+ sorted_currencies = sorted(currency_totals.items(), key=lambda x: x[1]['weight'], reverse=True)
177
+
178
+ currency_table = "<h3>Your Portfolio by Currency</h3><div class='table-container'><table style='border-collapse: collapse;'>"
179
+ 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>"
180
+
181
+ for currency, data in sorted_currencies:
182
+ currency_table += (
183
+ f"<tr>"
184
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{currency.upper()}</td>"
185
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{data['weight'] * 100:.1f}%</td>"
186
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>β‚©{data['amount']:,}</td>"
187
+ f"</tr>"
188
+ )
189
+
190
+ currency_table += "</tbody></table></div><br>"
191
+
192
+ result_message = portfolio_info + current_info_html + currency_table + "<h3>Re-Balancing Analysis</h3><div class='table-container'><table style='border-collapse: collapse;'>"
193
+ 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>"
194
+
195
+ for adj in adjustments:
196
+ 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
197
+ Buy_or_Sell = ""
198
+ if trade_quantity > 0:
199
+ Buy_or_Sell = f"<span class='buy-sell buy'>Buy</span>"
200
+ elif trade_quantity < 0:
201
+ Buy_or_Sell = f"<span class='buy-sell sell'>Sell</span>"
202
  else:
203
+ Buy_or_Sell = f"<span></span>"
204
+
205
+ price_str = f"β‚©{price:,.0f}" if stock_code != 'CASH' else ''
206
+ target_weight_str = f"<span class='highlight-edit'>{target_weight}</span>" if stock_code != 'CASH' else ''
207
+ target_ratio_str = f"<span class='highlight-edit'>{target_ratio * 100:.1f}%</span>" if stock_code == 'CASH' else f"{target_ratio * 100:.1f}%"
208
+ old_quantity_str = f"{old_quantity:,.0f} β†’ {new_quantity:,.0f}" if stock_code != 'CASH' else ''
209
+ trade_value_str = f"<span class='highlight-sky'>{format_quantity(trade_value)}</span>" if trade_value != 0 else ''
210
+ trade_quantity_str = (
211
+ f"<span class='highlight-sky'>{format_quantity(trade_quantity)}</span>"
212
+ if stock_code != 'CASH' and trade_value != 0 else ''
213
+ )
214
+ new_value_str = f"β‚©{new_value:,.0f}"
215
+ new_value_pct_str = f"{new_value_pct:.1f}%"
216
+
217
+ result_message += (
218
+ f"<tr>"
219
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{stock_code.upper()}</td>"
220
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{target_weight_str}</td>"
221
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{target_ratio_str}</td>"
222
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{Buy_or_Sell}</td>"
223
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{trade_value_str}</td>"
224
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{price_str}</td>"
225
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{trade_quantity_str}</td>"
226
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{old_quantity_str}</td>"
227
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{new_value_str}</td>"
228
+ f"<td style='border: 1px hidden #ddd; text-align: center;'>{new_value_pct_str}</td>"
229
+ f"</tr>"
230
+ )
231
+
232
+ result_message += "</tbody></table></div>"
233
+
234
+ return result_message
235
+
236
+ def rebalancing_tool(user_input, cash_amount, cash_ratio):
237
+ try:
238
+ stock_inputs, krw_cash = parse_input(user_input, cash_amount, cash_ratio)
239
+ portfolio, target_weights, krw_cash = build_portfolio(stock_inputs, krw_cash)
240
+ result = get_portfolio_rebalancing_info(portfolio, target_weights, krw_cash)
241
+ return result
242
+ except Exception as e:
243
+ return str(e)
244
+
245
+ def get_stock_prices(stock_code, days):
246
+ try:
247
+ df = fdr.DataReader(stock_code, end=pd.Timestamp.now().date(), data_source='yahoo')
248
+ df = df[df.index >= df.index.max() - pd.DateOffset(days=days)] # 졜근 days일 λ°μ΄ν„°λ‘œ μ œν•œ
249
+ return df['Close']
250
+ except Exception as e:
251
+ print(f"Failed to fetch data for {stock_code}: {e}")
252
+ return None
253
+
254
+ def plot_stock_prices(stock_codes, days):
255
+ # 주식 κ·Έλž˜ν”„ 생성을 μœ„ν•œ 병렬 처리
256
+ stock_prices = {}
257
+ with ThreadPoolExecutor() as executor:
258
+ futures = {executor.submit(get_stock_prices, stock_code.strip(), int(days)): stock_code.strip() for stock_code in stock_codes.split(',')}
259
+ for future in as_completed(futures):
260
+ stock_code = futures[future]
261
+ try:
262
+ prices = future.result()
263
+ if prices is not None:
264
+ stock_prices[stock_code] = prices
265
+ except Exception as e:
266
+ print(f"Failed to fetch data for {stock_code}: {e}")
267
+
268
+ # 각 주식에 λŒ€ν•œ κ·Έλž˜ν”„λ₯Ό κ·Έλ¦Ό
269
+ plt.figure(figsize=(10, 6))
270
+ for stock_code, prices in stock_prices.items():
271
+ relative_prices = prices / prices.iloc[0] # 첫 번째 데이터 포인트λ₯Ό κΈ°μ€€μœΌλ‘œ μƒλŒ€μ  가격 계산
272
+ plt.plot(prices.index, relative_prices, label=stock_code.upper()) # 주식 μ½”λ“œλ₯Ό λŒ€λ¬Έμžλ‘œ ν‘œμ‹œ
273
+ plt.xlabel('Date')
274
+ plt.ylabel('Relative Price (Normalized to 1)')
275
+ plt.title(f'Relative Stock Prices Over the Last {days} Days')
276
+ plt.legend()
277
+
278
+ # κ·Έλž˜ν”„λ₯Ό HTML둜 λ³€ν™˜ν•˜μ—¬ λ°˜ν™˜
279
+ html_graph = io.BytesIO()
280
+ plt.savefig(html_graph, format='png', dpi=300)
281
+ html_graph.seek(0)
282
+ graph_encoded = base64.b64encode(html_graph.getvalue()).decode()
283
+ graph_html = f'<img src="data:image/png;base64,{graph_encoded}"/>'
284
+
285
+ return graph_html
286
+
287
+ def cost_averaging(old_avg_price, old_quantity, new_price, new_quantity):
288
+ # μž…λ ₯값을 숫자둜 λ³€ν™˜
289
+ old_avg_price = float(old_avg_price) if old_avg_price else 0.0
290
+ old_quantity = float(old_quantity) if old_quantity else 0.0
291
+ new_price = float(new_price) if new_price else 0.0
292
+ new_quantity = float(new_quantity) if new_quantity else 0.0
293
+
294
+ # ν˜„μž¬ 투자 κΈˆμ•‘ 계산
295
+ current_investment = old_avg_price * old_quantity
296
+ # μΆ”κ°€ 투자 κΈˆμ•‘ 계산
297
+ additional_investment = new_price * new_quantity
298
+ # 총 투자 κΈˆμ•‘
299
+ total_investment = current_investment + additional_investment
300
+ # 총 주식 수
301
+ total_shares = old_quantity + new_quantity
302
+ # μƒˆ 평균 가격 계산
303
+ new_avg_price = total_investment / total_shares if total_shares != 0 else 0.0
304
+
305
+ # ν˜„μž¬ 수읡λ₯  계산
306
+ current_return = (new_price - old_avg_price) / old_avg_price * 100 if old_avg_price != 0 else 0.0
307
+ # μƒˆλ‘œμš΄ 수읡λ₯  계산
308
+ new_return = (new_price / new_avg_price - 1 ) * 100 if new_avg_price != 0 else 0.0
309
+ return new_avg_price, total_shares, total_investment, current_return, new_return, additional_investment
310
+
311
+ def gradio_cost_averaging(old_avg_price, old_quantity, new_price, new_quantity):
312
+ with open('portfolio.html', 'r', encoding='utf-8') as file:
313
+ css = file.read()
314
+
315
+ # μž…λ ₯값을 숫자둜 λ³€ν™˜
316
+ old_avg_price = float(old_avg_price) if old_avg_price else 0.0
317
+ old_quantity = float(old_quantity) if old_quantity else 0.0
318
+ new_price = float(new_price) if new_price else 0.0
319
+ new_quantity = float(new_quantity) if new_quantity else 0.0
320
+
321
+ new_avg_price, total_shares, total_investment, current_return, new_return, additional_investment = cost_averaging(old_avg_price, old_quantity, new_price, new_quantity)
322
+
323
+ current_return_class = ""
324
+ if current_return > 0:
325
+ current_return_class = f"<span style='color: #4caf50; font-weight: bold;'>{current_return:+,.2f}%</span>"
326
+ elif current_return < 0:
327
+ current_return_class = f"<span style='color: #f44336; font-weight: bold;'>{current_return:,.2f}%</span>"
328
+ else:
329
+ current_return_class = f"<span><strong>0</strong></span>"
330
+
331
+ new_return_class = ""
332
+ if new_return > 0:
333
+ new_return_class = f"<span style='color: #4caf50; font-weight: bold;'>{new_return:+,.2f}%</span>"
334
+ elif current_return < 0:
335
+ new_return_class = f"<span style='color: #f44336; font-weight: bold;'>{new_return:,.2f}%</span>"
336
+ else:
337
+ new_return_class = f"<span><strong>0</strong></span>"
338
+
339
+ # Construct the HTML string with the appropriate class
340
+ result_html = css+ f"""
341
+ <div style="box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); border-radius: 8px; padding: 48px; position: relative; width: 100%; padding: 24px;">
342
+ <div>
343
+ <div style="margin-bottom: 24px;">
344
+ <div style="font-size: 24px; margin-bottom: 24px;">Average Price</div>
345
+ <div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
346
+ <span></span>
347
+ <span>{new_avg_price:,.0f}</span>
348
+ </div>
349
+ <hr style="margin: 24px 0;">
350
+ </div>
351
+ </div>
352
+ <div>
353
+ <div style="margin-bottom: 24px;">
354
+ <div style="font-size: 24px; margin-bottom: 24px;">Total Quantity</div>
355
+ <div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
356
+ <span>{total_shares:,.0f}</span>
357
+ </div>
358
+ <hr style="margin: 24px 0;">
359
+ </div>
360
+ </div>
361
+ <div>
362
+ <div style="margin-bottom: 24px;">
363
+ <div style="font-size: 24px; margin-bottom: 24px;">Total Investment</div>
364
+ <div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
365
+ <span></span>
366
+ <span>{total_investment:,.0f}</span>
367
+ </div>
368
+ <hr style="margin: 24px 0;">
369
+ </div>
370
+ </div>
371
+ <div style='display: flex; justify-content: space-around; align-items: center;'>
372
+ <div style='text-align: center;'>
373
+ <div style="margin-bottom: 24px;">
374
+ <div style="font-size: 24px; margin-bottom: 24px;"></div>
375
+ <div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
376
+ <p></p>
377
+ <p>{current_return_class}</p>
378
+ <p>{old_avg_price:,.0f}</p>
379
+ </div>
380
+ </div>
381
+ </div>
382
+ <div style='text-align: center; margin-bottom: 24px; font-size: 24px;'>➜</div>
383
+ <div style='text-align: center;'>
384
+ <div style="margin-bottom: 24px;">
385
+ <div style="font-size: 24px; margin-bottom: 24px;"></div>
386
+ <div style="font-size: 24px; font-weight: bold; color: #1c75bc;">
387
+ <p></p>
388
+ <p>{new_return_class}</p>
389
+ <p>{new_avg_price:,.0f}</p>
390
+ </div>
391
+ </div>
392
+ </div>
393
+ </div>
394
+ <p style='text-align: center;'>총 μΆ”κ°€ κΈˆμ•‘: <strong>{additional_investment:,.0f}</strong></p>
395
+ </div>
396
+
397
+ """
398
+
399
+ return result_html
400
+
401
+
402
+
403
+
404
+
405
+ # Define the interface for the Portfolio tab
406
+ def portfolio_interface(input_text, cash_amount, cash_ratio):
407
+ result = rebalancing_tool(input_text, cash_amount, cash_ratio)
408
+ return result
409
+
410
+ portfolio_inputs = [
411
+ gr.Textbox(label="πŸ”₯ Holdings", lines=2, placeholder="Format: [stock code currency quantity target weight, ...]"),
412
+ gr.Number(label="πŸͺ΅ Cash", value=""),
413
+ gr.Slider(label="βš–οΈ Cash Ratio (%)", minimum=0, maximum=100, step=1)
414
+ ]
415
+
416
+ portfolio_interface = gr.Interface(
417
+ fn=portfolio_interface,
418
+ inputs=portfolio_inputs,
419
+ outputs=gr.HTML(),
420
+ examples = [
421
+ ["458730 krw 571 8,\n368590 krw 80 2", 17172, 0],
422
+ ["SCHD USD 400 8,\nQQQ USD 40 2", 1000000, 25],
423
+ ["458730 krw 571 8,\n368590 krw 80 2,\nSCHD USD 400 8,\nQQQ USD 40 2", 1000000, 25]
424
+ ],
425
+ live=False
426
+ )
427
+
428
+ # Define the interface for the Compare tab
429
+ def compare_interface(stock_codes, period):
430
+ result = plot_stock_prices(stock_codes, period)
431
+ return result
432
+
433
+ compare_inputs = [
434
+ gr.Textbox(label="πŸ“ˆ Stock Codes", lines=2, placeholder="Enter stock codes separated by comma (e.g., AAPL,GOOGL,MSFT)"),
435
+ gr.Number(label="πŸ“† Period (days)", value=90)
436
+ ]
437
+
438
+ compare_interface = gr.Interface(
439
+ fn=compare_interface,
440
+ inputs=compare_inputs,
441
+ outputs=gr.HTML(),
442
+ examples = [
443
+ ["SCHD,QQQ", 90],
444
+ ["458730,368590", 90],
445
+ ["AAPL,GOOGL,MSFT", 90]
446
+ ],
447
+ live=False
448
+ )
449
+
450
+ # Define the interface for the Cost Averaging tab
451
+ def cost_averaging_interface(old_avg_price, old_quantity, new_price, new_quantity):
452
+ result = gradio_cost_averaging(old_avg_price, old_quantity, new_price, new_quantity)
453
+ return result
454
+
455
+ cost_averaging_inputs = [
456
+ gr.Number(label="Old Price", value=""),
457
+ gr.Number(label="Quantity", value=""),
458
+ gr.Number(label="New Price", value=""),
459
+ gr.Number(label="Quantity", value="")
460
+ ]
461
+
462
+ cost_averaging_interface = gr.Interface(
463
+ fn=cost_averaging_interface,
464
+ inputs=cost_averaging_inputs,
465
+ outputs=gr.HTML(),
466
+ examples = [
467
+ [78.15, 6.024272, 77.11, 1]
468
+ ],
469
+ live=False
470
+ )
471
+
472
+ # Combine all interfaces into a tabbed interface
473
+ with gr.Blocks(css='style.css') as demo:
474
+ with gr.Column(elem_id="col-container"):
475
+ with gr.Tabs():
476
+ with gr.TabItem("Portfolio"):
477
+ portfolio_interface.render()
478
+ with gr.TabItem("Compare"):
479
+ compare_interface.render()
480
+ with gr.TabItem("Cost Averaging"):
481
+ cost_averaging_interface.render()
482
+ with gr.TabItem("πŸ“„ About"):
483
+ gr.Markdown("""
484
+ # About This Application
485
+
486
+ 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.
487
+
488
+ ## πŸ“Š Portfolio
489
+
490
+ **Description:**
491
+ 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.
492
+
493
+ **How to Use:**
494
+ 1. Enter your holdings in the format: `[stock code currency quantity target weight]`.
495
+ 2. Specify your cash amount and desired cash ratio.
496
+ 3. Click the "Analyze Data" button to see the rebalancing analysis.
497
+ 4. View the detailed breakdown of your current portfolio and suggested trades.
498
+
499
+ ## πŸ“ˆ Compare
500
+
501
+ **Description:**
502
+ 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.
503
+
504
+ **How to Use:**
505
+ 1. Enter the stock codes separated by commas (e.g., AAPL, GOOGL, MSFT).
506
+ 2. Specify the period in days for which you want to compare the stock prices.
507
+ 3. Click the "Compare Stock Prices" button to generate the comparison graph.
508
+ 4. View the relative price changes of the selected stocks over the chosen period.
509
+
510
+ ## πŸ’Ή Cost Averaging
511
+
512
+ **Description:**
513
+ 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.
514
+
515
+ **How to Use:**
516
+ 1. Enter the average price and quantity of your initial purchase in the "First Purchase" section.
517
+ 2. Enter the price and quantity of your subsequent purchase in the "Second Purchase" section.
518
+ 3. Click the "Calculate Cost Averaging" button to see the results.
519
+ 4. View the new average price, total quantity, total investment, and return rates.
520
+
521
+ ## πŸ“„ About
522
+
523
+ **Description:**
524
+ 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.
525
+
526
+ **How to Use:**
527
+ Simply read through the information provided to get acquainted with the application's capabilities.
528
+
529
+ ## Disclaimer
530
+
531
+ 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.
532
+
533
+ ---
534
 
535
+ We hope you find this tool useful for managing your investments. If you have any feedback or suggestions, feel free to reach out!
 
 
 
 
536
 
537
+ Happy Investing!
538
+ """)
539
 
540
+ demo.launch(share=True)