Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Getting list of symbols of current portfolio holdings

As per the title, I would like to be able to retrieve a list of symbols of my current portfolio holdings.

For example, if I have 25 shares of AAPL and 30 shares of GOOG, I would like to retrieve a list similar to: ['AAPL','GOOG']

I'd appreciate any input!

1 response

By 'retrieve' I'm assuming the goal is to view them.

log.info( [ str(s.symbol) for s in sorted(context.portfolio.positions) ] )

s stands for stock and can be anything.
str() is to remove the (u) unicode indicator like u'TSLA'.

2018-04-06 06:31 trade:39 INFO ['ARNC', 'AAPL', 'ABAX', 'ARCB', 'ABM', 'ABMD', 'ABT', 'ABX', 'ADSK', 'TAP', 'ACXM', 'ADBE', 'ADI', 'ADM', 'AEM', 'AEP', 'AES', 'AFL', 'AGCO', 'HES', 'AIG', 'AIN', 'AIR', 'AJG', 'MATX', 'ALK', 'ALKS', 'ALOG', 'AMAT', 'AMD', 'AME', 'AMGN', 'TVTY', 'AMWD', 'AN', 'AON', 'APA', 'APC', 'APD', 'APH', 'APOG', 'ATU', 'AAN', 'ARW', 'ASB', 'ASGN', 'ASH', 'ASTE', 'ATNI', 'ATO', 'ATRO', 'ADP', 'AMAG', 'AVP', 'AVT', 'AVY', 'AXP', 'AZO', 'AZZ', 'B', 'BA', 'BAC', 'BAX', 'BBBY', 'BBY', 'BC', 'BCE', 'BDX', 'BEN', 'BF_B', 'BGG', 'BHE', 'BID', 'BIO', 'BK', 'BKH', 'BKE', 'WRB', 'BCPC', 'NCS', 'BLL', 'BMI', 'BMS', 'BMY', 'BNS', 'BOH', 'BOKF', 'BXS', 'BPOP', 'BPT', 'BRC', 'BRO', 'BSX', 'MTRN', 'CAL', 'CA', 'CACC', 'CACI', 'CAG', 'CAKE', 'CAMP', 'CASY', 'CAT', 'CATY', 'CBI', 'CBM', 'CBRL', 'CBSH', 'CBU', 'CBT', 'CCE', 'C', 'CCK', 'CDE', 'CAH', 'CDNS', 'CEF', 'CELG', 'CERN', 'CFR', 'CGNX', 'CHD', 'CHFC', 'CI', 'CINF', 'CKH', 'CL', 'CLF', 'CLH', 'CLX', 'CMA', 'CMC', 'CMCS_A', 'CMO', 'CMS', 'CNA', 'CNMD', 'CMD', 'COG', 'COHU', 'COHR',...  

That hit the logging limit around 1024 bytes.

To log more content, this uses a string instead of a list and checks its length (number of characters), logging in batches:

    out = ''  
    for s in sorted(context.portfolio.positions):  
        out += "'{}', ".format( str(s.symbol) )  
        if len(out) > 1011:  
            log.info(out)  # this batch  
            out = ''       # start over  
    log.info(out)  # anything remaining  

The single quotes and commas are not necessary, can do this instead:

        out += "{} ".format( str(s.symbol) )  

Or

        out += ( str(s.symbol) + ' ' )