Esempio n. 1
0
  public List<StockInfo> findStockInfoBtw(StockInfo stock, int previousDays, int followingDays) {
    LinkedList<StockInfo> selected = new LinkedList<>();
    int beginIndex = 0;
    List<StockInfo> stocks = getStocks(stock.getTicker());
    for (int i = 0; i < stocks.size(); i++) {
      if (stocks.get(i).getTradeDate().equals(stock.getTradeDate())) {
        beginIndex = i;
        selected.add(stocks.get(beginIndex));
        break;
      }
    }

    for (int i = 1; i <= previousDays; i++) {
      StockInfo addingStock = null;
      try {
        addingStock = stocks.get(beginIndex + i);
        selected.addFirst(addingStock);
      } catch (Exception e) {

      }
    }
    for (int i = 1; i <= followingDays; i++) {
      StockInfo addingStock = null;
      try {
        addingStock = stocks.get(beginIndex - i);
      } catch (Exception e) {

      }
      selected.addLast(addingStock);
    }
    return selected;
  }
  public synchronized Stock getStock(StockInfo info, boolean force) {

    if (info == null) {
      Log.v(TAG, "getStock - info is null");
      return null;
    }

    Log.v(TAG, "getStock - stock_id:" + info.stock_id + ", force:" + force);

    // 先内存
    Stock stock = cache.get(info.getKey());

    // 再sql
    if (stock == null) {
      stock = new Stock(info);
      cache.put(info.getKey(), stock);
    }

    // 最后网络
    if (stock.outOfDate()) {
      cache.remove(info.getKey());
      stock.updateSQL(force); // sync NET and persit to SQL

      stock = new Stock(info); // reload from SQL
      cache.put(info.getKey(), stock);
    }

    return stock;
  }
 private Intent createShareCompanyIntent() {
   Intent shareIntent = new Intent(Intent.ACTION_SEND);
   shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
   shareIntent.setType("text/plain");
   String symbol = mStockInfo.getExchange_market() + ":" + mStockInfo.getTicker();
   shareIntent.putExtra(Intent.EXTRA_TEXT, APP_HASH_TAG + symbol);
   return shareIntent;
 }
Esempio n. 4
0
 public List<StockInfo> findLimitUpStocksOn(String date) {
   List<StockInfo> list = new ArrayList<>();
   for (Map.Entry<String, List<StockInfo>> entry : cache.entrySet()) {
     for (StockInfo stock : entry.getValue()) {
       if (stock.getTradeDate().equals(date) && stock.isLimitUp()) {
         list.add(stock);
       }
     }
   }
   return list;
 }
