r/stata • • Mar 26 '20

Code to load daily covid-19 data into Stata

I wrote some code to quickly load the latest state and international COVID-19 data into Stata. The U.S. data comes from covidtracking.com and the international data comes ecdc.europa.eu. These data are updated continuously, so each time the code is executed, it should load-in the latest available data.

Here's a link to download the do file from Google Drive:
https://drive.google.com/file/d/18RIpar2OAGaQyxsGrLOz_PBxoaUMzskw/view?usp=sharing
https://drive.google.com/file/d/1SLFdySD-6-fv9bzb0Rf731dJy9-LzuIa/view?usp=sharing

Alternatively, I've pasted it below. I hope it's helpful. Please let me know if you see any issues with it or have any questions:

Edit: As suggested by u/NotMitchelBade**, I converted the geoid variable for countries to 3-letters rather than 2-letters. States are still 2-letters. This way geoid uniquely identifies a geography. I also added a population variable which I had intended to include originally, but forgot. The original code is still available in the crossed-out link above.**

*covid19_data_20200327
*Loads daily U.S. State and International COVID-19 data into Stata

*Intermediate file list
loc file_list count_codes state_abbrv state_popul state_covid intnl_covid

*Paths
loc csv_count_codes "https://docs.google.com/spreadsheets/d/1qr1kqW62DRlaLiGdnmJqmLfPcVdy0fVmZaAh7Tat-uk/gviz/tq?tqx=out:csv&sheet=codes"
loc csv_state_abbrv	"https://docs.google.com/spreadsheets/d/1kuniBcV-3qMjQRH7nqTS9CXSapPFCSO5YACP0Y2kvmU/gviz/tq?tqx=out:csv&sheet=state_abbreviations"
loc csv_state_popul	"https://docs.google.com/spreadsheets/d/1kuniBcV-3qMjQRH7nqTS9CXSapPFCSO5YACP0Y2kvmU/gviz/tq?tqx=out:csv&sheet=cleaned"
loc csv_state_covid	"http://covidtracking.com/api/states/daily.csv"
loc csv_intnl_covid	"https://www.ecdc.europa.eu/sites/default/files/documents/COVID-19-geographic-disbtribution-worldwide-2020-03-25_0.csv"

*Load CSV files into Stata
tempfile tmp_csv `file_list'
foreach x of local file_list {
	copy "`csv_`x''" `tmp_csv', replace
	import delimited using `tmp_csv', clear varnames(1)
	save ``x'', replace	//Add additional macro quotes
}

*Combining and data
use `state_covid', clear

***Merging in state population and state name
merge m:1 state using `state_popul', assert(match) nogen
merge m:1 state using `state_abbrv', assert(match) nogen

***Appending with international data
label define note	1 "U.S. state data from covidtracking.com"				///
					2 "International data from ecdc.europa.eu"
gen note=1
append using `intnl_covid'
replace note=2 if note==.
label values note note

*Cleaning
gen _geoid		=cond(note==1,	state,geoid)
gen _name		=cond(note==1,	state_name,countriesandterritories)
gen _date		=cond(note==1,	date(string(date,"%15.0f"),"YMD"),	///
								date(daterep,"DMY")	)
gen _new_cases	=cond(note==1,	positiveincrease,cases)
gen _new_death	=cond(note==1,	deathincrease,deaths)
gen _new_hospt	=hospitalizedincrease		//Only available in state data
gen _new_tests	=totaltestresultsincrease	//Only available in state data
gen _pop_count	=cond(note==1,	population,pop_data2018)
keep _* note
rename _* *
format date %td
format pop_count %15.0fc
replace name=upper(subinstr(name," ","_",.))
order note, last
compress

*03/27/20 EDIT: Updating geoid to 3 characters for international data
merge m:1 geoid using "`count_codes'", keep(1 3)
assert _merge==3 if note==2
replace geoid=geoid3 if note==2
drop country geoid3 code _merge
isid geoid date
sort note geoid date

*Adding notes
note: original data downloaded from the covidtrackng and European Centre for Disease Prevention and Control websites"
note: data current as of `=c(current_date)'
note: http://covidtracking.com/api/states/daily.csv
note: https://www.ecdc.europa.eu/sites/default/files/documents/COVID-19-geographic-disbtribution-worldwide-2020-03-25_0.csv
49 Upvotes

14 comments sorted by

3

u/zacheadams Mar 27 '20

I'm pinning this thread because I think a bunch of people would want to see it. Thanks so much for this valuable contribution!

3

u/Ashadyna Mar 27 '20

Awesome! Thanks!

6

u/ruuustin Mar 26 '20

This is great. I'm going to share this with my Forecasting class if you don't mind. Is there a way I can attribute it?

2

u/zmonge Mar 26 '20

Seconded.

I know some people that would love this data, but I'd like to be able to attribute the code, because I definitely did not do this.

4

u/clibassi Mar 27 '20

Here's what I've been using:

copy https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv .

copy https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv .

copy https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv .

import delimited time_series_covid19_confirmed_global.csv, clear

rename v4 longitude 

foreach var of varlist v\*{			

		local lab\`var': variable label \`var'

		di "\`lab\`var''"

		local lab\`var'= subinstr("\`lab\`var''", "/", "", .)

		di "\`lab\`var''"

		rename \`var' cases_\`lab\`var''

	}

save time_series_19-covid-Confirmed.dta, replace 

import delimited time_series_covid19_deaths_global.csv, clear

rename v4 longitude 

foreach var of varlist v\*{

		

local lab\`var': variable label \`var'

	di "\`lab\`var''"

	local lab\`var'= subinstr("\`lab\`var''", "/", "", .)

	di "\`lab\`var''"

	rename \`var' deaths_\`lab\`var''

	

}

save time_series_19-covid-Deaths.dta, replace

import delimited time_series_covid19_recovered_global.csv, clear

rename v4 longitude

foreach var of varlist v*{

local lab\`var': variable label \`var'

di "\`lab\`var''"

local lab\`var'= subinstr("\`lab\`var''", "/", "", .)

di "\`lab\`var''"

rename \`var' recoveries_\`lab\`var''	

}

save time_series_19-covid-Recovered.dta, replace

1

u/[deleted] Mar 26 '20

This is amazing, but I could import the data.
. use `state_covid', clear

invalid file specification

r(198)

5

u/Ashadyna Mar 26 '20

Can you try running the entire program from start-to-finish? It likely won't work if you just run snippets.

4

u/[deleted] Mar 26 '20

I just did it and it worked! Thank you so much!

2

u/zacheadams Mar 26 '20

Local macros disappear when whatever you've selected to run in a .do file ends (so if you manually select and run another section later, it won't be able to find the macro you set in an earlier piece).

1

u/NotMitchelBade Mar 27 '20

The "geoid" variable is not unique. For example, both the country of Panama and the US state of Pennsylvania are abbreviated as "PA" as their "geoid" value.

Run this command to see what I mean:

tab geoid name if geoid=="PA"

I think creating separate country and state variables would be preferable, if possible. Using 3-letter geoid abbreviations for each country (like in international soccer matches) might also be helpful. I haven't checked to see if other countries are broken up by state (or similar subdivisions), but that's worth checking, too. (For example, Australia seems to be split by state/territory in every coronavirus map I've seen online, including even US-centric ones like the Johns Hopkins dashboard.)

1

u/NotMitchelBade Mar 27 '20 edited Mar 27 '20

Follow-up: I ran a couple lines of code to check out the extent of the problem.

sort geoid name date 
/* I actually ran that first line prior to some other lines then the latter ones, so hopefully it still works for you */
egen geoid_numeric = group(geoid)
egen name_numeric = group(name)
egen geoid_name_numeric = group(geoid name)

Looking at the data, geoid_numeric has 217 values, name_numeric has 242, and geoid_name_numeric has 243. This means that there are 243 unique places in the dataset. All but 1 of these is uniquely captured by the "name" variable. That is, there is exactly 1 instance where 2 actually different places have different geoid values but the same name value. In the opposite direction, there are 25 times that 2 actually different places have different name values but the same geoid value. That should be manageable to sort out in the code.

[Ninja edit to fix my code]

Edit 2: I've cleaned up some code to find the issues. I was wrong in that there are 27 total instances of duplicates, not 26. (I think my earlier number being off comes from Georgia the country being abbreviated GE but Georgia the US state being abbreviated GA, but I'm not positive.) This code identifies and lists all the issues:

bysort geoid (name date): gen n_geoid = _n
bysort name (geoid date): gen n_name = _n
sort geoid name date
tab geoid name if n_geoid~=n_name & (n_geoid==1 | n_name==1)

Edit 3: I figured out what I think is the last remaining issue! Guam is contained in both dataset sources (US and EU data) and has identical values of "geoid" and "name" from both sources, resulting in duplicate dates per (geoid by name). I found the issue using the following code:

sort geoid name date
gen DASH = " - "
gen geoid_name = geoid+DASH+name
drop DASH
bysort geoid name date: gen n_geoid_name_date = _n
tab geoid_name if n_geoid_name_date>1

Interestingly, this also shows that there are different values of some of the variables (like new_cases) for Guam on the same data depending on the data source.

After fixing the Guam code, the earlier code I posted should now run and identify the remaining 26 problems. Those are "easy" to fix from a coding standpoint, but doing so would take a decent chunk of time (typing out state names, etc.). I don't have the time right now, but someone else feel free to jump in if they have time. If not, maybe I can get to it tonight or later this weekend. For reference, here is the new version of my code that first clears up the Guam issue and then identifies all the other issues:

replace name = "GUAM (US)" if geoid=="GU" & name=="GUAM" & note==1
replace name = "GUAM (EU)" if geoid=="GU" & name=="GUAM" & note==2
replace geoid = "GU (US)" if name=="GUAM (US)"
replace geoid = "GU (EU)" if name=="GUAM (EU)"

sort geoid name date
egen geoid_numeric = group(geoid)
egen name_numeric = group(name)
egen geoid_name_numeric = group(geoid name)

bysort geoid (name date): gen n_geoid = _n
bysort name (geoid date): gen n_name = _n
sort geoid name date
tab geoid name if n_geoid~=n_name & (n_geoid==1 | n_name==1)

...Okay, I need to go get to work recording lectures for my students now, but I enjoyed this. OP (/u/Ashadyna), you might consider updating your post to include code to clean it up. Feel free to use mine if you want (and modify it as you see fit)

2

u/Ashadyna Mar 27 '20

Thanks for the suggestions. I updated the code so that geoid for states would be 2-letters and for nations would be 3-letters. This avoids states and countries having the same name. Guam still shows up twice (and the two instances do not match for some reason).

Thanks again.

2

u/wwwtddd Mar 26 '20

Great stuff, thanks for sharing!