1

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)

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

that's wonderful, but how can I put the value into the loop for the ts.get_tick_data function?
@LuYu isn't it just ts.get_tick_data(ticker, value)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.