Esempio n. 5
0
  @Override
  public OrderResult Execute(Order order, IUserBalance balanceService, IStockInfo stockService) {
    OrderResult result = new OrderResult(order);
    Date submitted = order.getDateSubmitted();
    if (today.equals(submitted)) {
      StockInfo info = stockService.requestCurrentStockData(order.getStock().getStockSymbol());
      if (info != null) {
        attemptTrade(
            result,
            balanceService,
            stockService,
            today,
            info.getDayLow(),
            info.getDayHigh(),
            info.getVolume());
      }
    } else // SELL
    {
      Date lastEvaluated = order.getLastEvaluated();
      if (order
          .getDateSubmitted()
          .equals(
              lastEvaluated)) { // do not try to evaluate again the first day the Limit order was
                                // submitted
        lastEvaluated = getDateOneDayInTheFuture(lastEvaluated);
      }

      List<HistoricalStockInfo> infos =
          stockService.requestDailyHistoricalStockData(
              order.getStock().getStockSymbol(), lastEvaluated);
      if (infos != null && infos.size() > 0) {
        HistoricalStockInfo info;
        for (int i = infos.size() - 1; i >= 0; --i) {
          info = infos.get(i);
          attemptTrade(
              result,
              balanceService,
              stockService,
              info.getDate(),
              info.getDayLow(),
              info.getDayHigh(),
              info.getVolume());
          if (result.getCompleted() || result.getCancelled()) {
            break;
          }
        }
      }
    }

    return result;
  }
 private void fetchFinancial() {
   RequestFinancialData requestFinancialData =
       new RequestFinancialData(
           getActivity(),
           new LinearLayout[] {
             mLinearLayout, mIncomeGraph, mBalanceGraph, mCashFlowGraph, mFinancialLayout
           },
           mTextView);
   requestFinancialData.execute(mStockInfo.getTicker());
 }
    // String... arg0 is the same as String[] args
    protected String doInBackground(String... args) {

      try {

        // Get the XML URL that was passed in

        URL url = new URL(args[0]);

        // connection is the communications link between the
        // application and a URL that we will read from.

        URLConnection connection;
        connection = url.openConnection();

        // Used to take advantage of HTTP specific features.
        // Provides tools that tell us if a connection was
        // made, lost and other HTTP Status Codes

        HttpURLConnection httpConnection = (HttpURLConnection) connection;

        // Did we connect properly the the URL?

        int responseCode = httpConnection.getResponseCode();

        // Tests if responseCode == 200 Good Connection
        if (responseCode == HttpURLConnection.HTTP_OK) {

          // Reads data from the connection
          InputStream in = httpConnection.getInputStream();

          // Provides a way to parse DOM object trees from XML documents

          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

          // Provides a DOM Document from an xml page
          DocumentBuilder db = dbf.newDocumentBuilder();

          // Parse the Yahoo Financial YQL Stock XML File
          Document dom = db.parse(in);

          // The root element is query
          Element docEle = dom.getDocumentElement();

          // Get a list of quote nodes
          NodeList nl = docEle.getElementsByTagName("quote");

          // Checks to make sure we found a quote tag
          if (nl != null && nl.getLength() > 0) {

            // Cycles through if we find multiple quote tags
            // Mainly used for demonstration purposes
            for (int i = 0; i < nl.getLength(); i++) {

              // Passes the root element of the XML page, so
              // that the function below can search for the
              // information needed
              StockInfo theStock = getStockInformation(docEle);

              // Gets the values stored in the StockInfo object
              daysLow = theStock.getDaysLow();
              daysHigh = theStock.getDaysHigh();
              yearLow = theStock.getYearLow();
              yearHigh = theStock.getYearHigh();
              name = theStock.getName();
              lastTradePriceOnly = theStock.getLastTradePriceOnly();
              change = theStock.getChange();
              daysRange = theStock.getDaysRange();

              // Outputs information for tracking reasons only
              Log.d(TAG, "Stock Name " + name);
              Log.d(TAG, "Stock Year High " + yearHigh);
              Log.d(TAG, "Stock Year Low " + yearLow);
              Log.d(TAG, "Stock Days High " + daysHigh);
              Log.d(TAG, "Stock Days Low " + daysLow);
            }
          }
        }
      } catch (MalformedURLException e) {
        Log.d(TAG, "MalformedURLException", e);
      } catch (IOException e) {
        Log.d(TAG, "IOException", e);
      } catch (ParserConfigurationException e) {
        Log.d(TAG, "Parser Configuration Exception", e);
      } catch (SAXException e) {
        Log.d(TAG, "SAX Exception", e);
      } finally {
      }

      return null;
    }
Esempio n. 8
0
 public String getLastestDateFor(StockInfo stock) {
   return getLastestDateFor(stock.getTicker());
 }
    @Override
    public View onCreateView(
        LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      //
      Intent intent = getActivity().getIntent();
      View rootView = inflater.inflate(R.layout.fragment_financial, container, false);
      if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
        String[] info = intent.getStringArrayExtra(Intent.EXTRA_TEXT);
        mStockInfo = new StockInfo(info);
        ((TextView) rootView.findViewById(R.id.financial))
            .setText(mStockInfo.getTicker() + " - " + mStockInfo.getCompany_name());
      }
      final CheckBox save = (CheckBox) rootView.findViewById(R.id.financial_chk);
      final String selection = FinancialContract.StockEntry.COLUMN_STOCK_TICKER + " = ?";
      final String[] selectionArgs = {mStockInfo.getTicker()};
      save.setOnClickListener(
          new View.OnClickListener() {
            public void onClick(View v) {
              if (save.isChecked()) {
                // TODO: New a request data task and insert it into DB
                RequestFinancialData requestFinancialData =
                    new RequestFinancialData(getActivity(), mStockInfo);
                requestFinancialData.addStock(mStockInfo);

                Toast.makeText(getActivity(), "Added " + mStockInfo.getTicker(), Toast.LENGTH_SHORT)
                    .show();
              } else {
                // TODO: Remove the data from DB
                getActivity()
                    .getContentResolver()
                    .delete(
                        FinancialContract.StockEntry.CONTENT_URI, // Uri to Query
                        selection, // selection
                        selectionArgs // selectionArgs
                        );

                Toast.makeText(
                        getActivity(), "Unfollow " + mStockInfo.getTicker(), Toast.LENGTH_SHORT)
                    .show();
              }
            }
          });
      // Check with the database to set the checkbox
      Cursor stockCursor =
          getActivity()
              .getContentResolver()
              .query(
                  FinancialContract.StockEntry.CONTENT_URI, // Uri to Query
                  null, // columns (projection)
                  selection, // selection
                  selectionArgs, // selectionArgs
                  null // sort order
                  );
      if (stockCursor.moveToFirst()) {
        save.setChecked(true);
        stockCursor.close();
      } else {
        save.setChecked(false);
        stockCursor.close();
      }

      mLinearLayout = (LinearLayout) rootView.findViewById(R.id.fragment_financial_linear);
      mIncomeGraph = (LinearLayout) rootView.findViewById(R.id.income);
      mBalanceGraph = (LinearLayout) rootView.findViewById(R.id.balance);
      mCashFlowGraph = (LinearLayout) rootView.findViewById(R.id.cashflow);
      mFinancialLayout = (LinearLayout) rootView.findViewById(R.id.financial_highlight);
      mTextView = (TextView) rootView.findViewById(R.id.no_data);

      return rootView;
    }
