def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    config.discard_unknown_keys = True
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3, status=3, status_forcelist=frozenset([429, 503]), backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    try:
        # {
        #     "strategy": {
        #         "id": "Client:/analytics_api/dbui_simple_strategy"
        #     },
        #     "account": {
        #         "id": "CLIENT:/FPO/1K_MAC_AMZN_AAPL.ACCT",
        #         "padocument": {
        #             "id": "CLIENT:/FPO/FPO_MASTER"
        #         }
        #     },
        #     "optimization": {
        #         "riskmodeldate": "0M",
        #         "backtestdate": "0M"
        #     },
        #     "outputtypes": {
        #         "trades": {
        #             "identifiertype": "Asset",
        #             "includecash": false
        #         }
        #     }
        # }
        # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
        # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older. 
        # cache_control = "max-stale=0"
        fpo_optimizer_strategy = FPOOptimizerStrategy(
            id="Client:/analytics_api/dbui_simple_strategy")
        fpo_pa_doc = PaDoc("CLIENT:/FPO/FPO_MASTER")
        fpo_optimizer_account = FPOAccount(
            fpo_pa_doc, id="CLIENT:/FPO/1K_MAC_AMZN_AAPL.ACCT")
        fpo_optimizer_optimization = Optimization(
            risk_model_date="0M",
            backtest_date="0M",
        )
        fpo_optimizer_trades_list = OptimizerTradesList(
            identifier_type="Asset", include_cash=False)
        fpo_optimizer_output_types = OptimizerOutputTypes(
            trades=fpo_optimizer_trades_list)
        fpo_optimizer_parameters = FPOOptimizationParameters(
            fpo_optimizer_strategy,
            fpo_optimizer_output_types,
            account=fpo_optimizer_account,
            optimization=fpo_optimizer_optimization
        )
        fpo_optimization_parameters_root = FPOOptimizationParametersRoot(
            data=fpo_optimizer_parameters)

        fpo_optimizations_api = FPOOptimizerApi(api_client)

        post_and_optimize_response = fpo_optimizations_api.post_and_optimize(
            fpo_optimization_parameters_root=fpo_optimization_parameters_root
        )
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_optimize_response = fpo_optimizations_api.post_and_optimize(
            # fpo_optimization_parameters_root=fpo_optimization_parameters_root, cache_control=cache_control
        # )
        if post_and_optimize_response[1] == 201:
            output_optimization_result(post_and_optimize_response[0]['data'])
        else:
            optimization_id = post_and_optimize_response[2]["X-Factset-Api-Calculation-Id"]
            print("Calculation Id: " + optimization_id)

            status_response = fpo_optimizations_api.get_optimization_status_by_id(id=optimization_id)

            while status_response[1] == 202:
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = fpo_optimizations_api.get_optimization_status_by_id(optimization_id)

            if status_response[1] == 201:
                print("Optimization Id: " + optimization_id + " Succeeded!!!")
                result_response = fpo_optimizations_api.get_optimization_result(id=optimization_id)
                output_optimization_result(result_response[0]['data'])
            else:
                print("Optimization Id:" + optimization_id + " Failed!!!")
                print("Error message : " + status_response[0].errors)

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3,
                           status=3,
                           status_forcelist=frozenset([429, 503]),
                           backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    try:
        screeningExpressionUniverse = QuantScreeningExpressionUniverse(
            source="ScreeningExpressionUniverse",
            universe_expr=
            "(TICKER=\"IBM\" OR TICKER=\"MS\" OR TICKER=\"GE\")=1",
            universe_type="Equity",
            security_expr="TICKER")

        fdsDate = QuantFdsDate(source="FdsDate",
                               start_date="20050701",
                               end_date="20051001",
                               frequency="M",
                               calendar="FIVEDAY")

        fqlExpression = QuantFqlExpression(source="FqlExpression",
                                           expr="P_PRICE(#DATE,#DATE,#FREQ)",
                                           name="Price")
        fqlExpression1 = QuantFqlExpression(source="FqlExpression",
                                            expr="FF_EPS(,#DATE,#DATE,#FREQ)",
                                            name="Eps")
        fqlExpression2 = QuantFqlExpression(source="FqlExpression",
                                            expr="FG_GICS_SECTOR",
                                            name="Sector")

        quant_calculation_parameters = {
            "1":
            QuantCalculationParameters(
                universe=screeningExpressionUniverse,
                dates=fdsDate,
                formulas=[fqlExpression, fqlExpression1, fqlExpression2])
        }
        # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
        # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older.
        # cache_control = "max-stale=0"
        quant_calculations_meta = QuantCalculationMeta(format='Feather')

        quant_calculation_parameter_root = QuantCalculationParametersRoot(
            data=quant_calculation_parameters, meta=quant_calculations_meta)

        quant_calculations_api = QuantCalculationsApi(api_client)

        post_and_calculate_response = quant_calculations_api.post_and_calculate(
            quant_calculation_parameters_root=quant_calculation_parameter_root)
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_calculate_response = quant_calculations_api.post_and_calculate(
        # quant_calculation_parameters_root=quant_calculation_parameter_root, cache_control=cache_control)
        if post_and_calculate_response[1] == 201:
            output_calculation_result('data', post_and_calculate_response[0])
        else:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = quant_calculations_api.get_calculation_status_by_id(
                id=calculation_id)

            while status_response[1] == 202 and (status_response[0].data.status
                                                 in ("Queued", "Executing")):
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = quant_calculations_api.get_calculation_status_by_id(
                    id=calculation_id)

            for (calculation_unit_id,
                 calculation_unit) in status_response[0].data.units.items():
                if calculation_unit.status == "Success":
                    print("Calculation Unit Id: " + calculation_unit_id +
                          " Succeeded!!!")
                    result_response = quant_calculations_api.get_calculation_unit_result_by_id(
                        id=calculation_id, unit_id=calculation_unit_id)
                    print("Calculation Data")
                    output_calculation_result('data',
                                              result_response[0].read())
                    result_response = quant_calculations_api.get_calculation_unit_info_by_id(
                        id=calculation_id, unit_id=calculation_unit_id)
                    print("Calculation Info")
                    output_calculation_result('info',
                                              result_response[0].read())
                else:
                    print("Calculation Unit Id:" + calculation_unit_id +
                          " Failed!!!")
                    print("Error message : " + str(calculation_unit.errors))

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    config.discard_unknown_keys = True
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3,
                           status=3,
                           status_forcelist=frozenset([429, 503]),
                           backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    components_api = ComponentsApi(api_client)
    try:
        spar_document_name = "pmw_root:/spar_documents/Factset Default Document"
        spar_component_name = "Returns Table"
        spar_component_category = "Raw Data / Returns"
        spar_benchmark_1 = "R.1000"
        spar_benchmark_2 = "RUSSELL_P:R.2000"
        spar_benchmark_prefix = "RUSSELL"
        spar_benchmark_return_type = "GTR"
        startdate = "20180101"
        enddate = "20181231"
        frequency = "Monthly"
        currency = "USD"
        # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
        # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older.
        # cache_control = "max-stale=0"
        get_components_response = components_api.get_spar_components(
            spar_document_name)

        component_id = [
            id for id in list(get_components_response[0].data.keys())
            if get_components_response[0].data[id].name == spar_component_name
            and get_components_response[0].data[id].category ==
            spar_component_category
        ][0]
        print("SPAR Component Id: " + component_id)
        spar_account_identifier = SPARIdentifier(
            id=spar_benchmark_1,
            returntype=spar_benchmark_return_type,
            prefix=spar_benchmark_prefix)
        spar_accounts = [spar_account_identifier]
        spar_benchmark_identifier = SPARIdentifier(
            id=spar_benchmark_2,
            returntype=spar_benchmark_return_type,
            prefix=spar_benchmark_prefix)
        spar_dates = SPARDateParameters(startdate, enddate, frequency)

        spar_calculation_parameters = {
            "1":
            SPARCalculationParameters(componentid=component_id,
                                      accounts=spar_accounts,
                                      benchmark=spar_benchmark_identifier,
                                      dates=spar_dates,
                                      currencyisocode=currency)
        }

        spar_calculation_parameter_root = SPARCalculationParametersRoot(
            data=spar_calculation_parameters)

        spar_calculations_api = SPARCalculationsApi(api_client)
        post_and_calculate_response = spar_calculations_api.post_and_calculate(
            spar_calculation_parameters_root=spar_calculation_parameter_root)
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_calculate_response = spar_calculations_api.post_and_calculate(spar_calculation_parameters_root=spar_calculation_parameter_root, cache_control=cache_control)
        if post_and_calculate_response[1] == 201:
            output_calculation_result(post_and_calculate_response[0]['data'])
        elif post_and_calculate_response[1] == 200:
            for (calculation_unit_id, calculation_unit
                 ) in post_and_calculate_response[0].data.units.items():
                print("Calculation Unit Id:" + calculation_unit_id +
                      " Failed!!!")
                print("Error message : " + str(calculation_unit.errors))
        else:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = spar_calculations_api.get_calculation_status_by_id(
                id=calculation_id)

            while status_response[1] == 202 and (status_response[0].data.status
                                                 in ("Queued", "Executing")):
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = spar_calculations_api.get_calculation_status_by_id(
                    calculation_id)

            for (calculation_unit_id,
                 calculation_unit) in status_response[0].data.units.items():
                if calculation_unit.status == "Success":
                    print("Calculation Unit Id: " + calculation_unit_id +
                          " Succeeded!!!")
                    result_response = spar_calculations_api.get_calculation_unit_result_by_id(
                        id=calculation_id, unit_id=calculation_unit_id)
                    output_calculation_result(result_response[0]['data'])
                else:
                    print("Calculation Unit Id:" + calculation_unit_id +
                          " Failed!!!")
                    print("Error message : " + str(calculation_unit.errors))
    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    config.discard_unknown_keys = True
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3,
                           status=3,
                           status_forcelist=frozenset([429, 503]),
                           backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    calculations = [
        "Security Type", "Security Name", "Run Status",
        "Elapse Time (seconds)", "Calc From Method", "Option Pricing Model",
        "Yield Curve Date", "Settlement Date", "Discount Curve", "Price",
        "Yield to No Call", "OAS", "Effective Duration", "Effective Convexity",
        "CF Coupon"
    ]

    security1 = FISecurity(calc_from_method="Price",
                           calc_from_value=100.285,
                           face=10000.0,
                           symbol="912828ZG8",
                           settlement="20201202",
                           discount_curve="UST")
    security2 = FISecurity(calc_from_method="Price",
                           calc_from_value=101.138,
                           face=200000.0,
                           symbol="US037833AR12",
                           settlement="20201203",
                           discount_curve="UST")

    # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
    # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older.
    # cache_control = "max-stale=0"

    securities = [security1, security2]

    jobSettings = FIJobSettings(as_of_date="20201201",
                                partial_duration_months=[1, 3, 6])

    fi_calculation_parameters = FICalculationParameters(
        securities, calculations, jobSettings)

    fi_calculation_parameters_root = FICalculationParametersRoot(
        data=fi_calculation_parameters)

    fi_calculations_api = FICalculationsApi(api_client)
    run_calculation_response = fi_calculations_api.post_and_calculate(
        fi_calculation_parameters_root=fi_calculation_parameters_root)
    # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
    # run_calculation_response = fi_calculations_api.post_and_calculate(
    # fi_calculation_parameters_root=fi_calculation_parameters_root, cache_control=cache_control)
    if run_calculation_response[1] != 202 and run_calculation_response[
            1] != 201:
        print_error(run_calculation_response)
        sys.exit()

    if run_calculation_response[1] == 201:
        output_calculation_result(run_calculation_response[0].data)
        sys.exit()

    calculation_id = run_calculation_response[2][
        "X-Factset-Api-Calculation-Id"]
    print("Calculation Id: " + calculation_id)

    status_response = fi_calculations_api.get_calculation_status_by_id(
        id=calculation_id)
    while status_response[1] == 202:
        max_age = '5'
        age_value = status_response[2].get("cache-control")
        if age_value is not None:
            max_age = age_value.replace("max-age=", "")
        print('Sleeping: ' + max_age)
        time.sleep(int(max_age))
        status_response = fi_calculations_api.get_calculation_status_by_id(
            id=calculation_id)

    if status_response[1] != 201:
        print_error(status_response)
        sys.exit()

    output_calculation_result(status_response[0].data)
예제 #5
0
def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    config.discard_unknown_keys = True
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3,
                           status=3,
                           status_forcelist=frozenset([429, 503]),
                           backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    components_api = ComponentsApi(api_client)

    try:
        pa_document_name = "PA_DOCUMENTS:DEFAULT"
        pa_component_name = "Weights"
        pa_component_category = "Weights / Exposures"
        portfolio = "BENCH:SP50"
        benchmark = "BENCH:R.1000"
        startdate = "20180101"
        enddate = "20181231"
        frequency = "Monthly"
        # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
        # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older.
        # cache_control = "max-stale=0"
        get_components_response = components_api.get_pa_components(
            document=pa_document_name)
        component_id = [
            id for id in list(get_components_response[0].data.keys())
            if get_components_response[0].data[id].name == pa_component_name
            and get_components_response[0].data[id].category ==
            pa_component_category
        ][0]
        print("PA Component Id: " + component_id)
        pa_accounts = [PAIdentifier(id=portfolio)]
        pa_benchmarks = [PAIdentifier(id=benchmark)]
        pa_dates = PADateParameters(startdate=startdate,
                                    enddate=enddate,
                                    frequency=frequency)

        pa_calculation_parameters = {
            "1":
            PACalculationParameters(componentid=component_id,
                                    accounts=pa_accounts,
                                    benchmarks=pa_benchmarks,
                                    dates=pa_dates),
            "2":
            PACalculationParameters(componentid=component_id,
                                    accounts=pa_accounts,
                                    benchmarks=pa_benchmarks,
                                    dates=pa_dates)
        }

        pa_calculation_parameter_root = PACalculationParametersRoot(
            data=pa_calculation_parameters)

        pa_calculations_api = PACalculationsApi(api_client)

        post_and_calculate_response = pa_calculations_api.post_and_calculate(
            pa_calculation_parameters_root=pa_calculation_parameter_root)
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_calculate_response = pa_calculations_api.post_and_calculate(pa_calculation_parameters_root=pa_calculation_parameter_root, cache_control=cache_control)
        if post_and_calculate_response[
                1] == 202 or post_and_calculate_response[1] == 200:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = pa_calculations_api.get_calculation_status_by_id(
                id=calculation_id)

            while status_response[1] == 202 and (status_response[0].data.status
                                                 in ("Queued", "Executing")):
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = pa_calculations_api.get_calculation_status_by_id(
                    calculation_id)

            for (calculation_unit_id,
                 calculation_unit) in status_response[0].data.units.items():
                if calculation_unit.status == "Success":
                    print("Calculation Unit Id: " + calculation_unit_id +
                          " Succeeded!!!")
                    result_response = pa_calculations_api.get_calculation_unit_result_by_id(
                        id=calculation_id, unit_id=calculation_unit_id)
                    output_calculation_result(result_response[0]['data'])
                else:
                    print("Calculation Unit Id:" + calculation_unit_id +
                          " Failed!!!")
                    print("Error message : " + str(calculation_unit.errors))
        else:
            print("Calculation creation failed")
            print("Error status : " + str(post_and_calculate_response[1]))
            print("Error message : " + str(post_and_calculate_response[0]))

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    config.discard_unknown_keys = True
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3, status=3, status_forcelist=frozenset([429, 503]), backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    try:
        pub_document_name = "Super_client:/publisher/Equity Snapshot.PUB_BRIDGE_PDF"
        pub_account_id = "BENCH:SP50"
        startdate = "-1M"
        enddate = "0M"
        # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
        # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older.
        # cache_control = "max-stale=0"
        pub_account_identifier = PubIdentifier(pub_account_id)
        pub_dates = PubDateParameters(enddate, startdate=startdate)

        pub_calculation_parameters = {
            "1": PubCalculationParameters(pub_document_name, pub_account_identifier, pub_dates)
        }

        pub_calculation_parameters_root = PubCalculationParametersRoot(
            data=pub_calculation_parameters)

        pub_calculations_api = PubCalculationsApi(api_client)
        post_and_calculate_response = pub_calculations_api.post_and_calculate(
           pub_calculation_parameters_root=pub_calculation_parameters_root)
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_calculate_response = pub_calculations_api.post_and_calculate(pub_calculation_parameters_root=pub_calculation_parameters_root, cache_control=cache_control)
        if post_and_calculate_response[1] == 201:
            output_calculation_result(
                "single_unit", (post_and_calculate_response[0].read()))
        elif post_and_calculate_response[1] == 200:
            for (calculation_unit_id, calculation_unit) in post_and_calculate_response[0].data.units.items():
                print("Calculation Unit Id:" +
                      calculation_unit_id + " Failed!!!")
                print("Error message : " + str(calculation_unit.errors))
        else:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = pub_calculations_api.get_calculation_status_by_id(id=calculation_id)

            while status_response[1] == 202 and (status_response[0].data.status in ("Queued", "Executing")):
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = pub_calculations_api.get_calculation_status_by_id(calculation_id)

            for (calculation_unit_id, calculation_unit) in status_response[0].data.units.items():
                if calculation_unit.status == "Success":
                    print("Calculation Unit Id: " +
                          calculation_unit_id + " Succeeded!!!")
                    result_response = pub_calculations_api.get_calculation_unit_result_by_id(id=calculation_id,
                                                                                             unit_id=calculation_unit_id)

                    output_calculation_result(
                        "single_unit", (result_response[0].read()))
                else:
                    print("Calculation Unit Id:" +
                          calculation_unit_id + " Failed!!!")
                    print("Error message : " + str(calculation_unit.errors))

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
예제 #7
0
def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    config.discard_unknown_keys = True
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3,
                           status=3,
                           status_forcelist=frozenset([429, 503]),
                           backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    components_api = ComponentsApi(api_client)

    try:
        vault_document_name = "Client:/aapi/VAULT_QA_PI_DEFAULT_LOCKED"
        vault_component_total_returns = "Total Returns"
        vault_component_performance = "Performance Over Time"
        vault_component_category = "Performance / Performance Relative Dates"
        vault_default_account = "CLIENT:/BISAM/REPOSITORY/QA/SMALL_PORT.ACCT"
        vault_startdate = "20180101"
        vault_enddate = "20180329"
        frequency = "Monthly"
        # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
        # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older.
        # cache_control = "max-stale=0"
        get_components_response = components_api.get_vault_components(
            vault_document_name)
        component_total_returns_id = [
            id for id in list(get_components_response[0].data.keys())
            if get_components_response[0].data[id].name ==
            vault_component_total_returns and get_components_response[0].
            data[id].category == vault_component_category
        ][0]
        print("Vault Total Returns Component Id: " +
              component_total_returns_id)

        component_performance_id = [
            id for id in list(get_components_response[0].data.keys())
            if get_components_response[0].data[id].name ==
            vault_component_performance and get_components_response[0].
            data[id].category == vault_component_category
        ][0]
        print("Vault Performance Over Time Component Id: " +
              component_performance_id)

        vault_account_identifier = VaultIdentifier(vault_default_account)
        vault_dates = VaultDateParameters(startdate=vault_startdate,
                                          enddate=vault_enddate,
                                          frequency=frequency)

        configurations_api = ConfigurationsApi(api_client)
        get_vault_configurations_response = configurations_api.get_vault_configurations(
            vault_default_account)
        configuration_id = list(
            get_vault_configurations_response[0].data.keys())[0]

        vault_calculation_parameters = {
            "total_returns":
            VaultCalculationParameters(componentid=component_total_returns_id,
                                       account=vault_account_identifier,
                                       dates=vault_dates,
                                       configid=configuration_id),
            "performance_over_time":
            VaultCalculationParameters(componentid=component_performance_id,
                                       account=vault_account_identifier,
                                       dates=vault_dates,
                                       configid=configuration_id)
        }

        vault_calculation_parameters_root = VaultCalculationParametersRoot(
            data=vault_calculation_parameters)

        vault_calculations_api = VaultCalculationsApi(api_client)

        post_and_calculate_response = vault_calculations_api.post_and_calculate(
            vault_calculation_parameters_root=vault_calculation_parameters_root
        )
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_calculate_response = vault_calculations_api.post_and_calculate(vault_calculation_parameters_root=vault_calculation_parameters_root, cache_control=cache_control)
        if post_and_calculate_response[
                1] == 202 or post_and_calculate_response[1] == 200:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = vault_calculations_api.get_calculation_status_by_id(
                id=calculation_id)

            while status_response[1] == 202 and (status_response[0].data.status
                                                 in ("Queued", "Executing")):
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = vault_calculations_api.get_calculation_status_by_id(
                    calculation_id)

            for (calculation_unit_id,
                 calculation_unit) in status_response[0].data.units.items():
                if calculation_unit.status == "Success":
                    print("Calculation Unit Id: " + calculation_unit_id +
                          " Succeeded!!!")
                    result_response = vault_calculations_api.get_calculation_unit_result_by_id(
                        id=calculation_id, unit_id=calculation_unit_id)
                    output_calculation_result(result_response[0]['data'])
                else:
                    print("Calculation Unit Id:" + calculation_unit_id +
                          " Failed!!!")
                    print("Error message : " + str(calculation_unit.errors))
        else:
            print("Calculation creation failed")
            print("Error status : " + str(post_and_calculate_response[1]))
            print("Error message : " + str(post_and_calculate_response[0]))

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()
예제 #8
0
def main():
    config = Configuration()
    config.host = host
    config.username = fds_username
    config.password = fds_api_key
    config.discard_unknown_keys = True
    # add proxy and/or disable ssl verification according to your development environment
    # config.proxy = "<proxyUrl>"
    config.verify_ssl = False

    # Setting configuration to retry api calls on http status codes of 429 and 503.
    config.retries = Retry(total=3, status=3, status_forcelist=frozenset([429, 503]), backoff_factor=2,
                           raise_on_status=False)

    api_client = ApiClient(config)

    try:
        screeningExpressionUniverse = QuantScreeningExpressionUniverse(
            universe_expr="ISON_DOW", universe_type="Equity", security_expr="TICKER")
        fdsDate = QuantFdsDate(
            start_date="0", end_date="-5D", frequency="D", calendar="FIVEDAY")
        screeningExpression = [QuantScreeningExpression(
            expr="P_PRICE", name="Price (SCR)")]
        fqlExpression = [QuantFqlExpression(
            expr="P_PRICE", name="Price (SCR)")]

        quant_calculation_parameters = {"1": QuantCalculationParameters(screening_expression_universe=screeningExpressionUniverse,
                                        fds_date=fdsDate, screening_expression=screeningExpression, fql_expression=fqlExpression)}

        quant_calculation_parameter_root = QuantCalculationParametersRoot(
            data=quant_calculation_parameters)
        # uncomment the below code line to setup cache control; max-stale=0 will be a fresh adhoc run and the max-stale value is in seconds.
        # Results are by default cached for 12 hours; Setting max-stale=300 will fetch a cached result which is 5 minutes older. 
        # cache_control = "max-stale=0"
        quant_calculations_api = QuantCalculationsApi(api_client)

        post_and_calculate_response = quant_calculations_api.post_and_calculate(
            quant_calculation_parameters_root=quant_calculation_parameter_root)
        # comment the above line and uncomment the below line to run the request with the cache_control header defined earlier
        # post_and_calculate_response = quant_calculations_api.post_and_calculate(
            # quant_calculation_parameters_root=quant_calculation_parameter_root, cache_control=cache_control)
        if post_and_calculate_response[1] == 201:
            output_calculation_result(post_and_calculate_response[0].read())
        else:
            calculation_id = post_and_calculate_response[0].data.calculationid
            print("Calculation Id: " + calculation_id)

            status_response = quant_calculations_api.get_calculation_status_by_id(id=calculation_id)

            while status_response[1] == 202 and (status_response[0].data.status in ("Queued", "Executing")):
                max_age = '5'
                age_value = status_response[2].get("cache-control")
                if age_value is not None:
                    max_age = age_value.replace("max-age=", "")
                print('Sleeping: ' + max_age)
                time.sleep(int(max_age))
                status_response = quant_calculations_api.get_calculation_status_by_id(id=calculation_id)

            for (calculation_unit_id, calculation_unit) in status_response[0].data.units.items():
                if calculation_unit.status == "Success":
                    print("Calculation Unit Id: " +
                          calculation_unit_id + " Succeeded!!!")
                    result_response = quant_calculations_api.get_calculation_unit_result_by_id(id=calculation_id,
                                                                                               unit_id=calculation_unit_id)
                    print("Calculation Data")
                    output_calculation_result(json.loads(result_response[0].read())['data'])
                    result_response = quant_calculations_api.get_calculation_unit_info_by_id(id=calculation_id,
                                                                                             unit_id=calculation_unit_id)
                    print("Calculation Info")
                    output_calculation_result(json.loads(result_response[0].read())['data'])
                else:
                    print("Calculation Unit Id:" +
                          calculation_unit_id + " Failed!!!")
                    print("Error message : " + str(calculation_unit.errors))

    except ApiException as e:
        print("Api exception Encountered")
        print(e)
        exit()