示例#1
0
def _get_factor_data(report_id: str, factor_name: str,
                     query_type: QueryType) -> pd.Series:
    # Check params
    report = FactorRiskReport.get(report_id)
    if factor_name not in ['Factor', 'Specific', 'Total']:
        if query_type in [QueryType.DAILY_RISK, QueryType.ANNUAL_RISK]:
            raise MqValueError(
                'Please pick a factor name from the following: ["Total", "Factor", "Specific"]'
            )
        model = FactorRiskModel.get(report.get_risk_model_id())
        factor = model.get_factor(factor_name)
        factor_name = factor.name

    # Extract relevant data for each date
    col_name = query_type.value.replace(' ', '')
    col_name = decapitalize(col_name)
    data_type = decapitalize(
        col_name[6:]) if col_name.startswith('factor') else col_name

    factor_data = report.get_results(factors=[factor_name],
                                     start_date=DataContext.current.start_date,
                                     end_date=DataContext.current.end_date,
                                     return_format=ReturnFormat.JSON)
    factor_exposures = [{
        'date': d['date'],
        col_name: d[data_type]
    } for d in factor_data if d.get(data_type)]

    # Create and return timeseries
    df = pd.DataFrame(factor_exposures)
    if not df.empty:
        df.set_index('date', inplace=True)
        df.index = pd.to_datetime(df.index)
    return _extract_series_from_df(df, query_type)
示例#2
0
def __format_plot_measure_results(time_series: Dict, query_type: QueryType, multiplier=1, handle_missing_column=False):
    """ Create and return panda series expected for a plot measure """
    col_name = query_type.value.replace(' ', '')
    col_name = decapitalize(col_name)
    time_series_list = [{'date': k, col_name: v * multiplier} for k, v in time_series.items()]
    df = pd.DataFrame(time_series_list)
    if not df.empty:
        df.set_index('date', inplace=True)
        df.index = pd.to_datetime(df.index)
    return _extract_series_from_df(df, query_type, handle_missing_column)
示例#3
0
def _get_factor_data(report_id: str, factor_name: str,
                     query_type: QueryType) -> pd.Series:
    # Check params
    report = RiskReport(report_id)
    if report.get_type() not in [
            ReportType.Portfolio_Factor_Risk, ReportType.Asset_Factor_Risk
    ]:
        raise MqValueError('This report is not a factor risk report')
    risk_model_id = report.get_risk_model_id()
    if factor_name not in ['Factor', 'Specific', 'Total']:
        if query_type in [QueryType.DAILY_RISK, QueryType.ANNUAL_RISK]:
            raise MqValueError(
                'Please pick a factor name from the following: ["Total", "Factor", "Specific"]'
            )
        factor = Factor(risk_model_id, factor_name)
        factor_name = factor.name

    # Extract relevant data for each date
    col_name = query_type.value.replace(' ', '')
    col_name = decapitalize(col_name)
    data_type = decapitalize(
        col_name[6:]) if col_name.startswith('factor') else col_name

    factor_data = report.get_factor_data(
        factor=factor_name,
        start_date=DataContext.current.start_time,
        end_date=DataContext.current.end_time)
    factor_exposures = [{
        'date': data['date'],
        col_name: data[data_type]
    } for data in factor_data if data.get(data_type)]

    # Create and return timeseries
    df = pd.DataFrame(factor_exposures)
    if not df.empty:
        df.set_index('date', inplace=True)
        df.index = pd.to_datetime(df.index)
    return _extract_series_from_df(df, query_type)
示例#4
0
    def as_dict(self) -> Dict:
        """
        Create a dictionary representation of the processor. Used for eventually turning the processor into json for
        API usage. Allows for nested processors.
        :return: Dictionary representation of the processor
        """
        processor = {TYPE: PROCESSOR, PARAMETERS: {}}

        parameters = processor[PARAMETERS]

        for parameter, alias in get_type_hints(self.__init__).items():
            if alias in (DataCoordinateOrProcessor, DataCoordinate,
                         Union[DataCoordinateOrProcessor, None]):
                # If the parameter is a DataCoordinate or processor, recursively call as_dict()
                attribute = self.children[parameter]
                if attribute is None:
                    continue
                parameters[parameter] = {}
                this_parameter = parameters[parameter]

                if isinstance(attribute, BaseProcessor):
                    this_parameter[TYPE] = PROCESSOR
                    this_parameter[
                        PROCESSOR_NAME] = attribute.__class__.__name__
                elif isinstance(attribute, DataCoordinate):
                    this_parameter[TYPE] = DATA_COORDINATE
                else:
                    # Continue if not an expected type or None
                    continue

                this_parameter.update(**attribute.as_dict())
            else:
                # Handle the less complex types such as python built in types, enums, entities, datetimes
                attribute = getattr(self, parameter)
                if attribute is not None:
                    parameters[parameter] = {}
                    if is_of_builtin_type(attribute):
                        value = attribute
                    elif isinstance(attribute, Enum):
                        value = attribute.value
                    elif isinstance(attribute, Entity):
                        parameters[parameter].update({
                            TYPE:
                            ENTITY,
                            ENTITY_ID:
                            attribute.get_marquee_id(),
                            ENTITY_TYPE:
                            attribute.entity_type().value
                        })
                        continue
                    elif isinstance(attribute, (date, datetime)):
                        if isinstance(attribute, date):
                            value = str(attribute)
                        else:
                            value = f"{attribute.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3]}Z"
                    else:
                        value = attribute.as_dict()
                    parameters[parameter].update({
                        TYPE:
                        decapitalize(type(attribute).__name__),
                        VALUE:
                        value
                    })

        return processor
示例#5
0
def test_decapitalize(case, expected):
    assert _.decapitalize(case) == expected