Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generating 100 Random Share Prices

I want to construct a list of 100 randomly generated share prices by generate 100 random 4-letter-names for the companies and a corresponding random share price.

So far, I have written the following code which provides a random 4-letter company name:

import string
import random

def stock_generator():
    return ''.join(random.choices(string.ascii_uppercase, k=4))

stock_name_generator()

# OUTPUT
'FIQG'

But, I want to generate 100 of these with accompanying random share prices. It is possible to do this while keeping the list the same once it’s created (i.e. using a seed of some sort)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

import string
import random


random.seed(0)


def stock_generator(n=100):
    return [(''.join(random.choices(string.ascii_uppercase, k=4)), random.random()) for _ in range(n)]


stocks = stock_generator()

print(stocks)

You can generate as many random stocks as you want with this generator expression. stock_generator() returns a list of tuples of random 4-letter names and a random number between 0 and 1. I image a real price would look different, but this is how you’d start.

random.seed() lets you replicate the random generation.

Edit: average stock price as additionally requested

average_price = sum(stock[1] for stock in stocks) / len(stocks)

stocks[i][1] can be used to access the price in the name/price tuple.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading