<commit_before><commit_msg>Create bbgdailyhistory.py<commit_after># *- bbgdailyhistory.py -*

import os
import numpy as np
import pandas as pd
import blpapi


class BBGDailyHistory:
    '''
    Parameters
    ----------
    sec : str
        Ticker
    fields : str or list
        Field of list of fields ('PX_HIGH', 'PX_LOW', etc...)
    start : str
        Start date
    end : stf
        End date
    '''
    
    def __init__(self, sec, fields, start=None, end=None):
        #self.rqst = rqst
        self.sec = sec
        self.fields = fields
        self.start = start
        self.end = end

    
    def get_data(self) -> pd.DataFrame:
        '''
        Returns
        -------
        data : pd.DataFrame()
            The historical data queried returned in a dataFrame presented as
            long format
        '''
        # Session management
        sess = blpapi.Session()
        sess.start()

        # Define data type
        sess.openService('//blp/refdata')
        service = sess.getService('//blp/refdata')

        # Create request
        request = service.createRequest('HistoricalDataRequest')

        # Optional request setters
        request.set('startDate', self.start)
        request.set('endDate', self.end)
        request.getElement('securities').appendValue(self.sec)

        # Data holders 
        date_acc =[]
        ticker_acc = []
        field_acc = []
        value_acc = []

        # Loop over fields
        for fie in self.fields:
            request.getElement('fields').appendValue(fie)
        sess.sendRequest(request)
        endReached = False
        while endReached == False:
            event = sess.nextEvent(500)
            if event.eventType() == blpapi.Event.RESPONSE or event.eventType() == blpapi.Event.PARTIAL_RESPONSE:
                for msg in event:
                    fieldData = msg.getElement('securityData').getElement('fieldData')
                for data in fieldData.values():
                    for fld in self.fields:
                        date_acc.append(data.getElement('date').getValue())
                        field_acc.append(fld)
                        value_acc.append(data.getElement(fld).getValue())
                        ticker_acc.append(self.sec)
                
            if event.eventType() == blpapi.Event.RESPONSE:
                endReached = True
        
        sess.stop()

        data = pd.DataFrame({'timestamp' : date_acc,
                            'ticker' : ticker_acc,
                            'field' : fie,
                            'value' : value_acc})

        return data



if __name__ == "__main__":
    # Use example of BBGHistory
    #from bbgdatapuller import BBGHistory # Expect folder issue
    security = 'SIMA SW Equity' #'SIMA SW Equity'
    fields = ['PX_OPEN', 'PX_HIGH', 'PX_LOW', 'PX_LAST']
    start = '20200105'
    end = '20200109'
    d = BBGDailyHistory(sec=security, fields=fields, start=start, end=end).get_data()
    print(d.head())
{'fraction_non_alphanumeric': 0.10840560373582388, 'fraction_numerical': 0.0063375583722481655, 'mean_word_length': 1.7042380522993688, 'pattern_counts': {'":': 1, '<': 3, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '316472', 'n_tokens_mistral': 891, 'n_tokens_neox': 849, 'n_words': 197}