Esempio n. 10
0
  public StockInfo[] flatMapOfData(Map<String, StockInfo[]> dataToProcess) {
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    dateFormat.applyPattern("dd/MM/YYYY");

    ArrayList<StockInfo> listOfInfo = new ArrayList<StockInfo>();

    int numOfIndexesOutOfBound = 0;
    Set<String> keySetOfDataToProcess = dataToProcess.keySet();
    int[] indexOnStockInfo = new int[keySetOfDataToProcess.size()];
    for (int index = 0; index < indexOnStockInfo.length; index++) {
      indexOnStockInfo[index] = 0;
    }

    // Get the key in an array
    String[] keys = keySetOfDataToProcess.toArray(new String[keySetOfDataToProcess.size()]);

    // Get the min start index to process, this index contains the min startTime
    long minStartIndexTime = Long.MAX_VALUE;

    for (int index = 0; index < keys.length; index++) {
      long tempDate = dataToProcess.get(keys[index])[0].date.getTime();
      minStartIndexTime = minStartIndexTime < tempDate ? minStartIndexTime : tempDate;
    }

    // While any index is still inside of its array boundaries, continue to flat array
    while (numOfIndexesOutOfBound != indexOnStockInfo.length) {
      float openSum = 0;
      float highSum = 0;
      float lowSum = 0;
      float closeSum = 0;
      long volumeSum = 0;

      int count = 0;
      long newMinStartTime = 0;

      // For every key in the set of keys
      for (int index = 0; index < keys.length; index++) {
        // logger.log("if indexOnStockInfo[index] " + indexOnStockInfo[index] + " <
        // dataToProcess.get(keys[index]).length " + dataToProcess.get(keys[index]).length);
        if (indexOnStockInfo[index] < dataToProcess.get(keys[index]).length) {
          StockInfo infoArray = dataToProcess.get(keys[index])[indexOnStockInfo[index]];
          long tempDate = infoArray.date.getTime();
          // logger.log("tempDate = " + dateFormat.format(tempDate));
          if (tempDate == minStartIndexTime) {
            openSum += infoArray.open;
            highSum += infoArray.high;
            lowSum += infoArray.low;
            closeSum += infoArray.close;
            volumeSum += infoArray.volume;
            count++;
            indexOnStockInfo[index]++;
            newMinStartTime = tempDate;
          }
        } else {
          numOfIndexesOutOfBound++;
        }
      }

      minStartIndexTime = Long.MAX_VALUE;
      for (int index = 0; index < keys.length; index++) {
        // logger.log("if indexOnStockInfo[index] " + indexOnStockInfo[index] + " <
        // dataToProcess.get(keys[index]).length " + dataToProcess.get(keys[index]).length);
        if (indexOnStockInfo[index] < dataToProcess.get(keys[index]).length) {
          long tempDate = dataToProcess.get(keys[index])[indexOnStockInfo[index]].date.getTime();
          minStartIndexTime = minStartIndexTime < tempDate ? minStartIndexTime : tempDate;
          logger.log("minStartIndexTime = " + minStartIndexTime);
        }
      }

      // logger.log("count = " + count);

      if (count != 0) {
        StockInfo newStockInfo = new StockInfo();
        newStockInfo.open = openSum / count;
        newStockInfo.high = highSum / count;
        newStockInfo.low = lowSum / count;
        newStockInfo.close = closeSum / count;
        newStockInfo.volume = volumeSum / count;
        newStockInfo.date = new Date(newMinStartTime);

        logger.log("flat date date is " + dateFormat.format(newStockInfo.date.getTime()));

        listOfInfo.add(newStockInfo);
      } else {
        logger.log("count is 0");
      }
    }

    return listOfInfo.toArray(new StockInfo[listOfInfo.size()]);
  }
Esempio n. 11
0
  // Run prediction method on data based on file name
  public StockInfo[] runPrediction(Map<String, StockInfo[]> dataToProcess) {
    double[] resultArrayOpen = null;
    double[] resultArrayHigh = null;
    double[] resultArrayLow = null;
    double[] resultArrayClose = null;
    double[] resultArrayVolume = null;

    StockInfo[] predictedDataArray = null;

    try {
      logger.log("prediction will start");
      // Flat the data to perform prediction on it
      StockInfo[] flatStockInfo = this.flatMapOfData(dataToProcess);
      Collections.reverse(Arrays.asList(flatStockInfo));

      REXP x;
      RVector v;

      // Check for installed packages
      x = re.eval("installed.packages()");
      v = x.asVector();
      String[] packages = x.asStringArray();
      boolean isForecastInstalled = false;
      logger.log("<R> getting installed packages");
      for (int index = 0; index < packages.length && isForecastInstalled == false; index++) {
        logger.log("<R> has installed " + packages[index]);
        if (packages[index] != null && packages[index].compareTo("forecast") == 0) {
          isForecastInstalled = true;
        }
      }

      // If forecast needs to be installed
      if (isForecastInstalled == false) {
        logger.log("<R> will set repos");

        // Set CRAN
        re.eval("r <- getOption(\"repos\")");
        re.eval("r[\"CRAN\"] <- \"http://cran.us.r-project.org\"");
        re.eval("options(repos = r)");
        re.eval("rm(r)");

        // Install forecast
        re.eval("install.packages(\"forecast\")");

        logger.log("<R> will install forecast package");
      }
      // Load forecast library
      re.eval("library(\"forecast\")");
      logger.log("<R> loaded forecast");

      // Make prediction for Open value -----------------------
      // Load data into R
      logger.log("<R> loading data into R");

      StringBuilder builder = new StringBuilder("inputData <- c(");
      for (int index = 0; index < flatStockInfo.length; index++) {
        builder.append(flatStockInfo[index].open);
        if (index != flatStockInfo.length - 1) {
          builder.append(",");
        } else {
          builder.append(")");
        }
      }
      String stringFromBuilder = builder.toString();
      re.eval(stringFromBuilder);
      // Create time series from data
      logger.log("<R> forecasting open values BestFit");
      re.eval("temporalData <- ts(inputData, frequency=365)");
      // Forecast data
      re.eval("forecastData <- forecast(temporalData, h=30)");
      // re.eval("arimaModel <- auto.arima(temporalData, max.p=5, max.q=5, max.P=5, max.Q=5)");
      // re.eval("forecastData <- forecast(arimaModel, h=30)");
      x = re.eval("forecastData");
      v = x.asVector();
      x = (REXP) v.elementAt(1); // instead of 3
      resultArrayOpen = x.asDoubleArray();

      // Make prediction for High value ------------------------
      builder = new StringBuilder("inputData <- c(");
      for (int index = 0; index < flatStockInfo.length; index++) {
        builder.append(flatStockInfo[index].high);
        if (index != flatStockInfo.length - 1) {
          builder.append(",");
        } else {
          builder.append(")");
        }
      }
      stringFromBuilder = builder.toString();
      re.eval(stringFromBuilder);
      // Create time series from data
      logger.log("<R> forecasting high values BestFit");
      re.eval("temporalData <- ts(inputData, frequency=365)");
      // Forecast data
      re.eval("forecastData <- forecast(temporalData, h=30)");
      // re.eval("arimaModel <- auto.arima(temporalData, max.p=5, max.q=5, max.P=5, max.Q=5)");
      // re.eval("forecastData <- forecast(arimaModel, h=30)");
      x = re.eval("forecastData");
      v = x.asVector();
      x = (REXP) v.elementAt(1);
      resultArrayHigh = x.asDoubleArray();

      // Make prediction for Low value ------------------------
      builder = new StringBuilder("inputData <- c(");
      for (int index = 0; index < flatStockInfo.length; index++) {
        builder.append(flatStockInfo[index].low);
        if (index != flatStockInfo.length - 1) {
          builder.append(",");
        } else {
          builder.append(")");
        }
      }
      stringFromBuilder = builder.toString();
      re.eval(stringFromBuilder);
      // Create time series from data
      logger.log("<R> forecasting low values BestFit");
      re.eval("temporalData <- ts(inputData, frequency=365)");
      // Forecast data
      re.eval("forecastData <- forecast(temporalData, h=30)");
      // re.eval("arimaModel <- auto.arima(temporalData, max.p=5, max.q=5, max.P=5, max.Q=5)");
      // re.eval("forecastData <- forecast(arimaModel, h=30)");
      x = re.eval("forecastData");
      v = x.asVector();
      x = (REXP) v.elementAt(1);
      resultArrayLow = x.asDoubleArray();

      // Make prediction for Close value ------------------------
      builder = new StringBuilder("inputData <- c(");
      for (int index = 0; index < flatStockInfo.length; index++) {
        builder.append(flatStockInfo[index].close);
        if (index != flatStockInfo.length - 1) {
          builder.append(",");
        } else {
          builder.append(")");
        }
      }
      stringFromBuilder = builder.toString();
      re.eval(stringFromBuilder);
      // Create time series from data
      logger.log("<R> forecasting close values BestFit");
      re.eval("temporalData <- ts(inputData, frequency=365)");
      // Forecast data
      re.eval("forecastData <- forecast(temporalData, h=30)");
      // re.eval("arimaModel <- auto.arima(temporalData, max.p=5, max.q=5, max.P=5, max.Q=5)");
      // re.eval("forecastData <- forecast(arimaModel, h=30)");
      x = re.eval("forecastData");
      v = x.asVector();
      x = (REXP) v.elementAt(1);
      resultArrayClose = x.asDoubleArray();

      // Make prediction for Close value ------------------------
      builder = new StringBuilder("inputData <- c(");
      for (int index = 0; index < flatStockInfo.length; index++) {
        builder.append(flatStockInfo[index].volume);
        if (index != flatStockInfo.length - 1) {
          builder.append(",");
        } else {
          builder.append(")");
        }
      }
      stringFromBuilder = builder.toString();
      re.eval(stringFromBuilder);
      // Create time series from data
      re.eval("temporalData <- ts(inputData, frequency=365)");
      // Forecast data
      re.eval("forecastData <- forecast(temporalData, h=30)");
      // re.eval("arimaModel <- auto.arima(temporalData, max.p=5, max.q=5, max.P=5, max.Q=5)");
      // re.eval("forecastData <- forecast(arimaModel, h=30)");
      x = re.eval("forecastData");
      v = x.asVector();
      x = (REXP) v.elementAt(1);
      resultArrayVolume = x.asDoubleArray();

      // Create a single StockInfo[] for all data
      StockInfo predictedData;
      predictedDataArray = new StockInfo[30];

      Date lastDate = flatStockInfo[flatStockInfo.length - 1].date;
      Calendar c = Calendar.getInstance();
      c.setTime(lastDate);
      c.add(Calendar.DATE, 1);

      logger.log("<R> values for forecasted data");

      SimpleDateFormat dateFormat = new SimpleDateFormat();
      dateFormat.applyPattern("dd/MM/YYYY");

      // For all days that were predicted
      for (int index = 0; index < 30; index++) {
        predictedData = new StockInfo();
        predictedData.open = (float) resultArrayOpen[index];

        float maxHigh =
            (float)
                StrictMath.max(
                    resultArrayClose[index],
                    StrictMath.max(resultArrayHigh[index], resultArrayOpen[index]));
        predictedData.high = maxHigh;

        float minLow =
            (float)
                StrictMath.min(
                    resultArrayClose[index],
                    StrictMath.min(resultArrayLow[index], resultArrayOpen[index]));
        predictedData.low = minLow;

        predictedData.close = (float) resultArrayClose[index];
        predictedData.volume = (int) resultArrayVolume[index];

        while (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
            || c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
          c.add(Calendar.DATE, 1);
        }
        predictedData.date = c.getTime();

        predictedDataArray[index] = predictedData;

        logger.log(
            "<R> stock prediction "
                + dateFormat.format(predictedData.date.getTime())
                + " open: "
                + predictedData.open
                + " high: "
                + predictedData.high
                + " low: "
                + predictedData.low
                + " close: "
                + predictedData.close);
        c.add(Calendar.DATE, 1);
      }

    } catch (Exception e) {
      logger.logException(e);
    }

    return predictedDataArray;
  }