Elif Y
Elif Y

Reputation: 251

Writing loop to get the data during some specific periods in Python

I want to write a loop for multiple stocks for specific date time periods.

The following code can only get the data for one day each time. So I want to write a loop outside the function. After that, I want to contact all these stock data into DataFrame.

Like I want the data from 2015-01-01 to today.

import tushare as ts

ticker = ['002428', '600030', '600031', '002437', '300399']
df = ts.get_tick_data(ticker,'2014-01-09')
df.head(10)

Upvotes: 1

Views: 862

Answers (1)

alecxe
alecxe

Reputation: 473863

Loop over a date range day-by-day and use strftime() to convert a date into a string:

from datetime import timedelta, datetime

def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)


start_date = datetime(year=2015, month=1, day=1)
end_date = datetime.today()

for single_date in daterange(start_date, end_date):
    value = single_date.strftime("%Y-%m-%d")

    print value

Demo:

>>> start_date = datetime(year=2015, month=1, day=1)
>>> end_date = datetime.today()
>>> for single_date in daterange(start_date, end_date):
...     value = single_date.strftime("%Y-%m-%d")
...     print value
... 
2015-01-01
2015-01-02
...
2015-03-03
2015-03-04
2015-03-05

There is also an awesome library for working with dates and times called delorean. Aside from other features, it has a built-in support for date range iterations:

>>> import delorean
>>> from delorean import stops
>>> for stop in stops(freq=delorean.DAILY, timezone="US/Eastern", start=start_date, stop=end_date):
...     value = stop.date.strftime("%Y-%m-%d")
...     print value
... 
2015-01-01
2015-01-02
2015-01-03
...
2015-03-04
2015-03-05
2015-03-06

Upvotes: 1

Related Questions