개발이야기/자바스크립트

[자바스크립트] 주식 수익률 계산기 만들기

후린개발자 2023. 7. 20.
반응형

사용자가 입력한 가격과 수량을 기반으로 예상 매수 총금액, 매도 총금액, 예상 수익, 예상 수익률, 손실, 손실률 등을 계산하여 결과를 표시합니다.

 

<h2>주식 수익률 계산기</h2>
  <p>매매 수수료: 0.015%  / 세금 : 0.23%</p>
  <div>
	  <div style="margin:3px;">
		  <label for="buyPrice">매수 가격:</label>
		  <input type="number" id="buyPrice">
	  </div>
	  <div style="margin:3px;">
		  <label for="sellPrice">매도 가격:</label>
		  <input type="number" id="sellPrice">
	  </div>
	  <div style="margin:3px;">
		  <label for="quantity">보유 수량:</label>
		  <input type="number" id="quantity" step="1">
	  </div>
  </div>
  <button type="button" onclick="calculate()">계산하기</button>

  <div id="result" style="margin-top:10px;"></div>
  <script>
    function numberWithCommas(x) {
      return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function calculate() {
      const buyPrice = parseFloat(document.getElementById('buyPrice').value);
      const sellPrice = parseFloat(document.getElementById('sellPrice').value);
      const quantity = parseInt(document.getElementById('quantity').value);
      
      if (isNaN(buyPrice) || isNaN(sellPrice) || isNaN(quantity)) {
        document.getElementById('result').innerHTML = '올바른 가격과 수량을 입력해주세요.';
      } else {
        // 매매 수수료 및 세금 계산
        const commissionRate = 0.00015; // 수수료율 0.015%
        const taxRate = 0.0023; // 세금율 0.23%
        const buyCommission = buyPrice * quantity * commissionRate;
        const sellCommission = sellPrice * quantity * commissionRate;
        const sellTax = sellPrice * quantity * taxRate;
        const totalCommission = buyCommission + sellCommission + sellTax;

        // 예상 수익 계산
        const totalCost = buyPrice * quantity;
        const totalRevenue = sellPrice * quantity;
        const profit = (totalRevenue - totalCost - totalCommission);
        const percentage = (((totalRevenue - totalCost - totalCommission) / totalCost) * 100).toFixed(2);

        const resultText = profit >= 0
          ? `매수 총 금액: ${numberWithCommas(Math.floor(totalCost))}<br>매도 총 금액: ${numberWithCommas(Math.floor(totalRevenue))}<br>수익: ${numberWithCommas(Math.floor(profit))} / 수익률: ${percentage}%`
          : `매수 총 금액: ${numberWithCommas(Math.floor(totalCost))}<br>매도 총 금액: ${numberWithCommas(Math.floor(totalRevenue))}<br>손실: ${numberWithCommas(Math.floor(Math.abs(profit)))} / 손실률: ${percentage}%`;

        document.getElementById('result').innerHTML = resultText;
      }
    }
  </script>

 

 

 

⬇ 테스트 해보세요. 모두 대박 나세요

주식 수익률 계산기

매매 수수료: 0.015% / 세금 : 0.23%

반응형

댓글

💲 추천 글