cryman38 commited on
Commit
5fea6c7
ยท
verified ยท
1 Parent(s): 96f8c18

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +480 -195
  2. portfolio.html +249 -0
  3. requirements.txt +4 -0
  4. style.css +13 -0
app.py CHANGED
@@ -1,147 +1,135 @@
1
- import gradio as gr
2
- import logging
3
  import math
4
- import FinanceDataReader as fdr
5
  import requests
 
 
6
  import ssl
 
 
 
 
7
  from datetime import datetime
 
 
 
 
 
 
8
  import matplotlib.pyplot as plt
 
 
 
 
9
  import io
10
  import base64
11
- from concurrent.futures import ThreadPoolExecutor
12
-
13
- # ํ˜„์žฌ ๋‚ ์งœ๋ฅผ "Jun-20-2024" ํ˜•์‹์œผ๋กœ ๊ฐ€์ ธ์˜ค๊ธฐ
14
- current_date = datetime.now().strftime("%b-%d-%Y")
15
-
16
- # SSL ์ธ์ฆ์„œ ๊ฒ€์ฆ ๋น„ํ™œ์„ฑํ™” (์ฃผ์„์ฒ˜๋ฆฌ, ๊ธฐ๋ณธ HTTPS ์ปจํ…์ŠคํŠธ ์‚ฌ์šฉ)
17
- # ssl._create_default_https_context = ssl._create_unverified_context
18
-
19
- # ๋กœ๊น… ์„ค์ •
20
- logging.basicConfig(level=logging.WARNING)
21
- logger = logging.getLogger(__name__)
22
 
23
- exchange_rates = {}
24
 
25
- class StockCodeNotFoundError(Exception):
26
- pass
27
 
28
- class CurrencyConversionError(Exception):
29
- pass
30
 
31
- def parse_input(text, cash_amount_expr, cash_ratio):
32
- logger.info(f"Parsing input: {text} with cash amount expression: {cash_amount_expr} and cash ratio: {cash_ratio}")
33
- try:
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
- country_code, stock_code, quantity_expr, target_weight_expr = parts
42
- quantity = math.floor(eval(quantity_expr.replace(' ', '')))
43
- target_weight = eval(target_weight_expr.replace(' ', ''))
44
- stock_inputs.append((country_code, stock_code, quantity, target_weight, target_weight_expr)) # target_weight_expr ์ถ”๊ฐ€
45
- total_target_weight += target_weight
46
- else:
47
- raise ValueError("Invalid input format.")
48
-
49
- if cash_amount_expr.strip():
50
- cash_amount = math.floor(eval(cash_amount_expr.replace(' ', '')))
51
- else:
52
- cash_amount = 0
53
-
54
- krw_cash = {'amount': cash_amount, 'target_weight': cash_ratio / 100.0}
55
 
56
- cash_ratio = krw_cash['target_weight']
57
- stock_total_weight = total_target_weight
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- for i in range(len(stock_inputs)):
60
- stock_inputs[i] = (stock_inputs[i][0], stock_inputs[i][1], stock_inputs[i][2], (1 - cash_ratio) * stock_inputs[i][3] / stock_total_weight, stock_inputs[i][4])
61
 
62
- logger.info(f"Parsed stock inputs: {stock_inputs}, KRW cash: {krw_cash}")
63
- return stock_inputs, krw_cash
64
- except (ValueError, SyntaxError) as e:
65
- logger.error("Error parsing input", exc_info=e)
66
- raise ValueError("Invalid input format. Example: usd schd 21 8, krw 368590 530 2")
67
 
68
- def get_exchange_rate(country_code):
69
- if country_code.upper() in exchange_rates:
70
- return exchange_rates[country_code.upper()]
71
 
72
- logger.info(f"Fetching exchange rate - {country_code}")
73
- if country_code.upper() == 'KRW':
74
- return 1
75
 
76
- url = f"https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRW{country_code.upper()}"
77
- try:
78
- response = requests.get(url, verify=True) # verify=True๋กœ ์„ค์ •
79
- response.raise_for_status()
80
- data = response.json()
81
- exchange_rate = data[0]['basePrice']
82
- exchange_rates[country_code.upper()] = exchange_rate
83
- logger.info(f"Exchange rate - {country_code}: {exchange_rate}")
84
- return exchange_rate
85
- except (requests.RequestException, IndexError) as e:
86
- logger.error(f"Error fetching exchange rate - {country_code}", exc_info=e)
87
- raise CurrencyConversionError("Error fetching exchange rate. Please enter a valid country code.")
88
-
89
- def get_exchange_reflected_stock_price(stock_code, country_code):
90
- logger.info(f"Fetching exchange reflected stock price - {stock_code} in {country_code}")
91
- try:
92
- current_price = get_current_stock_price(stock_code)
93
- exchange_rate = get_exchange_rate(country_code)
94
- reflected_price = math.floor(current_price * exchange_rate)
95
- logger.info(f"Reflected stock price - {stock_code}: {reflected_price}")
96
- return reflected_price
97
- except (StockCodeNotFoundError, CurrencyConversionError) as e:
98
- logger.error(f"Error fetching reflected stock price - {stock_code} in {country_code}", exc_info=e)
99
- raise e
100
 
101
  def get_current_stock_price(stock_code):
102
- logger.info(f"Fetching current stock price - {stock_code}")
103
- try:
104
- df = fdr.DataReader(stock_code)
105
- current_price = df['Close'].iloc[-1]
106
- logger.info(f"Current stock price - {stock_code}: {current_price}")
107
- return current_price
108
- except ValueError as e:
109
- logger.error(f"Error fetching stock price - {stock_code}", exc_info=e)
110
- raise StockCodeNotFoundError("Stock code not found. Please enter a valid stock code.")
111
 
112
  def build_portfolio(stock_inputs, krw_cash):
113
  portfolio = {}
114
  target_weights = {}
115
-
116
- logger.info(f"Building portfolio - stock inputs: {stock_inputs}, KRW cash: {krw_cash}")
117
-
118
  with ThreadPoolExecutor() as executor:
119
- results = list(executor.map(lambda stock_input: (
120
- stock_input[1], # stock_code
121
- get_exchange_reflected_stock_price(stock_input[1], stock_input[0]),
122
- stock_input[2], # quantity
123
- stock_input[3], # target_weight
124
- stock_input[4] # target_weight_expr
125
- ), stock_inputs))
126
-
127
- for stock_code, current_price, quantity, target_weight, target_weight_expr in results:
128
- portfolio[stock_code] = {'quantity': quantity, 'price': current_price, 'target_weight_expr': target_weight_expr}
129
- target_weights[stock_code] = target_weight
130
-
131
- if krw_cash is None:
132
- krw_cash = {'amount': 0, 'target_weight': 0}
133
-
134
- logger.info(f"Portfolio built: {portfolio}, target weights: {target_weights}, KRW cash: {krw_cash}")
135
  return portfolio, target_weights, krw_cash
136
 
 
 
 
 
 
 
137
  def get_portfolio_rebalancing_info(portfolio, target_weights, krw_cash):
138
- logger.info("Calculating portfolio rebalancing information")
 
 
 
 
139
 
140
  total_value = sum(stock['price'] * stock['quantity'] for stock in portfolio.values()) + krw_cash['amount']
141
  total_new_stock_value = 0
142
  total_trade_value = 0
143
  adjustments = []
144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  for stock_code, stock_data in portfolio.items():
146
  current_value = stock_data['price'] * stock_data['quantity']
147
  target_value = total_value * target_weights.get(stock_code, 0)
@@ -153,103 +141,400 @@ def get_portfolio_rebalancing_info(portfolio, target_weights, krw_cash):
153
  total_trade_value += abs(trade_value)
154
  total_new_stock_value += new_value
155
  current_value_pct = (current_value / total_value) * 100
 
156
 
157
- 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, stock_data['target_weight_expr'])) # target_weight_expr ์ถ”๊ฐ€
158
 
159
- # ์ฃผ์‹ ํ‰๊ฐ€๊ธˆ์•ก ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ
160
- adjustments.sort(key=lambda x: x[1], reverse=True)
 
 
 
 
 
 
 
 
161
 
162
- result_message = "<ol>"
163
- for adjustment in adjustments:
164
- difference, current_value, target_value, current_value_pct, trade_quantity, stock_code, price, new_value, trade_value, old_quantity, new_quantity, target_weight_expr = adjustment # target_weight_expr ์ถ”๊ฐ€
165
- new_value_pct = (new_value / total_value) * 100
166
- formatted_trade_quantity = f"<span style='color: {'#57bb8a' if trade_quantity > 0 else '#cc0000'}'> {trade_quantity:+,} </span>" if trade_quantity != 0 else "0"
167
- result_message += (
168
- f"<li style='font-size: 1rem;'><strong>{stock_code.upper()}</strong> {current_value_pct:.0f}% <span style='background-color: yellow; color: blue;'>[ {target_weight_expr} ]</span> {target_value / total_value * 100:.0f}% {formatted_trade_quantity}</li>" # target_weight_expr๋กœ ๋ณ€๊ฒฝ
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  )
170
- result_message += "</ol>"
171
-
172
- if krw_cash:
173
- krw_new_amount = total_value - total_new_stock_value
174
- krw_target_value = total_value * krw_cash['target_weight']
175
- krw_difference = krw_new_amount - krw_cash['amount']
176
- krw_new_pct = (krw_new_amount / total_value) * 100
177
- formatted_krw_difference = f"<span style='color: {'#57bb8a' if krw_difference > 0 else '#cc0000'}'> {krw_difference:+,} </span>" if krw_difference != 0 else "0"
178
  result_message += (
179
- f"<p style='font-size: 1rem;'><strong>๐Ÿ’ฐ CASH</strong> {krw_cash['amount'] / total_value * 100:.0f}% <span style='background-color: yellow; color: blue;'>[ {krw_cash['target_weight'] * 100:.0f}% ]</span> {formatted_krw_difference}</p>"
 
 
 
 
 
 
 
 
 
 
 
180
  )
181
 
182
- result_message += f"<p style='font-size: 1.5rem;'><strong>๐Ÿฆ„ {total_value:,}</strong></p>"
183
- logger.info("Portfolio rebalancing information calculated")
184
- return result_message, adjustments, total_value, krw_new_amount
185
-
186
- def plot_bar_chart(adjustments):
187
- fig, ax = plt.subplots()
188
- stock_codes = [f"{adj[5].upper()}\n@{adj[6]:,}" for adj in adjustments]
189
- current_values = [adj[1] for adj in adjustments]
190
- new_values = [adj[7] for adj in adjustments]
191
-
192
- x = range(len(stock_codes))
193
- bar_width = 0.35
194
- bars1 = ax.bar([i - bar_width / 2 for i in x], current_values, width=bar_width, label='CURRENT VALUE')
195
- bars2 = ax.bar([i + bar_width / 2 for i in x], new_values, width=bar_width, label='NEW VALUE')
196
-
197
- ax.set_ylabel('VALUE (IN KRW)')
198
- ax.set_xticks(x)
199
- ax.set_xticklabels(stock_codes)
200
- ax.legend()
201
-
202
- for bar in bars1:
203
- yval = bar.get_height()
204
- ax.text(bar.get_x() + bar.get_width() / 2, yval, f"{int(yval):,}", ha='center', va='bottom')
205
-
206
- for bar in bars2:
207
- yval = bar.get_height()
208
- ax.text(bar.get_x() + bar.get_width() / 2, yval, f"{int(yval):,}", ha='center', va='bottom')
209
-
210
- plt.tight_layout() # ๊ทธ๋ž˜ํ”„์™€ ํƒ€์ดํ‹€ ์‚ฌ์ด์˜ ๊ฐ„๊ฒฉ ์กฐ์ •
211
 
212
- buf = io.BytesIO()
213
- plt.savefig(buf, format='png')
214
- buf.seek(0)
215
- img = base64.b64encode(buf.read()).decode('utf-8')
216
- buf.close()
217
 
