Running SAS from Python on WRDS

Suppose I have a SAS macro that I call using a parameter, is there a way to pass that parameter from a Python program?

Turns out the answer is “yes!” Suppose I want SAS to operate on every daily TAQ file for 2006. It is easy to get Python to pull together a list of files, turn those into dates (extracted from the file names), and then pass these to SAS via the command line.

Here is SAS code using the variable &sysparm.

%put &sysparm;
%get_spreads(taq_date=&sysparm);

Now here is some Python code that can be called as follows ./run_program.py 2006 to run the SAS code for each day in 2006.

#!/usr/bin/python

# import the relevant modules
import glob
import re
import subprocess
import sys

# Extract the year from the command line
year = sys.argv[1]
print year

# Get the list of TAQ files for the given year
path = '/wrds/taq/sasdata/ct_' + str(year) + '*.sas7bdat'
print path
file_list = glob.glob(path)

# Now work through each file in the chosen year
for daily_file in file_list:
  # Use regular expression to extract the date; it's in YYYYMMDD format.
  date = re.sub('/wrds/taq/sasdata/ct_(\d{8}).sas7bdat', '\\1', daily_file)
  
  # Construct and run the necessary SAS command
  command = "time sas ia_daily_idg.sas -log " + date + ".log "
  command += "-noterminal -sysparm \"" + date + "\""
  print command
  subprocess.call(command, shell=True)

print "All done!"
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s