Advertisement
Guest User

Untitled

a guest
Nov 26th, 2015
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. # Algorithm to calculate the best stocks to buy based on their forecasts and taking into account transaction costs when
  2. # selling one stock for another.
  3.  
  4. stock_predictions = {
  5. 'APPL': [1, 1, 1, 10, 1, 1],
  6. 'GOOG': [0, 0, 0, 0, 0, 10],
  7. 'MSFT': [0, 0, 10, 0, 0, 0]
  8. }
  9.  
  10.  
  11. class Node:
  12. def __init__(self, stock, day, unit_value, total_value, parent):
  13. self.stock = stock
  14. self.day = day
  15. self.unit_value = unit_value
  16. self.total_value = total_value
  17. self.parent = parent
  18. self.children = []
  19.  
  20. def __str__(self):
  21. return 'Stock: ' + self.stock + ' on day ' + str(self.day) + ' trading at ' + str(
  22. self.unit_value) + '. Total Value: ' + str(self.total_value)
  23.  
  24.  
  25. def add_nodes(node, stocks, day, transaction_cost):
  26. length = len(next(iter(stocks.values())))
  27.  
  28. if day < length:
  29. for stock_name, predictions in stock_predictions.items():
  30. cost = transaction_cost if stock_name != node.stock else 0
  31. total = node.total_value + predictions[day] - cost
  32. child = Node(stock_name, day, predictions[day], total, node)
  33. node.children.append(child)
  34. add_nodes(node.children[-1], stocks, day + 1, transaction_cost)
  35.  
  36.  
  37. def print_nodes(parent):
  38. print(str(parent.value))
  39.  
  40. if len(parent.children) > 0:
  41. for child in parent.children:
  42. print_nodes(child)
  43.  
  44.  
  45. def get_greatest_node(root):
  46. max_node = root
  47. if len(max_node.children) > 1:
  48. for child in root.children:
  49. max_value = max_node.total_value
  50. greatest_child = get_greatest_node(child)
  51. greatest_child_value = greatest_child.total_value
  52. if greatest_child_value > max_value:
  53. max_node = greatest_child
  54.  
  55. return max_node
  56.  
  57.  
  58. def print_path(node):
  59. if node.stock == 'root':
  60. return
  61.  
  62. print(str(node))
  63. return print_path(node.parent)
  64.  
  65.  
  66. if __name__ == "__main__":
  67. transaction_cost = 5
  68. root = Node('root', 0, 0, transaction_cost, None)
  69. add_nodes(root, stock_predictions, 0, transaction_cost)
  70. greatest_node = get_greatest_node(root)
  71. print_path(greatest_node)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement