Skip to content

Instantly share code, notes, and snippets.

@nobodywasishere
Last active January 24, 2022 03:52
Show Gist options
  • Save nobodywasishere/ade63c4d5917951d2c2dbbf68d4375d4 to your computer and use it in GitHub Desktop.
Save nobodywasishere/ade63c4d5917951d2c2dbbf68d4375d4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# get Tufts COVID-19 dashboard data and plot it
# https://coronavirus.tufts.edu/testing-metrics
# Copyright © 2022 Michael Riegert
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the “Software”), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import requests
from prettytable import PrettyTable
from datetime import date, timedelta
from dateutil.rrule import rrule, DAILY
import matplotlib.pyplot as plt
import numpy as np
from rich import print as pprint
# assumes year 2022
base_url = 'https://coronavirus.tufts.edu/sites/default/files/2022-01/Testing%20Metrics%20{}-{}-22%20longdes.txt'
# gets all the covid data from start_date to end_date, which are datetime objects
def get_data(start_date, end_date):
data = {}
# https://stackoverflow.com/a/1061779/9047818
for date in rrule(DAILY, dtstart=start_date, until=end_date):
url = base_url.format(str(date.month).zfill(2), str(date.day).zfill(2))
resp = requests.get(url)
if resp.status_code == 404:
url = base_url.format(date.month, date.day)
resp = requests.get(url)
print(f'{date}: {resp.status_code}')
if resp.status_code != 404:
data[date] = resp.content.decode('utf-8')
return data
# decodes the response text to a dictionary
def decode_data(point):
point = point.split('\r\n\r\n')[1]
out = {}
for line in point.splitlines():
if ':' in line:
key = line.split(':')[0]
if key == 'Total Number of Tests with Results':
key = 'Total Results'
if '%' in line:
val = round(float(line.split(':')[1].replace('%', '')) / 100.0, 4)
elif '.' in line.split(':')[1]:
val = round(float(line.split(':')[1]), 2)
else:
val = int(line.split(':')[1].replace(',',''))
out[key] = val
return out
def print_data(data):
head = ['Date'] + list(data[list(data)[0]].keys())
x = PrettyTable()
x.field_names = head
for key, val in data.items():
x.add_row([key.strftime('%Y-%m-%d')] + [oth for _, oth in val.items()])
print(x)
# earlier dates used the database dashboard thing and doesn't work
start_date = date(2022, 1, 8)
end_date = date.today()
# get all the data
data = get_data(start_date, end_date)
# decode all the data
for key, val in data.items():
data[key] = decode_data(val)
# print_data(data)
print_data(data)
# used for plotting
plot_range = list(rrule(DAILY, dtstart=start_date, until=end_date))
# create the subplots
fig, axs = plt.subplots(2)
fig.suptitle('Tufts COVID Cases (7 Day Total/Avg)')
items = ['Total Results', 'Negative Tests', 'Positive Tests']
for item in items:
axs[0].plot(plot_range, [val[item] for key, val in data.items()], label=item)
axs[0].axis([None, None, 0, None])
axs[0].legend()
items = ['% Positive', '% Negative']
for item in items:
axs[1].plot(plot_range, [val[item] for key, val in data.items()], label=item)
axs[1].axis([None, None, 0, 1])
axs[1].legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment