model.py 2.4 KB

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