メインコンテンツ

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

RESTful API、JSON、および JavaScript を使用した Web ベース ツールの作成

R2026a

この例では、単純な式から債権の価格を計算する Web アプリケーションを作成する方法を説明します。MATLAB® Production Server™ RESTful API および MATLAB データ型の JSON 表現 を使用して、MATLAB Production Server を使用したエンドツーエンドのワークフローを示しています。次の既知の値を Web インターフェイスに入力して、この例を実行します。

  • 額面価格 (または満期時の債権価格) — M

  • 利払い — C

  • 支払い回数 — N

  • 金利 — i

アプリケーションは、次の方程式に基づいて価格 (P) を計算します。

P = C * ( (1 - (1 + i)^-N) / i ) + M * (1 + i)^-N
異なる債権に価格を設定するには、Web アプリケーションでスライダーを使用します。

手順 1: MATLAB コードの記述

MATLAB で以下のコードを記述し、債権に価格を設定します。ファイル名 pricecalc.m を使用してコードを保存します。

function price = pricecalc(face_value, coupon_payment,...
                           interest_rate, num_payments)
    M = face_value;
    C = coupon_payment;
    N = num_payments;
    i = interest_rate;
    
    price = C * ( (1 - (1 + i)^-N) / i ) + M * (1 + i)^-N;

手順 2: Production Server アーカイブ コンパイラ アプリを使用したデプロイ可能なアーカイブの作成

この例のために、デプロイ可能なアーカイブを作成するには、次のようにします。

  1. [アプリ] タブで、[Production Server アーカイブ コンパイラ] を選択します。

  2. [エクスポートする関数] フィールドで、pricecalc.m を追加します。

  3. アーカイブの名前を BondTools に変更します。

  4. [パッケージ化] をクリックします。

デプロイ可能なアーカイブ BondTools.ctf がプロジェクトの出力フォルダーに生成されます。

手順 3: デプロイ可能なアーカイブのサーバーへの配置

  1. 必要に応じて、https://www.mathworks.com/products/compiler/mcr で MATLAB Runtime をダウンロードします。詳細については、MATLAB Production Server でサポートされる MATLAB Runtime バージョンを参照してください。

  2. mps-new を使用してサーバーを作成します。詳細については、コマンド ラインを使用したサーバー インスタンスの作成を参照してください。サーバー環境をまだセットアップしていない場合、詳細については、mps-setupを参照してください。

  3. まだ行っていない場合、サーバー構成ファイル main_config を編集して --mcr-root のパスを指定することで、MATLAB Runtime の場所をサーバーに指定します。詳細については、Server Configuration Properties を参照してください。

  4. mps-start を使用してサーバーを起動し、mps-status を使用してサーバーが実行されていることを確認します。

  5. BondTools.ctf ファイルを、ホスト用のサーバー上の auto_deploy フォルダーにコピーします。

手順 4: サーバーでのオリジン間リソース共有 (CORS) の有効化

サーバー構成ファイル main_config を編集して、サーバーに対してリクエストを行うことができるドメイン オリジンのリストを指定することで、オリジン間リソース共有 (CORS) を有効にします。たとえば、cors-allowed-origins オプションを --cors-allowed-origins * に設定すると、任意のドメインからのリクエストがサーバーにアクセスできるようになります。詳細については、cors-allowed-originsおよびServer Configuration Propertiesを参照してください。

手順 5: RESTful API および JSON を使用した JavaScript コードの記述

RESTful API および MATLAB データ型の JSON 表現をガイドとして使用して、次の JavaScript® コードを記述します。このコードを calculatePrice.js という名前の JavaScript ファイルとして保存します。

コード:

//calculatePrice.js : JavaScript code to calculate the price of a bond.
        function calculatePrice() 
        {
            var cp = parseFloat(document.getElementById('coupon_payment_value').value);
            var np = parseFloat(document.getElementById('num_payments_value').value);
            var ir = parseFloat(document.getElementById('interest_rate_value').value);
            var vm = parseFloat(document.getElementById('facevalue_value').value);

            // A new XMLHttpRequest object
            var request = new XMLHttpRequest();
            //Use MPS RESTful API to specify URL
            var url = "http://localhost:9910/BondTools/pricecalc";
            
            //Use MPS RESTful API to specify params using JSON
            var params = { "nargout":1,
                           "rhs": [vm, cp, ir, np] };

            document.getElementById("request").innerHTML = "URL: " + url + "<br>"
                    + "Method: POST <br>" + "Data:" + JSON.stringify(params);

            request.open("POST", url);

            //Use MPS RESTful API to set Content-Type
            request.setRequestHeader("Content-Type", "application/json");

            request.onload = function()
            {   //Use MPS RESTful API to check HTTP Status
                if (request.status == 200) 
                {
                    // Deserialization: Converting text back into JSON object
                    // Response from server is deserialized 
                    var result = JSON.parse(request.responseText);
					
                    //Use MPS RESTful API to retrieve response in "lhs"
                    if('lhs' in result)
                    {  document.getElementById("error").innerHTML = "" ;
                       document.getElementById("price_of_bond_value").innerHTML = "Bond Price: " + result.lhs[0].mwdata; }
                    else { document.getElementById("error").innerHTML = "Error: " + result.error.message; }
                }
                else { document.getElementById("error").innerHTML = "Error:" + request.statusText; }
                document.getElementById("response").innerHTML = "Status: " + request.status + "<br>"
                        + "Status message: " + request.statusText + "<br>" +
                        "Response text: " + request.responseText;
            }
            //Serialization: Converting JSON object to text prior to sending request
            request.send(JSON.stringify(params)); 
        }

        //Get value from slider element of "document" using its ID and update the value field
        //The "document" interface represent any web page loaded in the browser and
        //serves as an entry point into the web page's content.
        function printValue(sliderID, valueID) {
            var x = document.getElementById(valueID);
            var y = document.getElementById(sliderID);
            x.value = y.value;
        }
        //Execute JavaScript and calculate price of bond when slider is moved
        function updatePrice(sliderID, valueID) {
            printValue(sliderID, valueID);
            calculatePrice();
        }

