Code for fetching and processing historical data