diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/main/java/edu/brown/cs/student/term/Main.java | 43 | ||||
-rw-r--r-- | src/main/java/edu/brown/cs/student/term/ProfitCalculation.java | 126 |
2 files changed, 101 insertions, 68 deletions
diff --git a/src/main/java/edu/brown/cs/student/term/Main.java b/src/main/java/edu/brown/cs/student/term/Main.java index 7b9c9fc..08cadd7 100644 --- a/src/main/java/edu/brown/cs/student/term/Main.java +++ b/src/main/java/edu/brown/cs/student/term/Main.java @@ -46,6 +46,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.*; + import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import joptsimple.OptionParser; @@ -65,6 +66,7 @@ import freemarker.template.Configuration; import org.json.JSONObject; + import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @@ -130,7 +132,7 @@ public final class Main { return new FreeMarkerEngine(config); } - public void runSparkServer(int port) { + public void runSparkServer(int port) { Spark.port(port); Spark.externalStaticFileLocation("src/main/resources/static"); Spark.exception(Exception.class, new ExceptionPrinter()); @@ -138,26 +140,26 @@ public final class Main { Spark.options("/*", (request, response) -> { - String accessControlRequestHeaders = request - .headers("Access-Control-Request-Headers"); - if (accessControlRequestHeaders != null) { - response.header("Access-Control-Allow-Headers", - accessControlRequestHeaders); - } - - String accessControlRequestMethod = request - .headers("Access-Control-Request-Method"); - if (accessControlRequestMethod != null) { - response.header("Access-Control-Allow-Methods", - accessControlRequestMethod); - } - - return "OK"; + String accessControlRequestHeaders = request + .headers("Access-Control-Request-Headers"); + if (accessControlRequestHeaders != null) { + response.header("Access-Control-Allow-Headers", + accessControlRequestHeaders); + } + + String accessControlRequestMethod = request + .headers("Access-Control-Request-Method"); + if (accessControlRequestMethod != null) { + response.header("Access-Control-Allow-Methods", + accessControlRequestMethod); + } + + return "OK"; }); - + Spark.before((request, response) -> response.header("Access-Control-Allow-Origin", "*")); - Spark.post("/data", new DataHandler()); + Spark.post("/data", new DataHandler()); } @@ -167,7 +169,7 @@ public final class Main { String str = request.body(); xmlLinks = new JSONObject(str); //this is all the filedAt times and xml files - try{ + try { DatabaseQuerier db = new DatabaseQuerier("data/trades.sqlite3"); LinkMapper lm = new LinkMapper(db); @@ -178,7 +180,7 @@ public final class Main { HubSearch hub = new HubSearch(lm); Map<Holder, Double> him = hub.runHubSearch(start, end); return GSON.toJson(him); - } catch(Exception e){ + } catch (Exception e) { System.out.println("DBQuerier Test, couldn't connect to db???"); return "Error"; } @@ -187,7 +189,6 @@ public final class Main { /** * Display an error page when an exception occurs in the server. - * */ private static class ExceptionPrinter implements ExceptionHandler { @Override diff --git a/src/main/java/edu/brown/cs/student/term/ProfitCalculation.java b/src/main/java/edu/brown/cs/student/term/ProfitCalculation.java index aa1bc09..19b439e 100644 --- a/src/main/java/edu/brown/cs/student/term/ProfitCalculation.java +++ b/src/main/java/edu/brown/cs/student/term/ProfitCalculation.java @@ -2,17 +2,12 @@ package edu.brown.cs.student.term; import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; import java.net.URI; -import java.net.URL; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; @@ -24,7 +19,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; -import java.util.List; import java.util.HashMap; import java.util.Map; @@ -51,6 +45,9 @@ public class ProfitCalculation { //map of stock to gains from increases in value of holdings private Map<String, Double> unrealizedGainsMap; + //map to store current prices of stocks -- to avoid repeated api calls + private Map<String, Double> currentStockPrices; + private double moneyInput; /** @@ -70,16 +67,16 @@ public class ProfitCalculation { sellHistoryMap = new HashMap<>(); realizedGainsMap = new HashMap<>(); unrealizedGainsMap = new HashMap<>(); + currentStockPrices = new HashMap<>(); } /** - * This method fills the maps of sell and buy orders with lists of oldest - new trades + * This method fills the maps of sell and buy orders with lists of oldest - new trades. */ private void organizeOrders() { //get a list of trades for a person to consider try { PreparedStatement prep; - // TODO: add start and end time prep = conn.prepareStatement("SELECT * FROM \'trades\' WHERE holder_name= ? " + " AND trade_timestamp BETWEEN ? AND ?" @@ -92,7 +89,7 @@ public class ProfitCalculation { while (rs.next()) { String ticker = rs.getString("stock_name"); int shares = rs.getInt("number_of_shares"); - double price = rs.getDouble("price"); + double price = rs.getDouble("share_price"); OrderTuple order = new OrderTuple(shares, price, rs.getDate("trade_timestamp")); //one element list for first time ticker is seen. @@ -107,9 +104,7 @@ public class ProfitCalculation { } else { buyHistoryMap.put(ticker, oneElement); } - } - //for sell orders build up sell history - else { + } else { //ignore sell orders for which we do not have buys for if (buyHistoryMap.containsKey(ticker)) { if (sellHistoryMap.containsKey(ticker)) { @@ -128,7 +123,7 @@ public class ProfitCalculation { } /** - * This method processes the sell orders in the sellHistoryMap to get realized gains + * This method processes the sell orders in the sellHistoryMap to get realized gains. */ private void getRealizedGains() { for (String ticker : sellHistoryMap.keySet()) { @@ -177,7 +172,7 @@ public class ProfitCalculation { } /** - * get the change in value of stocks which are still held + * get the change in value of stocks which are still held. */ private void getUnrealizedGains() { @@ -186,16 +181,17 @@ public class ProfitCalculation { double unrealizedGains = 0; double currentPrice = getCurrentPrice(ticker); - LinkedList<OrderTuple> stockHistory = buyHistoryMap.get(ticker); - for (OrderTuple order : stockHistory) { - unrealizedGains += order.getShares() * (currentPrice - order.getCost()); + if (currentPrice != -1) { + LinkedList<OrderTuple> stockHistory = buyHistoryMap.get(ticker); + for (OrderTuple order : stockHistory) { + unrealizedGains += order.getShares() * (currentPrice - order.getCost()); + } } - unrealizedGainsMap.put(ticker, unrealizedGains); } } - private class OrderTuple { + private final class OrderTuple { private int shares; private double cost; private Date date; @@ -224,30 +220,43 @@ public class ProfitCalculation { } private double getCurrentPrice(String ticker) { - String PRICE_URL = BASE_URL + "/last/stocks/" + ticker; + if (currentStockPrices.containsKey(ticker)) { + return currentStockPrices.get(ticker); + } else { + String PRICE_URL = BASE_URL + "/last/stocks/" + ticker; + + HttpClient client = HttpClient.newHttpClient(); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(PRICE_URL)).setHeader("APCA-API-KEY-ID", API_KEY) + .setHeader("APCA-API-SECRET-KEY", SECRET_KEY) + .build(); + + HttpResponse<String> response = null; + try { + response = client.send(request, + HttpResponse.BodyHandlers.ofString()); + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(PRICE_URL)).setHeader("APCA-API-KEY-ID", API_KEY) - .setHeader("APCA-API-SECRET-KEY", SECRET_KEY) - .build(); - HttpResponse<String> response = null; - try { - response = client.send(request, - HttpResponse.BodyHandlers.ofString()); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); + JSONObject object = new JSONObject(response.body()); + try { + double price = object.getJSONObject("last").getDouble("price"); + currentStockPrices.put(ticker, price); + return price; + } catch (JSONException e) { + currentStockPrices.put(ticker, -1.0); + return -1.0; + } } - JSONObject object = new JSONObject(response.body()); - return object.getJSONObject("last").getDouble("price"); } - public void calculateGains() { + public double calculateGains() { organizeOrders(); getRealizedGains(); getUnrealizedGains(); @@ -261,15 +270,14 @@ public class ProfitCalculation { for (double value : unrealizedGainsMap.values()) { unrealizedGains += value; } - - double totalGains = unrealizedGains + realizedGains; - - System.out.println("Money In: " + moneyInput); - System.out.println("Money Out: " + (moneyInput + totalGains)); - System.out.println("NASDAQ on money In: " + (moneyInput * compareToSP500())); - System.out.println( - "Total: " + totalGains + "| unrealized: " + unrealizedGains + " | realized: " + - realizedGains); + return unrealizedGains + realizedGains; + +// System.out.println("Money In: " + moneyInput); +// System.out.println("Money Out: " + (moneyInput + totalGains)); +// System.out.println("NASDAQ on money In: " + (moneyInput * compareToSP500())); +// System.out.println( +// "Total: " + totalGains + "| unrealized: " + unrealizedGains + " | realized: " + +// realizedGains); } /** @@ -305,10 +313,34 @@ public class ProfitCalculation { double endPrice = object.getJSONObject(object.length() - 1).getDouble("c"); //get percent change //end - start /start - return 1 + ((endPrice - startPrice) /startPrice); + return 1 + ((endPrice - startPrice) / startPrice); } + /** + * get a map for all people in the timeframe of holder_id to percent gain. + * + * @return a map of holder_id to percent gain + */ + public Map<Integer, Double> getProfitMap() { + Map<Integer, Double> profitMap = new HashMap<>(); + try { + PreparedStatement prep; + prep = + conn.prepareStatement("SELECT * from trades group by holder_name;"); + ResultSet rs = prep.executeQuery(); + while (rs.next()) { + int id = rs.getInt("holder_id"); + this.person = rs.getString("holder_name"); + profitMap.put(id, this.calculateGains() / moneyInput); + } + } catch (SQLException throwables) { + System.out.println("ERROR: SQl error in profit calculation"); + } + System.out.println(profitMap.toString()); + return profitMap; + } + public void setConnection(String filename) throws SQLException, ClassNotFoundException { // Initialize the database connection, turn foreign keys on |