手順 6: HTML コード内への JavaScript の組み込み

次の構文を使用して、前の手順の JavaScript を以下の HTML コード内に組み込みます。

<script src="calculatePrice.js" type="text/javascript"></script>

このコードを bptool.html という名前の HTML ファイルとして保存します。

コード:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang="en">
    <meta charset="UTF-8">
    <title>Bond Pricing Tool</title>
</head>
<body>
    <!-- Embed the JavaScript code here by referencing calculatePrice.js -->
    <script src="calculatePrice.js" type="text/javascript"></script>
    <script>
        //Helper Code: Execute JavaScript immediately after the page has been loaded
        window.onload = function() {
            printValue('coupon_payment_slider', 'coupon_payment_value');
            printValue('num_payments_slider', 'num_payments_value');
            printValue('interest_rate_slider', 'interest_rate_value');
            printValue('facevalue_slider', 'facevalue_value');
            calculatePrice();
        }
    </script>
    <h1><a>Bond Pricing Tool</a></h1>
    <h2></h2>
    This example shows an application that calculates a bond price from a simple formula.<p>
    You run this example by entering the following known values into a simple graphical interface:<p>
      <ul>
        <li>Face Value (or value of bond at maturity) - M</li>
        <li>Coupon payment - C</li>
        <li>Number of payments - N</li>
        <li>Interest rate - i</li>
      </ul>
      The application calculates price (P) based on the following equation:<p>
      P = C * ( (1 - (1 + i)^-N) / i ) + M * (1 + i)^-N<p>
      <hr>
      <h3>M: Face Value </h3>
      <input id="facevalue_value" type="number" maxlength="4" oninput="updatePrice('facevalue_value', 'facevalue_slider')"/>
      <input type="range" id="facevalue_slider" value="0" min="0" max="10000" onchange="updatePrice('facevalue_slider', 'facevalue_value')"/>

      <h3>C: Coupon Payment </h3>
      <input id="coupon_payment_value" type="number" maxlength="4" oninput="updatePrice('coupon_payment_value', 'coupon_payment_slider')" />
      <input type="range" id="coupon_payment_slider" value="0" min="0" max="1000" onchange="updatePrice('coupon_payment_slider', 'coupon_payment_value')"/>
            
      <h3>N: Number of payments  </h3>
      <input id="num_payments_value" type="number" maxlength="4" oninput="updatePrice('num_payments_value', 'num_payments_slider')"/>
      <input type="range" id="num_payments_slider" value="0" min="0" max="1000" onchange="updatePrice('num_payments_slider', 'num_payments_value')"/>
      
      <h3>i: Interest rate </h3>
      <input id="interest_rate_value" type="number" maxlength="4" step="0.01" oninput="updatePrice('interest_rate_value', 'interest_rate_slider')"/>
      <input type="range" id="interest_rate_slider" value="0" min="0" max="1" step="0.01" onchange="updatePrice('interest_rate_slider', 'interest_rate_value')"/>

    <h2>BOND PRICE</h2>
    <p id="price_of_bond_value" style="font-weight: bold">
    <p id="error" style="color:red">

    <hr>
    <h3>Request to MPS Server</h3>
    <p id="request">
    
    <h3>Response from MPS Server</h3>
    <p id="response">
    <hr>
</body>
</html>

手順 7: 例の実行

デプロイされた MATLAB 関数をもつサーバーが実行されていることを確認します。Web ブラウザーで、HTML ファイル bptool.html を開きます。値がまだ入力されていないため、既定の債券価格は NaN です。以下の値を試して債権に価格を設定します。

  • 額面価格 = $1000

  • 利払い = $100

  • 支払い回数 = 5

  • 金利 = 0.08 (8% に相当)

結果として生じる債券価格は $1079.85 です。

異なる債権に価格を設定するには、ツールのスライダーを使用します。金利を変化させると、債権の価格が最も劇的に変化します。

View of the bond pricing tool. There are fields that contain values for a bond at maturity, coupon payment, number of payments, interest rate, and the calculated bond price. The bottom section displays HTTP status codes, messages, and payloads for the HTTP request and response.

参考

トピック