218
- return f'<img src="data:image/png;base64,{img}"/>'
219
-
220
- def rebalance_portfolio(input_text, cash_amount_expr, cash_ratio):
221
  try:
222
- # ์ž…๋ ฅ ๋ฐ์ดํ„ฐ ํŒŒ์‹ฑ
223
- stock_inputs, krw_cash = parse_input(input_text, cash_amount_expr, cash_ratio)
224
-
225
- # ํฌํŠธํด๋ฆฌ์˜ค ๊ตฌ์ถ•
226
  portfolio, target_weights, krw_cash = build_portfolio(stock_inputs, krw_cash)
227
-
228
- # ํฌํŠธํด๋ฆฌ์˜ค ๋ฆฌ๋ฐธ๋Ÿฐ์‹ฑ ์ •๋ณด ๊ณ„์‚ฐ
229
- result_message, adjustments, total_value, krw_new_amount = get_portfolio_rebalancing_info(portfolio, target_weights, krw_cash)
230
-
231
- # ํ˜„์žฌ vs ์ƒˆ๋กœ์šด ๊ฐ’ ๋ฐ” ์ฐจํŠธ ์ƒ์„ฑ
232
- bar_chart = plot_bar_chart(adjustments)
233
-
234
- # ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜
235
- return result_message, bar_chart
 
236
  except Exception as e:
