котировки акций с javascript

Кто-нибудь знает способ получить котировки акций в реальном времени или с задержкой на 20 минут с помощью javascript? Я просмотрел API Google по адресу http://code.google.com/apis/finance/docs/finance-gadgets.html, но получить работающий пример было очень сложно.

Кто-нибудь получил его для работы, чтобы получить котировку для любой акции, или нашел лучший способ?

благодарю вас.


person Abraham Adam    schedule 01.03.2011    source источник


Ответы (6)


Это заняло некоторое время, но вот рабочий код, использующий Yahoo! YQL и jQuery:

<script type="text/javascript" src="jquery-1.5.1.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
            var symbol='goog';
            var callback = function(data) {
                    var price=data.query.results.span[0].content;
                    alert('Stock Price: ' + price);
                };

            var url = 'http://query.yahooapis.com/v1/public/yql';
            // this is the lovely YQL query (html encoded) which lets us get the stock price:
            // select * from html where url="http://finance.yahoo.com/q?s=goog" and xpath='//span[@id="yfs_l10_goog"]'
            var data = "q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fq%3Fs%3D" + symbol + "%22%20and%20xpath%3D'%2F%2Fspan%5B%40id%3D%22yfs_l10_" + symbol + "%22%5D'&format=json";
            $.getJSON(url, data, callback);
    });
</script>
person troutinator    schedule 01.03.2011
comment
Большое спасибо, мне удалось последовать вашему примеру и получить изменение цены в % и изменение цены на основе идентификатора. интересно, как бы я сделал то же самое для тех, у которых нет идентификатора, например, 1y Target Est. - person Abraham Adam; 01.03.2011

немного поздно, но я сделал рабочий код :))) счастливый код человек: вы можете поставить индекс, а после него показать все изображения и номера индекса

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
<title>IGotMessage - Finances</title>
<link href="stock_chart_yahoo_finance/styles.css" type="text/css" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="Get stock quotes, research investments and read business news that help you manage your financial life." name="description">
<meta content="financial Information,investing,investor,market news,stock research,business news,economy,finance,personal finance,quote,loan,student loan,morgage loan,car loan" name="keywords">
<meta content="all" name="robots">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script language="JavaScript">
function start(){
    getData();
    document.getElementById('link1').click();
}
function getData() {
var url = "http://query.yahooapis.com/v1/public/yql";
var symbol = $("#symbol").val();
var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol + "')");

$.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env")
    .done(function (data) {

         $("#name").text("Bid Price: " + data.query.results.quote.Symbol);
         $("#date").text("Bid Price: " + data.query.results.quote.Date);
         $("#time").text("Bid Price: " + data.query.results.quote.LastTradeTime);
         $("#result").text("Bid Price: " + data.query.results.quote.LastTradePriceOnly);
         $("#chg").text("Bid Price: " + data.query.results.quote.PercentChange);
         $("#bid").text("Bid Price: " + data.query.results.quote.LastTradePriceOnly);
         $("#ask").text("Bid Price: " + data.query.results.quote.Ask);
         $("#volume").text("Bid Price: " + data.query.results.quote.Volume);
         $("#high").text("Bid Price: " + data.query.results.quote.HighLimit);
         $("#low").text("Bid Price: " + data.query.results.quote.LowLimit);

         if(data.query.results.quote.PercentChange.indexOf("+") != -1){

            document.getElementById("chg").className = "greenText";
        }
         else{
            //alert(data.query.results.quote.PercentChange);

            document.getElementById("chg").className = "redText";
        }

}).fail(function (jqxhr, textStatus, error) {
    var err = textStatus + ", " + error;
        $("#result").text('Request failed: ' + err);
});
}
function SendRequest()
{

    getData();
    document.getElementById('link1').click();
}   

function CheckEnter(e)
{
    if ((e.keyCode && e.keyCode==13) || (e.which && e.which==13)) {
        return SendRequest();
    }
    return true;
}       

function changeChart(select, item, url, symbol)
{   
    url = url.replace('yhoo',$("#symbol").val());
    symbol = symbol.replace('YHOO',$("#symbol").val());
    var div1d=document.getElementById("div1d_"+item);
    var div5d=document.getElementById("div5d_"+item);
    var div3m=document.getElementById("div3m_"+item);
    var div6m=document.getElementById("div6m_"+item);
    var div1y=document.getElementById("div1y_"+item);
    var div2y=document.getElementById("div2y_"+item);
    var div5y=document.getElementById("div5y_"+item);
    var divMax=document.getElementById("divMax_"+item);
    var divChart=document.getElementById("imgChart_"+item);
    if(div1d==null || div5d==null || div3m==null || div6m==null || div1y==null || div2y==null || div5y==null || divMax==null || divChart==null)
        return;
    div1d.innerHTML="1d";
    div5d.innerHTML="5d";
    div3m.innerHTML="3m";
    div6m.innerHTML="6m";
    div1y.innerHTML="1y";
    div2y.innerHTML="2y";
    div5y.innerHTML="5y";
    divMax.innerHTML="Max";
    var rand_no = Math.random();
    rand_no = rand_no * 100000000;
    switch(select)
    {
    case 0:
        div1d.innerHTML ="<b>1d</b>";
        divChart.src = "http://ichart.finance.yahoo.com/b?s="+symbol+"&"+rand_no;
        break;
    case 1:
        div5d.innerHTML="<b>5d</b>";
        divChart.src = "http://ichart.finance.yahoo.com/w?s="+symbol+"&"+rand_no;
        break;
    case 2:
        div3m.innerHTML="<b>3m</b>";
        divChart.src = "http://chart.finance.yahoo.com/c/3m/"+url+"?"+rand_no;
        break;
    case 3:
        div6m.innerHTML="<b>6m</b>";
        divChart.src = "http://chart.finance.yahoo.com/c/6m/"+url+"?"+rand_no;
        break;
    case 5:
        div2y.innerHTML="<b>2y</b>";
        divChart.src = "http://chart.finance.yahoo.com/c/2y/"+url+"?"+rand_no;
        break;
    case 6:
        div5y.innerHTML="<b>5y</b>";
        divChart.src = "http://chart.finance.yahoo.com/c/5y/"+url+"?"+rand_no;
        break;
    case 7:
        divMax.innerHTML="<b>msx</b>";
        divChart.src = "http://chart.finance.yahoo.com/c/my/"+url+"?"+rand_no;
        break;
    case 4:
    default:
        div1y.innerHTML="<b>1y</b>";
        divChart.src = "http://chart.finance.yahoo.com/c/1y/"+url+"?"+rand_no;
        break;
    }
}
</script>
</head>

<body style="margin: 0px;" bgcolor="#678fc2" onload="start();">

<div align="center" style="background:url(stock_chart_yahoo_finance/main_body.jpg); width:900px; margin:50px auto; padding:20px;">

