⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 querythestock.java

📁 股票投资管理系统
💻 JAVA
字号:
package querystock;
import java.net.*;
import java.util.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import querystock.WebsiteDataException;
import querystock.NoSuchTickerException;

/**
 * QueryTheStock is a utility class that can retrieve the latest market value of
 * a given stock by ticker symbol.
 * The QueryTheStock obtains the stock value by using the website:
 * http://finance.cn.yahoo.com/fin/finance_search_result.html?s=
 * A valid ticker symbol is one that is currently registered with either the
 * Shanghai Stock Exchange (SSE) or The Stock Exchange of Hong Kong  .
 * Examples of valid ticker symbols are <tt>ZGLY</tt> and <tt>NFHK</tt>. *
 */


public class QueryTheStock {

    protected static final String _URL = "http://finance.cn.yahoo.com/fin/finance_search_result.html?s=";
    protected static final String _TOKEN1 = "searbg3";
    protected static final String _TOKEN2 = "new_price";
    //protected static final String _DELIMITER = "</>\"=";
    protected static final String _DELIMITER = ":</>\"=";
    protected static final String _TOKEN3 = "currticker=";
    protected static final String _TOKEN4 = "&symbols=";
    protected static final String _TOKEN5 = "mwsymbollookupstandard";
    protected static boolean stocktypeAH=true;

    protected static HashMap names = new HashMap();
    protected static final String USAGE = "USAGE: java querystock.QueryTheStock <tickerSymbol>";

    /**
     *
     * Retrieve the latest market value of a stock.
     *
     * @requires: tickerSymbol != null
     * @effects: Returns a current value for tickerSymbol. The return value may contain commas.
     *          Examples: "120.50", "2,243.87".
     *          Throws NoSuchTickerException if tickerSymbol is not a valid SSE or SEHK
     *          symbol and throws WebsiteDataException if there is an error
     *          connecting to the website or some other error occurs.
     */
    public static String getLastValue(String tickerSymbol)
      throws WebsiteDataException, NoSuchTickerException {
      // the web page queried by the code below can be broken into tokens
      // with delimiters being <, >, and =.  The token corresponding to
      // the current stock price comes after the two tokens: searbg3 or new_price

      String strURLStart = _URL;
      URL urlWebPage = null;
      InputStreamReader isr = null;
      BufferedReader brWebPage = null;

      // open the web page for reading
      try {
        //System.out.println(strURLStart + tickerSymbol);
        urlWebPage = new URL(strURLStart + tickerSymbol);
        isr = new InputStreamReader(urlWebPage.openStream());
        brWebPage = new BufferedReader(isr);
      } catch(Exception e) {
        throw new WebsiteDataException();
      }

      // find the line with the stock quote on it
      String strLine = null;
      try {
        while(true) {
          strLine = brWebPage.readLine();
          if(strLine == null)
            {
              throw new NoSuchTickerException("Invalid ticker symbol!");
            }
          if((strLine.indexOf(_TOKEN2) != -1) || (strLine.indexOf(_TOKEN1) != -1))
            break;
        }
      } catch(IOException e) {
        throw new WebsiteDataException();
      }

      if(strLine.indexOf(_TOKEN1) != -1)
        try {
          for (int i = 3; i >= 1; i--)
            strLine = brWebPage.readLine();
        } catch(IOException e) {
        throw new WebsiteDataException();
      }

      // find the stock quote in the line
       String strStockValue="";
      StringTokenizer strtok = new StringTokenizer(strLine, _DELIMITER);

      while(true) {
        if(strtok.hasMoreTokens() == false){
          break;
          //throw new NoSuchTickerException("NoFind valid stock quote!");
        }
        if(strtok.nextToken().compareTo("new_price" ) == 0) {
          stocktypeAH = false;
          break;
        }
      }
     // ****
     StringTokenizer strtokAH = new StringTokenizer(strLine, _DELIMITER);
     while(stocktypeAH==true) {
        if(strtokAH.hasMoreTokens() == false){
          System.out.println(strLine);
          throw new NoSuchTickerException("NoFind valid stock quote!");
        }
        if (strtokAH.nextToken().compareTo("color" ) == 0)
          break;
      }

      if(stocktypeAH==false)
      strStockValue = strtok.nextToken("\"></") ;
      if(stocktypeAH==true)
        {
          strStockValue = strtokAH.nextToken(":\"<>/");
          strStockValue=strtokAH.nextToken();
        }
     //else if(strtok.nextToken().compareTo("color" ) == 0)
       // strStockValue = strtok.nextToken(":\"<>/"); //format the stock price

      // close the web page stream
      try {
        brWebPage.close();
        isr.close();
      } catch(IOException e) {
        throw new WebsiteDataException();
      }

      return strStockValue;
    }

    /**
     * Retrieve the company name associated with a stock.
     *
     * @requires: tickerSymbol != null
     * @effects:  Returns the company name associated with tickerSymbol.
     *          Throws NoSuchTickerException if tickerSymbol is not a valid NYSE or NASDAQ
     *          symbol and throws WebsiteDataException if there is an error
     *          connecting to the website or some other error occurs.
     * @modifies: QueryTheStock.names
     */
    public static String getNameFromTicker(String tickerSymbol) throws WebsiteDataException, NoSuchTickerException {
          String strStockName = (String)QueryTheStock.names.get(tickerSymbol);
          if (strStockName != null)
            return strStockName;

          tickerSymbol = tickerSymbol.toUpperCase();
          String strURLStart ="";
          URL urlWebPage = null;

          InputStreamReader isr = null;
          BufferedReader brWebPage = null;
          String nameLookupToken = _TOKEN3+tickerSymbol+_TOKEN4+tickerSymbol;

          // open the web page for reading
          // System.out.println(nameLookupToken);
          try {
            urlWebPage = new URL(strURLStart + tickerSymbol);
            isr = new InputStreamReader(urlWebPage.openStream());
            brWebPage = new BufferedReader(isr);
          } catch(Exception e) {
            throw new WebsiteDataException();
          }

          // find the line with the stock quote on it
          String strLine = null;
          try {
            while(true) {
              strLine = brWebPage.readLine();
              if(strLine == null) {
                throw new NoSuchTickerException("Invalid ticker symbol!");
                //throw new WebsiteDataException("Parse failed!");
              }
              //System.out.println(strLine);
              if(strLine.indexOf(nameLookupToken) != -1)
                break;
            }
          }
          catch(IOException e) {
            throw new WebsiteDataException();
          }

          // find the stock quote in the line
          StringTokenizer strtok = new StringTokenizer(strLine, _DELIMITER);

          while(true) {
            if(strtok.hasMoreTokens() == false) {
              throw new NoSuchTickerException("Invalid ticker symbol!");
            }
            if(strtok.nextToken().compareTo(_TOKEN5) == 0) {
              strStockName = strtok.nextToken();
              if (strStockName.substring(0, 5).compareTo("nbsp;") == 0)
                break;
            }
          }

          strStockName = strStockName.substring(5);
          QueryTheStock.names.put(tickerSymbol, strStockName);
          return strStockName;
        }



  public QueryTheStock() {
  }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -