import yfinance as yf import FinanceDataReader as fdr from modules.utils import load_css # def get_stock_price(stock_code): # try: # # 한국 주식 코드가 숫자만 있는지 확인 (한국 주식은 보통 숫자 코드) # if stock_code.isdigit(): # df = fdr.DataReader(stock_code) # return df['Close'].iloc[-1] # else: # # 한국 외 주식은 yfinance로 조회 # stock = yf.Ticker(stock_code) # df = stock.history(period="1d") # return df['Close'].iloc[-1] # except Exception as e: # # 에러 발생 시 0.0으로 설정하고, 오류 메시지를 반환 # return None def calculate_dollar_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 if old_quantity == 0 and new_quantity == 0: return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 current_investment = old_avg_price * old_quantity additional_investment = new_price * new_quantity total_investment = current_investment + additional_investment total_quantity = old_quantity + new_quantity new_avg_price = total_investment / total_quantity if total_quantity != 0 else 0.0 old_return = (new_price / old_avg_price - 1) * 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_quantity, total_investment, new_return, additional_investment, old_return def dollar_cost_averaging(old_avg_price, old_quantity, new_price, new_quantity): css = load_css() # 주식 가격 가져오기 # new_price = get_stock_price(stock_code) 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_quantity, total_investment, new_return, additional_investment, old_return = calculate_dollar_cost_averaging(old_avg_price, old_quantity, new_price, new_quantity) emoji_return = "" new_return_class = "" old_return_class = "" if new_price < old_avg_price: emoji_return = "💧" elif new_price > old_avg_price: emoji_return = "🔥" else: emoji_return = "" if new_return > 0: new_return_class = f"{new_return:+,.2f}%" elif new_return < 0: new_return_class = f"{new_return:,.2f}%" else: new_return_class = f"0" if old_return > 0: old_return_class = f"{old_return:+,.2f}%" elif old_return < 0: old_return_class = f"{old_return:,.2f}%" else: old_return_class = f"0" result_html = css + f"""
{emoji_return}
Old Price
{old_avg_price:,.2f} {old_return_class}

Average Price
{new_avg_price:,.2f} {new_return_class}

Additional Investment
{additional_investment:,.2f}

""" return result_html