Python, Getting stock data on particular days

1.3k views Asked by At

I'm looking into getting data from the American stock exchanges for some python code, Basically what I need to do is import a stock name and previous date in time and it will give me all the data for the next 10 days of the market being open, Is this possible?

market = input("Market:")
ticker = input("Ticker:")
ticker = ticker.upper()
ystartdate = (input("Start Date IN FORMAT yyyy-mm-dd:"))
day1=input("Day1 :")
day2=input("Day2 :")
day3=input("Day3 :")
day4=input("Day4 :")
day5=input("Day5 :")
day6=input("Day6 :")
day7=input("Day7 :")
day8=input("Day8 :")
day9=input("Day9 :")
day10=input("Day10:")

Currently i have to input all the data automatically but that is a pain to do, Basically i would put in a stock and date like 2012-10-15 and it would go look at the stock on that date and for the next 10 days. If its possible it would be a life saver! Thanks

2

There are 2 answers

1
Alexis Drakopoulos On

You should be working with a proper time format, not strings for this.

You can use pandas for example with datetime64.

import pandas as pd

input = ("Starting Date: ")
dates = pd.date_range(start=start_date, periods=10)

There is also the datetime package which has timedelta concepts which may help you if you don't want to use pandas.

0
Ingo On

I think what your need is included in pandas. In fact, you want to use either pandas.bdate_range or pandas.date_range with the freq argument set to B (I think both are more or less the same). These create business days, that is they would non include weekends. bdate_range also allows you to specify holidays, so I think that it might be a little more flexible.

>>> import pandas as pd
>>> dates = pd.bdate_range(start='2018-10-25', periods=10)  # Start date is a Thursday
>>> print(dates)
DatetimeIndex(['2018-10-25', '2018-10-26', '2018-10-29', '2018-10-30',
           '2018-10-31', '2018-11-01', '2018-11-02', '2018-11-05',
           '2018-11-06', '2018-11-07'],
          dtype='datetime64[ns]', freq='B')

Note how this excludes the 27th (a Saturday) and the 28th (a Sunday). If you want to specify holidays, you need to specify freq='C'.

Having these dates in separate variables is kind of ugly, but if you really want to, you can then go and unpack them like this:

>>> day1, day2, day3, day4, day5, day6, day7, day8, day9, day10 = dates