MCPcopy Create free account
hub / github.com/gto76/python-cheatsheet / update_confirmed_cases

Function update_confirmed_cases

web/update_plots.py:43–92  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

41
42
43def update_confirmed_cases():
44 def main():
45 df = wrangle_data(*scrape_data())
46 f = get_figure(df)
47 update_file('covid_cases.js', f)
48 f.layout.paper_bgcolor = 'rgb(255, 255, 255)'
49 write_to_png_file('covid_cases.png', f, width=960, height=315)
50
51 def scrape_data():
52 def scrape_covid():
53 url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv'
54 df = pd.read_csv(url, usecols=['location', 'date', 'total_cases'])
55 return df[df.location == 'World'].set_index('date').total_cases
56 def scrape_yahoo(slug):
57 url = f'https://query1.finance.yahoo.com/v7/finance/download/{slug}' + \
58 '?period1=1579651200&period2=9999999999&interval=1d&events=history'
59 df = pd.read_csv(url, usecols=['Date', 'Close'])
60 return df.set_index('Date').Close
61 out = [scrape_covid(), scrape_yahoo('BTC-USD'), scrape_yahoo('GC=F'),
62 scrape_yahoo('^DJI')]
63 return map(pd.Series.rename, out, ['Total Cases', 'Bitcoin', 'Gold', 'Dow Jones'])
64
65 def wrangle_data(covid, bitcoin, gold, dow):
66 df = pd.concat([dow, gold, bitcoin], axis=1) # Joins columns on dates.
67 df = df.sort_index().interpolate() # Sorts by date and interpolates NaN-s.
68 yesterday = str(datetime.date.today() - datetime.timedelta(1))
69 df = df.loc['2020-02-23':yesterday] # Discards rows before '2020-02-23'.
70 df = round((df / df.iloc[0]) * 100, 2) # Calculates percentages relative to day 1
71 df = df.join(covid) # Adds column with covid cases.
72 return df.sort_values(df.index[-1], axis=1) # Sorts columns by last day's value.
73
74 def get_figure(df):
75 figure = go.Figure()
76 for col_name in reversed(df.columns):
77 yaxis = 'y1' if col_name == 'Total Cases' else 'y2'
78 colors = {'Total Cases': '#EF553B', 'Bitcoin': '#636efa', 'Gold': '#FFA15A',
79 'Dow Jones': '#00cc96'}
80 trace = go.Scatter(x=df.index, y=df[col_name], name=col_name, yaxis=yaxis,
81 line=dict(color=colors[col_name]))
82 figure.add_trace(trace)
83 figure.update_layout(
84 yaxis1=dict(title='Total Cases', rangemode='tozero'),
85 yaxis2=dict(title='%', rangemode='tozero', overlaying='y', side='right'),
86 legend=dict(x=1.1),
87 margin=dict(t=24, b=0),
88 paper_bgcolor='rgba(0, 0, 0, 0)'
89 )
90 return figure
91
92 main()
93
94
95###

Callers 1

mainFunction · 0.85

Calls 1

mainFunction · 0.70

Tested by

no test coverage detected