model.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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_string = f.read()
  38. if this_timestamp_stored_string.replace('.','',1).isdigit():
  39. this_timestamp_stored = int(this_timestamp_stored_string)
  40. else:
  41. this_timestamp_stored = 0
  42. return this_timestamp_stored
  43. def put_timestamp_stored(this_timestamp):
  44. """
  45. Update timestamp when the program checked the database
  46. :param this_timestamp:
  47. :return:
  48. """
  49. with open('timestamp.txt', 'w') as f:
  50. f.write("{}".format(this_timestamp))
  51. def get_data(stock_id, this_timestamp):
  52. db = database.db
  53. cursor = db.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
  54. query = """SELECT current_price, available_shares FROM stocks WHERE stock_id = %s AND timestamp = %s"""
  55. cursor.execute(query, (stock_id, this_timestamp))
  56. this_data = cursor.fetchone()
  57. cursor.close()
  58. db.close()
  59. return this_data
  60. def process_data(this_data_previous, this_data_latest, this_threshold):
  61. """
  62. Calculate if there is enough change to call it a drop
  63. :param this_data_previous:
  64. :param this_data_latest:
  65. :param this_threshold
  66. :return boolean:
  67. """
  68. this_drop = False
  69. quantity_previous = this_data_previous.available_shares * this_data_latest.current_price
  70. quantity_latest = this_data_latest.available_shares * this_data_latest.current_price
  71. if quantity_latest - quantity_previous > this_threshold * 1e9:
  72. this_drop = True
  73. return this_drop