Advertisement
Guest User

Untitled

a guest
Feb 6th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. package trading_game;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import exceptions.InsufficientFundsException;
  7. import exceptions.InsufficientSharesException;
  8. import game.BaseTradingStrategy;
  9. import game.DailyInput;
  10. import game.DailyOutput;
  11.  
  12. public class TradingStrategy extends BaseTradingStrategy {
  13.  
  14. public TradingStrategy (){
  15. // Initialise any variables needed.
  16.  
  17. }
  18.  
  19. // input starts from the most recent day
  20. public double crossoverEMA(List<DailyInput> l){
  21. double ema = 0;
  22. Double[] alphas = new Double[l.size()];
  23. double a = 2 / (1 + l.size());
  24. double divider = 0;
  25. for (int i = 0; i < l.size(); i++) {
  26. alphas[i] = Math.pow(1 - a, i);
  27. divider += alphas[i];
  28. }
  29. assert divider != 0;
  30. // calculate the ema
  31. double sum = 0;
  32. for (int i = 0; i < l.size(); i++) {
  33. // get the avg
  34. DailyInput in = l.get(i);
  35. double avg = (in.getClose() + in.getOpen() + in.getHigh() + in.getLow() ) / 4;
  36. sum += alphas[i] * avg;
  37. }
  38. return sum / divider;
  39. }
  40. // list of a COMPANY stock (each element represents the stocks of one company)
  41. List<DailyInput> pastStock = new ArrayList<DailyInput>();
  42. @Override
  43. public DailyOutput makeDailyTrade(DailyInput input) throws InsufficientFundsException, InsufficientSharesException {
  44. // add the most recent day from
  45. if(input.getRemainingDays() == 0){
  46. pastStock = new ArrayList<DailyInput>();
  47. pastStock.add(0, input);
  48. }
  49. else
  50. pastStock.add(0, input);
  51.  
  52. //get the Exponential Moving Average for the stock chart
  53. double crossover = crossoverEMA(pastStock);
  54.  
  55. // compare with closing price
  56. double crossprice = input.getClose() - crossover;
  57.  
  58. System.out.println(crossprice);
  59.  
  60. DailyOutput output;
  61. if (input.getDay() % 2 == 0) {
  62. output = tradingManager.buyMaxNumberOfShares(input);
  63.  
  64. } else {
  65. output = tradingManager.sellAllShares(input);
  66. }
  67.  
  68. return output;
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement