run_weighter.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # pandas and numpy for data manipulation
  2. import pandas as pd
  3. import numpy as np
  4. # fbprophet for additive models
  5. import fbprophet
  6. # gspread for Google Sheets access
  7. import gspread
  8. # slacker for interacting with Slack
  9. from slacker import Slacker
  10. # oauth2client for authorizing access to Google Sheets
  11. from oauth2client.service_account import ServiceAccountCredentials
  12. # os for deleting images
  13. import os
  14. # matplotlib for plotting
  15. import matplotlib.pyplot as plt
  16. import matplotlib.patches as mpatches
  17. import matplotlib
  18. # import weighter
  19. from weighter import Weighter
  20. if __name__ == "__main__":
  21. # google sheets access
  22. scope = ["https://spreadsheets.google.com/feeds"]
  23. # Use local stored credentials in json file
  24. # make sure to first share the sheet with the email in the json file
  25. credentials = ServiceAccountCredentials.from_json_keyfile_name(
  26. "C:/Users/Will Koehrsen/Desktop/weighter-2038ffb4e5a6.json", scope
  27. )
  28. # Authorize access
  29. gc = gspread.authorize(credentials)
  30. # Slack api key is stored as text file
  31. with open("C:/Users/Will Koehrsen/Desktop/slack_api.txt", "r") as f:
  32. slack_api_key = f.read()
  33. slack = Slacker(slack_api_key)
  34. # Open the sheet, need to share the sheet with email specified in json file
  35. gsheet = gc.open("Auto Weight Challenge").sheet1
  36. # List of lists with each row in the sheet as a list
  37. weight_lists = gsheet.get_all_values()
  38. # Headers are the first list
  39. # Pop returns the element (list in this case) and removes it from the list
  40. headers = weight_lists.pop(0)
  41. # Convert list of lists to a dataframe with specified column header
  42. weights = pd.DataFrame(weight_lists, columns=headers)
  43. # Record column should be a boolean
  44. weights["Record"] = weights["Record"].astype(bool)
  45. # Name column is a string
  46. weights["Name"] = weights["Name"].astype(str)
  47. # Convert dates to datetime, then set as index, then set the time zone
  48. weights["Date"] = pd.to_datetime(weights["Date"], unit="s")
  49. weights = weights.set_index("Date", drop=True).tz_localize(tz="US/Eastern")
  50. # Drop any extra entries
  51. weights = weights.drop("NaT")
  52. # If there are new entries create the weighter object
  53. if len(weights) > np.count_nonzero(weights["Record"]):
  54. # Initialize with dataframe of weights, google sheet, and slack object
  55. weighter = Weighter(weights, gsheet, slack)
  56. weighter.process_entries()
  57. print("Success")