<table width="90%" border="0" cellpadding="0" cellspacing="0" align="center">
<tbody>
  <tr valign="top">
    <td class="normalText" align="left">
        <input name="txtQuote" id="symbol" onkeypress="return CheckEnter(event);" value="YHOO" type="text" />
        <input name="button" type="button" id="btnQuote" onclick="return SendRequest();" value="Get Quotes" />
        <br />
        <span class="smallText">e.g. &quot;YHOO or YHOO GOOG&quot;</span>

        <div id="service" style="padding:10px 0;">
            <table style="border: 1px solid black;" width="770">
              <tbody>
                <tr style="font-size: 14px; font-family: Arial,Helvetica,sans-serif; font-weight: bold;">
                    <td>Symbol</td>
                    <td>Date</td>
                    <td>Time</td>
                    <td>Trade</td>
                    <td>% Chg</td>
                    <td>Bid</td>
                    <td>Ask</td>
                    <td>Volume</td>
                    <td>High</td>
                    <td>Low</td>
                </tr>
                <tr style="font-family: Arial,Helvetica,sans-serif; font-size: 14px; padding: 0px 2px;">
                    <td id="name">YHOO</td>
                    <td id="date">3/11/2011</td>
                    <td id="time">5:00pm</td>
                    <td id="result">$17.42</td>
                    <td id="chg"><span id="colorText" class="greenText">+0.36(+2.11%)</span></td>
                    <td id="bid">17.30</td>
                    <td id="ask">17.77</td>
                    <td id="volume">19,455,986</td>
                    <td id="high">17.54</td>
                    <td id="low">17.00</td>
                </tr>
            </tbody>
          </table>
          <br />
          <img id="imgChart_0" src="stock_chart_yahoo_finance/yhoo.png" border="0" /><br />
          <a class="linkText" href='javascript:changeChart(0,0,%20&quot;y/yhoo&quot;,%20&quot;YHOO&quot;);'><span id="div1d_0">1d</span></a>&nbsp;&nbsp;
          <a class="linkText" href='javascript:changeChart(1,0,%20&quot;y/yhoo&quot;,%20&quot;YHOO&quot;);'><span id="div5d_0">5d</span></a>&nbsp;&nbsp;
          <a class="linkText" href='javascript:changeChart(2,0,%20&quot;y/yhoo&quot;,%20&quot;YHOO&quot;);'><span id="div3m_0">3m</span></a>&nbsp;&nbsp;
          <a class="linkText" href='javascript:changeChart(3,0,%20&quot;y/yhoo&quot;,%20&quot;YHOO&quot;);'><span id="div6m_0">6m</span></a>&nbsp;&nbsp;
          <a class="linkText" href='javascript:changeChart(4,0,%20&quot;y/yhoo&quot;,%20&quot;YHOO&quot;);'><span id="div1y_0">1y</span></a>&nbsp;&nbsp;
          <a class="linkText" href='javascript:changeChart(5,0,%20&quot;y/yhoo&quot;,%20&quot;YHOO&quot;);'><span id="div2y_0">2y</span></a>&nbsp;&nbsp;
          <a class="linkText" href='javascript:changeChart(6,0,%20&quot;y/yhoo&quot;,%20&quot;YHOO&quot;);'><span id="div5y_0">5y</span></a>&nbsp;&nbsp;
          <a id="link1" class="linkText" href='javascript:changeChart(7,0,%20&quot;y/yhoo&quot;,%20&quot;YHOO&quot;);'><span id="divMax_0"><b>msx</b></span></a>
          <br />
        </div>
    </td>
</tr>
</tbody>

CSS:

                   body 
        { 
          margin:0; 
          padding:0; 
          height:100%;
            }
        h1
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: black;
            text-decoration: none;
            font-weight: normal;    
            margin:0 0 0 0;
        }
        .postTitle
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            color: Blue;
            font-weight: bold;  
            text-decoration: underline;
        }
        .readon
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            color: Red;
            font-weight: bold;  
            text-decoration: underline; 
        }   
        .titleText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            color: #000;
            text-decoration: none;
            font-weight: bold;  
        }
        .subtitleText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #000;
            text-decoration: none;
            font-weight: bold;  
        }
        .normalText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #000;
            text-decoration: none;
        }
        .bigText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 16px;
            color: black;
            font-weight: bold;  
        }
        .grayText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: Blue;
            text-decoration: underline;
            font-weight: bold;      
        }
        .barText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #000;
            padding-top: 10px;
            border-bottom: solid 1px #000;
            text-decoration: none;
            font-weight: bold;  
        }
        .dateText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #666;
            text-decoration: none;
            font-weight: bold;      
        }
        .linkText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: Blue;
        }
        .normalLinkText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            color: Blue;
        }
        .linkGrayText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: Blue;
        }
        .errorText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #ff0000;
            text-decoration: none;
        }
        .greenText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: rgb(83, 241, 83);
            text-decoration: none;
        }
        .redText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: Red;
            text-decoration: none;
        }
        .programText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            text-decoration: none;
        }
        .programGrayText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            color: #666;
            text-decoration: none;
        }
        .programGreenText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            color: Green;
            text-decoration: none;
        }
        .smallText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 11px;
            color: #666;
            text-decoration: none;
        }
        .smallLinkText 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 11px;
            color: Blue;
            text-decoration: underline;
        }
        .greenButton
        {
            margin: 0;
            border: 0;
            background: URL(images/greenbuttonbg.gif) no-repeat;
            height: 21px;
            width: 120px;
            color: #FFFFFF;
            font-family: Arial, Helvetica, Sans-serif;
            font-size: 14px;
            margin: 0px;
            padding-top: 2px;
            padding-bottom: 2px;
            vertical-align:middle;
            overflow: hidden;
            cursor:pointer;
            cursor:hand;
        }
        /*
        Tabs
        */
        :focus { -moz-outline-style: none; }
        #header ul 
        {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        #header li 
        {
            float: left;
            border-left: 1px solid #d0d0d0;
            border-right: 1px solid #212121;
            border-bottom-width: 0;
            margin: 0 0em   
        }
        #header a 
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;        
            text-decoration: none;
            display: block;
            background: URL(images/tabbg.gif) repeat;
            padding: 0.2em 1em 0.2em 1em;
            color: white;
            text-align: center;
            font-weight: bold;  
        }
        #header a:hover 
        {
            background: URL(images/tabhoverbg.gif) repeat;
        }
        #header #selected 
        {
            border-color: #E2C068;
            background: #E2C068;
        }
        #header #selected a 
        {
            position: relative;
            top: 1px;
            background: #E2C068;
            color: #000;
            font-weight: bold;  
        }
        #content 
        {
            background: #E2C068;
            clear: both;
            padding: 0.2em 1em 0.2em;
        }
        .bgWhite
        {
            background-color:White;
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: black;
            text-decoration: none;
            font-weight: normal;    
        }   
        .thNormalText
        {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 14px;
            color: #000;    
            background-color:#E2C068;
        }   
