model.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import psycopg2.extras
  2. def get_timestamp_previous():
  3. """
  4. Retrieve second to last timestamp from the stocks database
  5. :return timestamp:
  6. """
  7. cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  8. query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1 OFFSET 1;"""
  9. cursor.execute(query)
  10. res = cursor.fetchone()
  11. this_timestamp_previous = res.timestamp
  12. cursor.close()
  13. return this_timestamp_previous
  14. def get_timestamp_latest():
  15. """
  16. Retrieve latest timestamp from the stocks database
  17. :return timestamp:
  18. """
  19. cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  20. query = """SELECT DISTINCT timestamp FROM stocks ORDER BY stocks.timestamp DESC LIMIT 1;"""
  21. cursor.execute(query)
  22. res = cursor.fetchone()
  23. this_timestamp_latest = res.timestamp
  24. cursor.close()
  25. return this_timestamp_latest
  26. def get_timestamp_stored():
  27. """
  28. Retrieve the timestamp when the program checked the database
  29. :return timestamp:
  30. """
  31. with open('timestamp.txt', 'r') as f:
  32. this_timestamp_stored_string = f.read()
  33. if this_timestamp_stored_string.replace('.', '', 1).isdigit():
  34. this_timestamp_stored = int(this_timestamp_stored_string)
  35. else:
  36. this_timestamp_stored = 0
  37. return this_timestamp_stored
  38. def put_timestamp_stored(this_timestamp):
  39. """
  40. Update timestamp when the program checked the database
  41. :param this_timestamp:
  42. :return:
  43. """
  44. with open('timestamp.txt', 'w') as f:
  45. f.write("{}".format(this_timestamp))
  46. def get_data(stock_id, this_timestamp):
  47. cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  48. query = """SELECT current_price, available_shares FROM stocks WHERE stock_id = %s AND timestamp = %s"""
  49. cursor.execute(query, (stock_id, this_timestamp))
  50. this_data = cursor.fetchone()
  51. cursor.close()
  52. return this_data
  53. def process_data(this_data_previous, this_data_latest, this_threshold):
  54. """
  55. Calculate if there is enough change to call it a drop
  56. :param this_data_previous:
  57. :param this_data_latest:
  58. :param this_threshold
  59. :return boolean:
  60. """
  61. this_drop = False
  62. quantity_previous = this_data_previous.available_shares * this_data_latest.current_price
  63. quantity_latest = this_data_latest.available_shares * this_data_latest.current_price
  64. if quantity_latest - quantity_previous > this_threshold * 1e9:
  65. this_drop = True
  66. return this_drop