Getting Started

API Token and Documentation

The API token can be found by going to the https://pi.ompnt.com home screen and then clicking on the platform tab on the left. The platform page will have a copy icon to copy your API token.

Omega Point's API query tool, GraphiQL, is the best way to test sample queries. To access it, click on the external link icon on the platform page.

Open the API documentation by clicking on the top right "Docs" tab on the GraphiQL page. Please refer to the API documentation for the full list of available query fields, as this readme will only include a small subset of examples.

Running a POST request in Python

Here is some sample code to run a GraphQL query with a POST request. If you are not familiar with requests or need help installing this library, see http://www.pythonforbeginners.com/requests/using-requests-in-python. Sample query strings are given below. The API token must be passed in the request for authentication. Be sure to set it in the example below.

import json
import requests
import sys

# To run this example:
# 1. Replace INSERT_YOUR_API_TOKEN_HERE with a valid token for your account.
# 2. Replace the values in the 'variables' section with your own portfolioId
#    and fromDate and toDate values.

# You can get an API token by logging in to https://pi.ompnt.com, then selecting 'Platform'
# from the sidebar. From here, you can view existing tokens or create new ones.
API_TOKEN=INSERT_YOUR_API_TOKEN_HERE
GRAPHQL_URL='https://api.ompnt.com/graphql'

headers = {
    'Content-Type': 'application/json',
    'Authorization': API_TOKEN
}

# To run this sample query, you'll need to replace the variables section below with values
# that are appropriate for your account.

query =  """
query($portfolioId: String!, $fromDate: Date!, $toDate: Date!) {
    portfolio(id: $portfolioId) {
        name
        dates(from: $fromDate, to: $toDate) {
            date
            equities {
                id {
                    ticker
                    mic
                }
            economicExposure
            }
        }
    }
}
"""

# Your portfolioId below is the next part of the url after /p/ when you're on
# that portfolio's page. For example, if you had selected a portfolio and
# your URL was: https://pi.ompnt.com/demo_account/p/omega_point_example/overview/performance
# Then your portfolioID would be 'omega_point_example'.
#
# Please note that this is one of two styles of portfolioId, the short form. The longer form is
# a UUID v4 alphanumeric string, and either can be used in the portfolioId field.

def run_query(query, variables=None):
    if variables is None:
        variables = {
            'portfolioId': 'omega_point_example',
            'fromDate': '2016-01-24',
            'toDate': '2016-02-24'
        }

    data = {}
    data["query"] = query
    data["variables"] = variables

    try:
        response = requests.post(GRAPHQL_URL, headers=headers, data=json.dumps(data))

        # throw an exception if we got a non-OK response
        response.raise_for_status()

        return json.loads(response.text)

    except requests.exceptions.RequestException as ex:
        print("An error occurred during the request: ")
        print(ex)
        sys.exit(1)

results = run_query(query)
print(results)

Sample Queries

Models

Let's begin with a simple query to return the model ids.

query = """
{
  models {
    id
  }
}
"""
results = run_query(query)

Be sure to use valid model ids for the rest of the examples.

Factor

Factors are identified by a unique id. Here is a sample query that will return a list of factors with their id, name, and category.

query = """
{
  model(id:"AXWW4-MH") {
    factors {
      id
      name
      category
    }
  }
}
"""
results = run_query(query)

If you want to find the data for a specific factor, Volatility, here is a sample query for normalized returns in 2017.

query = """
{
  model(id:"AXWW4-MH") {
    factors(id: "Volatility") {
      performance(from: "2017-01-01", to: "2017-01-31") {
        date
        normalizedReturn
      }
    }
  }
}
"""
results = run_query(query)

Security

Securities can be identified in multiple ways. Here's a sample query to search by ticker and MIC code.

query = """
{
  model(id: "AXWW4-MH") {
    security(ticker: "AAPL" mic: "XNAS"){
      descriptors(on: "2018-04-10") {
        name
      }
    }
  }
}
"""
results = run_query(query)

Since there may be small variations in ticker names and MIC codes, searching by sedols is recommended. Here is another sample query that returns the same data as before, but with a sedol lookup.

query = """
{
  model(id: "AXWW4-MH") {
    security(sedol: "2046251"){
      descriptors(on: "2018-04-10") {
        name
        ticker
        mic
      }
    }
  }
}
"""
results = run_query(query)

In addition to returning security descriptor information, the API can also return security performance. It can also be used to return a benchmark's performance by using a proxy ETF as the security. For example, if you want to analyze the performance of the S&P 500 benchmark in 2017, the following query uses SPY as the proxy ETF.

query = """
{
  model(id: "AXWW4-MH") {
    security(ticker: "SPY" mic: "ARCX"){
      performance(from: "2017-01-01" to: "2017-12-31") {
        date
        percentPriceChangeCumulative {
          total
          attribution{
            summary {
              factors
              specific
            }
          }
        }
      }
    }
  }
}
"""
results = run_query(query)

Portfolio

The API can return performance, risk, and exposure data for portfolios that are already loaded into the system. Portfolios are identified by a unique id. Here is a sample query that will return a list of portfolios with their id, name, and model.

query = """
{
  portfolios {
    id
    name
    modelId
  }
}
"""

results = run_query(query)
print results["data"]["portfolios"][0]

The result will look something like this:

{u'modelId': u'AXWW4-MH', u'id': u'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', u'name': u'My Portfolio'}

Here's a sample query that will return risk data for this portfolio. Be sure to replace the portfolio_id and model_id below.

model_id = "AXWW4-MH"
portfolio_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
start_date = "2017-01-01"
end_date = "2017-12-31"

query = """
{
  model(id:"%s") {
    portfolio(id:"%s") {
      risk(from:"%s" to:"%s") {
        date
        total
        attribution {
          summary {
            specific
            factors
          }
        }
      }
    }
  }
}
""" % (model_id, portfolio_id, start_date, end_date)
results = run_query(query)

For portfolio attribution or exposures, please refer to the API documentation on the graphiql page for details.

PositionSet Schema

If a portfolio is not loaded into https://pi.ompnt.com, it must be formatted in the PositionSet schema in order to make API calls. It must contain a list of portfolio dates and for each date and position, the security asset class, security identification, and economic exposure (or size of the position). Here is a sample PositionSet where there is only one date and two equity positions on that date.

positions_set = {
    "dates": [
        {
            "date": "2017-01-04",
            "equities": [
                {
                    "economicExposure": 2000.00,
                    "id": {
                        "mic": "XNAS",
                        "ticker": "AAPL"
                    }
                },
                {
                    "economicExposure": 1000.00,
                    "id": {
                        "mic": "XNAS",
                        "ticker": "MSFT"
                    }
                },
            ],
            "equity": 5000.00
        }
    ]
}

The portfolio API can also be used to return a PositionSet for a portfolio that is already loaded into https://pi.ompnt.com.

portfolio_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
start_date = "2017-01-04"
end_date = "2017-01-04"

position_set_query = """
{
  portfolio(id: "%s") {
    dates(from: "%s" to: "%s") {
      date
      equity
      equities {
        id {
          ticker
          mic
        }
        economicExposure
      }
    }
  }
}
""" % (portfolio_id, start_date, end_date)
results = run_query(position_set_query)
position_set = results["data"]["portfolio"]

Simulation

The API can return the risk, performance, and factor exposures for a simulated portfolio. In this example, the simulated portfolio will be generated from a starting PositionSet and two additional securities will be added, but in general any updates to the portfolio can be made.

position_set_new = position_set.copy()
new_securities = [
  {
    'id': {'ticker': 'AAPL', 'mic': u'XNAS'},
    'economicExposure': 50000.00
  },
  {
    'id': {'ticker': 'MSFT', 'mic': u'XNAS'},
    'economicExposure': 50000.00
  }
]
for new_security in new_securities:
    position_set_new["dates"][0]["equities"].append(new_security)

Once the PositionSet is updated, use the following query to return the factor exposures with the new positions.

query = """
query ($positionSet: PositionSetInput! $modelId: String!)
{
  model(id: $modelId) {
    simulation(positionSet: $positionSet) {
      exposure {
        date
        factors(category: "Style") {
          id
          net
        }
      }
    }
  }
}
"""
variables = {
  "positionSet": position_set_new,
  "modelId": "AXWW4-MH"
}
results = run_query(query, variables=variables)

Here the position set and model id are passed as variables to the POST request.

Additional Help

Output to CSV/Excel

In many workflows, the results need to be saved for further analysis. Here is a simple example to save the daily specific attribution for your portfolio. Using the sample query above for portfolio risk, the results may look like this:

{
  "data": {
    "model": {
      "portfolio": {
        "risk": [
          {
            "date": "2017-01-02",
            "total": 0.2197601,
            "attribution": {
              "summary": {
                "specific": 0.016606011911523978,
                "factors": 0.983393988088476
              }
            }
          },
          {
            "date": "2017-01-03",
            "total": 0.21932538,
            "attribution": {
              "summary": {
                "specific": 0.016591339162409246,
                "factors": 0.9834086608375907
              }
            }
          },
          ...
}


The data structure is nested where risk has a range of dates and the specific risk is within attribution and summary. The pandas library has a convenient way of flattening this data structure. Here is sample code that will return a flattened dataframe.

from pandas.io.json import json_normalize
df = json_normalize(results["data"]["model"]["portfolio"]["risk"])

This next line will output only the date and specific risk to a csv file.

# only exports the specified df columns
df[["date","attribution.summary.specific"]].to_csv("myfile.csv")

Alternatively, you can also save the file to excel.

df[["date","attribution.summary.specific"]].to_excel("myfile.xlsx")

-----
It is also possible to export the entire resulting dataset, which can be exported directly to excel.

from pandas.io.json import json_normalize
df = json_normalize(results)

# exports all columns from the data frame
df.to_excel("myfile.xlsx")


Did this answer your question?