237
- return "", str(e)
238
-
239
- # Gradio ์ธํ„ฐํŽ˜์ด์Šค ์„ค์ •
240
- interface = gr.Interface(
241
- fn=rebalance_portfolio,
242
- inputs=[
243
- gr.Textbox(lines=2, value="krw 458730 530 8, krw 368590 79 2", label="ํฌํŠธํด๋ฆฌ์˜ค ๋ฐ์ดํ„ฐ"),
244
- gr.Textbox(lines=1, value="518192", label="์ถ”๊ฐ€ ํˆฌ์ž๊ธˆ"),
245
- gr.Slider(minimum=0, maximum=100, step=1, value=0, label="ํ˜„๊ธˆ ๋น„์œจ (%)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  ],
247
- outputs=[
248
- gr.HTML(label="๊ฒฐ๊ณผ ๋ฉ”์‹œ์ง€"),
249
- gr.HTML(label="๋ฐ” ์ฐจํŠธ")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  ],
251
- title=f"๐ŸฆŠ๐Ÿป๐Ÿถ๐Ÿฐ{current_date}"
252
  )
253
 
254
- if __name__ == "__main__":
255
- interface.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
 
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)
portfolio.html ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="ko">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Portfolio Rebalancing</title>
7
+ <style>
8
+ :root {
9
+ --background-color-light: #ffffff;
10
+ --background-color-dark: #121212;
11
+ --text-color-light: #333333;
12
+ --text-color-dark: #ffffff;
13
+ --highlight-color-light: #f7f7f7;
14
+ --highlight-color-dark: #1e1e1e;
15
+ --header-color-light: #000000;
16
+ --header-color-dark: #ffffff;
17
+ --buy-color: #4caf50;
18
+ --sell-color: #f44336;
19
+ --highlight-edit-bg-color-light: #fff2cc;
20
+ --highlight-edit-text-color-light: #0000ff;
21
+ --highlight-edit-bg-color-dark: hsl(45, 100%, 70%); /* ์–ด๋‘์šด ๋ฐฐ๊ฒฝ */
22
+ --highlight-edit-text-color-dark: hsl(240, 100%, 50%); /* ๋ฐ์€ ํ…์ŠคํŠธ */
23
+ --highlight-yellow-bg-color-light: #ffeb3b;
24
+ --highlight-yellow-bg-color-dark: #ffca28;
25
+ --highlight-yellow-text-color-light: #000000;
26
+ --highlight-yellow-text-color-dark: #000000;
27
+ --highlight-sky-bg-color-light: #ddf5fd;
28
+ --highlight-sky-bg-color-dark: #89c9e6;
29
+ --highlight-sky-text-color-light: #000000;
30
+ --highlight-sky-text-color-dark: #000000;
31
+ --highlight-black-light: #000000;
32
+ --highlight-black-dark: #ffffff;
33
+ --total-value-color-light: #000000;
34
+ --total-value-color-dark: #ffeb3b;
35
+ }
36
+
37
+ body {
38
+ font-family: 'Roboto', sans-serif;
39
+ line-height: 1.6;
40
+ color: var(--text-color-light);
41
+ background-color: var(--background-color-light);
42
+ padding: 20px;
43
+ }
44
+
45
+ .buy-sell {
46
+ padding: 5px 10px;
47
+ border-radius: 5px;
48
+ font-weight: bold;
49
+ display: inline-block;
50
+ margin: 2px;
51
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
52
+ }
53
+
54
+ .buy {
55
+ background-color: var(--buy-color);
56
+ color: white !important;
57
+ }
58
+
59
+ .dashboard {
60
+ /* background-color: #f6fcfe; */
61
+ /* border: 1px solid #89c9e6; */
62
+ text-align: left;
63
+ padding: 10px;
64
+ font-size: 1rem;
65
+ border-radius: 18px;
66
+ box-shadow: 2px 4px 12px #00000014;
67
+ transition: all .3s cubic-bezier(0,0,.5,1);
68
+ }
69
+
70
+
71
+ .sell {
72
+ background-color: var(--sell-color);
73
+ color: white !important;
74
+ }
75
+ .highlight-edit {
76
+ background-color: var(--highlight-edit-bg-color-light);
77
+ color: var(--highlight-edit-text-color-light) !important;
78
+ padding: 5px 10px;
79
+ font-weight: bold;
80
+ border-radius: 5px;
81
+ display: inline-block;
82
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
83
+ }
84
+ .highlight-black {
85
+ background-color: var(--highlight-black-light);
86
+ color: var(--text-color-dark) !important;
87
+ padding: 5px 10px;
88
+ font-weight: bold;
89
+ border-radius: 5px;
90
+ display: inline-block;
91
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
92
+ }
93
+
94
+ .highlight-yellow {
95
+ background-color: var(--highlight-yellow-bg-color-light);
96
+ color: var(--highlight-yellow-text-color-light) !important;
97
+ padding: 5px 10px;
98
+ font-weight: bold;
99
+ border-radius: 5px;
100
+ display: inline-block;
101
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
102
+ }
103
+
104
+ .highlight-sky {
105
+ background-color: var(--highlight-sky-bg-color-light);
106
+ color: var(--highlight-sky-text-color-light) !important;
107
+ padding: 5px 10px;
108
+ font-weight: bold;
109
+ border-radius: 5px;
110
+ display: inline-block;
111
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
112
+ }
113
+
114
+ .container {
115
+ font-size: 1.2rem;
116
+ margin-bottom: 15px;
117
+ padding: 20px;
118
+ border: 1px solid #ddd;
119
+ border-radius: 5px;
120
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
121
+ background-color: var(--highlight-color-light);
122
+ }
123
+
124
+ .header {
125
+ font-size: 1.2rem;
126
+ font-weight: bold;
127
+ color: var(--header-color-light);
128
+ margin-top: 10px;
129
+ text-align: center;
130
+ }
131
+
132
+ .total-value {
133
+ color: var(--total-value-color-light);
134
+ font-size: 3rem;
135
+ }
136
+
137
+ .summary {
138
+ font-size: 1.2rem;
139
+ color: var(--text-color-light);
140
+ margin-top: 10px;
141
+ text-align: center;
142
+ }
143
+
144
+ .table-container {
145
+ width: 100%;
146
+ overflow: auto;
147
+ margin-bottom: 20px;
148
+ position: relative;
149
+ max-height: 600px;
150
+ border: 1px hidden #ddd;
151
+ max-height: max-content; /* ํ‘œ์˜ ์ตœ๋Œ€ ๋†’์ด ์„ค์ • */
152
+ overflow-y: hidden; /* ์Šคํฌ๋กค ์ˆจ๊น€ */
153
+ }
154
+
155
+ .table-container table {
156
+ width: 100%;
157
+ border-collapse: collapse;
158
+ }
159
+
160
+ .table-container th, .table-container td {
161
+ border: 1px hidden #ddd;
162
+ padding: 8px;
163
+ text-align: left;
164
+ background-color: var(--background-color-light);
165
+ }
166
+
167
+ .table-container th {
168
+ background-color: var(--highlight-color-light);
169
+ position: sticky;
170
+ top: 0;
171
+ z-index: 2;
172
+ }
173
+
174
+ .table-container td:first-child, .table-container th:first-child {
175
+ position: sticky;
176
+ left: 0;
177
+ z-index: 1;
178
+ }
179
+
180
+ .table-container th:first-child {
181
+ z-index: 3;
182
+ }
183
+
184
+ @media (prefers-color-scheme: dark) {
185
+ body {
186
+ color: var(--text-color-dark);
187
+ background-color: var(--background-color-dark);
188
+ }
189
+
190
+ .container {
191
+ background-color: var(--highlight-color-dark);
192
+ }
193
+
194
+ .header {
195
+ color: var(--header-color-dark);
196
+ }
197
+
198
+ .total-value {
199
+ color: var(--total-value-color-dark);
200
+ }
201
+
202
+ .table-container th, .table-container td {
203
+ background-color: var(--background-color-dark);
204
+ color: var(--text-color-dark);
205
+ }
206
+
207
+ .highlight-yellow {
208
+ background-color: var(--highlight-yellow-bg-color-dark);
209
+ color: var(--highlight-yellow-text-color-dark) !important;
210
+ }
211
+
212
+ .highlight-black {
213
+ background-color: var(--highlight-black-dark);
214
+ color: var(--text-color-light) !important;
215
+ }
216
+
217
+ .highlight-sky {
218
+ background-color: var(--highlight-sky-bg-color-dark);
219
+ color: var(--highlight-sky-text-color-dark) !important;
220
+ }
221
+ .highlight-edit {
222
+ background-color: var(--highlight-edit-bg-color-dark);
223
+ color: var(--highlight-edit-text-color-dark) !important;
224
+ }
225
+
226
+ .table-container th {
227
+ background-color: var(--highlight-color-dark);
228
+ }
229
+
230
+ .buy-sell, .highlight-black, .highlight-yellow, .highlight-sky, .highlight-edit {
231
+ box-shadow: 0 2px 4px rgba(255, 255, 255, 0.1);
232
+ }
233
+ .dashboard {
234
+ background-color: #2b2b2b; /* ์–ด๋‘์šด ๋ฐฐ๊ฒฝ์ƒ‰ */
235
+ border: 1px solid #555555; /* ์–ด๋‘์šด ํ…Œ๋‘๋ฆฌ ์ƒ‰์ƒ */
236
+ color: #e0e0e0; /* ๋ฐ์€ ๊ธ€์ž ์ƒ‰์ƒ */
237
+ text-align: left;
238
+ padding: 10px;
239
+ font-size: 1rem;
240
+ border-radius: 18px;
241
+ box-shadow: 2px 4px 12px #00000050; /* ๋‹คํฌ๋ชจ๋“œ์— ์–ด์šธ๋ฆฌ๋Š” ๊ทธ๋ฆผ์ž ์ƒ‰์ƒ */
242
+ transition: all .3s cubic-bezier(0,0,.5,1);
243
+ }
244
+
245
+
246
+ }
247
+ </style>
248
+ </head>
249
+ </html>
requirements.txt CHANGED
@@ -4,3 +4,7 @@ finance-datareader
4
  requests
5
  plotly
6
  gradio
 
 
 
 
 
4
  requests
5
  plotly
6
  gradio
7
+ matplotlib
8
+ pandas
9
+ pytz
10
+ yfinance
style.css ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;700&display=swap');
3
+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;700&display=swap');
4
+
5
+ #col-container {
6
+ margin: 0 auto;
7
+ max-width: 100%;
8
+ font-family: 'Montserrat', 'ui-sans-serif', 'system-ui', 'sans-serif';
9
+ }
10
+
11
+ .code {
12
+ font-family: 'IBM Plex Mono', 'ui-monospace', 'Consolas', 'monospace';
13
+ }