person T-student    schedule 08.04.2014

чтобы вставить финансовые котировки Javasript в html, вы можете проверить в разделе для веб-мастеров Forexpros. Вам просто нужно скопировать/вставить код, и их финансовые графики высокого качества. Я использовал их для своего сайта.

person Azurwebdev    schedule 29.01.2012

Здесь может пригодиться плагин jQuery для котировок акций jquery-stockquotes.

Twitter:  <span class="stock-quote" data-symbol="TWTR"></span>
Facebook: <span class="stock-quote" data-symbol="FB"></span>
Google:   <span class="stock-quote" data-symbol="GOOGL"></span>
Netflix:  <span class="stock-quote" data-symbol="NTFLX"></span>
Yahoo:    <span class="stock-quote" data-symbol="YHOO"></span>

<script>
$('.stock-quote').stockQuotes();
</script>

Производство:

введите здесь описание изображения

Ссылка на Github: https://github.com/ajwhite/jquery-stockquotes

Пример блога: https://atticuswhite.com/blog/jquery-stock-quotes/

person Atticus    schedule 07.01.2016

Я создал новую библиотеку под названием stocks.js, она обеспечивает простой в использовании фондовый рынок. API, который может получать оперативные биржевые данные (обновляются каждую минуту). Источником данных является Alpha Vantage.

Пример использования:

// Let's get the stock data of Tesla Inc. for the last 10 minutes
var result = stocks.timeSeries({
  symbol: 'TSLA',
  interval: '1min',
  amount: 10
 });
person Thomas Wagenaar    schedule 21.07.2017

Этот код извлекает информацию о нескольких акциях из Yahoo Finance. Плагин не нужен, только jQuery. Я получил остальную конечную точку по адресу https://developer.yahoo.com/yql/console/, под столом сообщества yahoo.finance.quote.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    var symbols= ["goog", "aapl", "msft"];
    var callback = function(data) {
       var results = "";
       $.each(data.query.results.quote, function(i, value){
          results += value.Name + ":$" + value.LastTradePriceOnly + " ";
       })
       alert(results);
    };

    var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20("
    $.each(symbols, function(j, code){
       url += "%22" + code + "%22";
       if (j < (symbols.length-1)){
          url += "%2C";
       }
    });
    url += ")&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
    $.getJSON(url, callback);
  });
</script>

person Roskow    schedule 26.07.2017