#!/usr/bin/env python # ------------------------------------------------------------------------------ # # Disclaimer: # # DTN grants you an nonexclusive copyright license to use this code and you can # use it to prepare similar functions tailored to your own needs. # # The code is provided for illustrative purposes only and has not been tested under # all conditions. For that reason, DTN provides this code to you "AS IS" without # any warranties of any kind. # # ------------------------------------------------------------------------------ # # Retrieve a daily history report and present result in CSV format. # # Imports import PXWeb # ------------------------------------------------------------------------------ # PXWeb access credentials USER = 'YOUR_USER' PSWD = 'YOUR_PASSWORD' # List of search patterns to send to PXWeb PATTERNS = ( '@C`##', '@W`##', 'QCL`##', 'QNG`##' ) # Max number of history entries to return for each symbol LIMIT = 10 # GetDailyHistory request string and CSV fields for response FIELDS = ( 'Date', 'Open', 'Close', 'High', 'Low', 'OI', 'Volume' ) # Name of output file OUT_FILE = 'result.csv' # ------------------------------------------------------------------------------ # Open output file and write header ofile = open( OUT_FILE, 'w' ) ofile.write( 'Symbol,{}\n'.format(','.join( FIELDS ) ) # Get PXWeb client object pxWeb = PXWeb.PXServiceWebClient( USER, PSWD ) # Send each search pattern in an independent request for pattern in PATTERNS: # Send GetDailyHistory request for current search pattern and get an XML tree xml = pxWeb.getDailyHistory( symbol=pattern, limit=LIMIT ) # For each node returned for hNode in xml: # Get actual symbol symbol = hNode.attrib[ 'TickerSymbol' ] # For each in the node write a CSV line for dNode in hNode: csv = f'{symbol},' for field in FIELDS: csv += dNode.attrib[ field ] + ',' ofile.write( csv[ :-1 ] + '\n' ) # Close file ofile.close() # Notify print(f'Result ready in file "{OUT_FILE}".')