skip to Main Content

I have a list of stock ticker symbols as values and their sectors as keys in a python defauldict. I would like to randomly sample one or two from each value and place them in their own list, then do some stuff, then randomly sample again and do this for 50 or 100 times.

Is this possible?

Here is the sample of the dictionary.

sector_dict = defaultdict(list,
                          {'Technology': ['AAPL', 'ADBE', 'AMD', 'AMAT', 'FSLR', 'GPRO', 'IBM', 'MSFT', 'MU',
                                          'QCOM', 'TXN', 'XLNX', 'CRM'],
                           'Healthcare': ['ABT', 'GILD', 'MDT', 'BMY'],
                           'Consumer Cyclical': ['AMZN', 'ANF', 'BABA', 'BBY', 'BZUN', 'CMG', 'EBAY', 'GM', 'HD',
                                                 'JD', 'LULU', 'MCD', 'NKE', 'TSLA', 'UA', 'GME'],
                           'Energy': ['APA', 'HAL', 'PBR', 'SLB', 'CVX'],
                           'Industrials': ['BA', 'CAT', 'DE', 'FDX', 'HON', 'UAL'],
                           'Communication Services': ['BIDU', 'FB', 'GOOG', 'NFLX', 'SNAP', 'TWTR', 'ZM', 'CMCSA'],
                           'Real Estate': ['BRX', 'SPG'],
                           'Consumer Defensive': ['COST'],
                           'Basic Materials': ['FCX', 'NEM', 'CLF'],
                           'Financial Services': ['GS', 'HIG', 'LYG', 'MA', 'V', 'C', 'JPM', 'MS']})

Replacement can be True. The only constraint is at least one ticker from each key should be chosen. How do I do this?

When I try, I get a list of lists when all I’m trying to get is a list of values (tickers).

Here was my attempt:

import random
random_port = []
for key, val in sector_dict.items():
    random_port.append(random.sample(val, 1))
random_port

2

Answers


  1. Try:

    random_port = []
    for value in sector_dict.values():
        random_port += random.sample(value, min(len(value), 2))
    
    Login or Signup to reply.
  2. Here below I slightly modified your code to select one or two stocks from each category:

    import random
    
    random_list = []
    
    for key, val in sector_dict.items():
        random_list.extend(random.sample(val, min(len(val), random.randint(1,2))))
    
    print(random_list)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search