Python Forum

Full Version: How to pick random entries of stock prices?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear Python Users,

Please, can you help me with the following issue. I downloaded a stock price from google. Sorted the prices. What I need to do now is to pick 8 prices starting at the beginning of the consecutive months (the closest date, since not all times stocks trade on the 1st of the month). Say, if the randomly assigned starting month is January then the 2nd price is picked from February, 3rd from March, etc. This should be random. Once, the prices are picked they should be allocated to excel file. I attach the code I have below. Please, advise me this issue

import pandas as pd
import datetime
#import pandas.io.data as web 
import pandas_datareader.data as web
from matplotlib import style
style.use('ggplot')

start = datetime.datetime(2010, 1, 1)
end = datetime.datetime.today().strftime("%m/%d/%Y")

stock = web.DataReader("AMZN", "google", start, end)
stock1 = stock['Close']#pick the column - close price
          
stock1 = stock1.resample('BMS', how='first') #sort the data following the calendar dates
Something like that?
victor ~ $ ptpython
>>> import random, datetime

>>> months = {datetime.date(2017, month, 1).strftime('%B'): month for month in range(1, 13)}

>>> carousel = iter(months)

>>> num = months[random.choice(list(months.keys()))]

>>> for i in range(num - 1):
...     next(carousel)

>>> while True:
...     try:
...         print(months[next(carousel)])
...     except StopIteration:
...         break
10
11
12