Posted: -

Now when you sign in to your Dashboards account and navigate either to the description of plans or to the support page you will have access to a chat icon in the lower right corner:



Type any question and an Everysk representative will provide answers right away.

Posted: -

This blog demonstrates some properties from our fixed income asset classes. Specifically we will show how Everysk can capture intricate correlation effects between a corporate bond and a credit default swap.


First, let’s build a portfolio in Dashboards containing $1M face of a hypothetical 5 year bond issued by Chesapeake and a hypothetical 5 year CDS.


Security Quantity
CORP:CHK 20220628 6.77 100 $1,000,000
CDS:CHK 20220628 P5 $1,000,000


The corporate bond above matures on june 2022, has a 6.77% coupon and is priced at par. The CDS has the same maturity and buyer of credit protection pays 500 basis points annually. See all supported symbology here.


By stress testing this portfolio against a credit index, such as the Merrill Lynch US Corporate Bond BB Total Return Index, we get the following expected PL (for a 2% drop, which is in the range of weekly movements that this index can experience):


Portfolio CDS Bond
Expected Value (EV) 0.06% 0.76% -0.70%


We can see that the risk of the portfolio is largely hedged.


A more interesting stress test that captures some correlated effects is to shock the SP500. Below, we include a dynamic visualization whereby SP is being shocked from -1.2% (leftmost grey bar) to +1.2% (rightmost grey bar). This range is automatically calculated by Everysk and reflects the expected range of SP moves in a week:



The leftmost bar is highlighted to show it is the “active” bar. Move your mouse over the bar and you will be able to see the expected PL for the portfolio in that scenario, 0.22%. We also show low probability, high impact positive profit and loss (PL) of +1.09% and negative of -0.67%. These extreme PLs, specially the negative one, are generally called Conditional Value at Risk (CVaR) or expected shortfall. Then move the mouse over the 2 securities on the right: in a scenario of SP falling 1.2%, the corporate bond tends to lose money and the CDS tends to make. The contributions from each security to the overall portfolio properties are shown when you move the mouse over the securities. The summary is provided below:


Portfolio CDS Bond
CVaR+ 1.09% 0.76% 0.33%
EV 0.22% 0.47% -0.25%
CVaR- -0.67% 0.05% -0.72%


To visualize what happens when SP is up, just unselect the leftmost bar by clicking on it and then click on the rightmost bar. As you move your mouse over the other scenarios, you will realize that the right visualization changes accordingly. The summary for a +1.2% SP shock:


Portfolio CDS Bond
CVaR+ 0.68% -0.49% 1.16%
EV -0.21% -0.66% 0.45%
CVaR- -1.15% -0.90% -0.25%


So why is that the the CDS is expected to make more money (+0.47%) when the markets drops than the corporate bond is expected to lose (-0.25%), if the payer CDS is an exact short of the bond?


The main reason for this (expected) behavior is that corporate bonds have a credit spread risk factor that is positively correlated to the markets and an interest rate risk factor that is negatively correlated with the markets. When the markets are falling, the rate sensitivity helps immunize some of the pain, which is not present in the CDS. Therefore the CDS is expected to make more money. Conversely, when the markets are up the reverse happens: CDS is expected to lose more money (-0.66%) than the bond makes (+0.45%).


We can easily eliminate the interest rate effect described above by adding a payer swap to the portfolio:



Security Quantity
CORP:CHK 20220628 6.77 100 $1,000,000
CDS:CHK 20220628 P5 $1,000,000
SWAP:US 20220628 P1.77 $1,000,000


The resulting behavior for SP500 shocks would be:



We have largely eliminated the behavior (note small value for grey bars).


Capturing these correlated effects via visualizations can be a powerful metaphor to engage an existing and/or prospective client. You can find some code that replicates these results using our PortEngine API here. Check the symbology of fixed income securities here.

Posted: -

We are happy to announce the release of our fixed income asset class library. It is comprised of 7 new instruments, all sharing common risk elements:


The new fixed income asset classes and their respective symbology prefix are:

  • Convertibles (CONV:)
  • Exchangeables (EXCH:)
  • Term Debt (LOAN:)
  • Corporate Bonds (CORP:)
  • Government Bonds (GOV:)
  • Credit Default Swaps (CDS:)
  • Interest Rate Swaps (SWAP:)


The above schematic illustrates the risk factors that are simulated for each security. For example: for convertibles, we simulate rate risk, spread risk and convertibility risk (underlying stock risk). We also need to simulate FX risk when the security currency is different from the base currency of the portfolio (FX risk not shown in the schematic above).


Some salient features for the remaining securities:


  • For corporate bonds we simulate rate and spread risk (convertibility risk is greyed out).
  • For Government bonds we simulate rate risk and keep country spreads constant.
  • Term loans have limited rate rate risk and no convertibility.
  • CDS has pure spread (credit) risk.
  • Interest rate swaps has pure rate risk.


The prefix inside each box is used for specify the security. For example: CONV:AMD 20250901 2.5 140 78.0 is our symbology for Advanced Micro Device’s convertible expiring on September 2025, with a 2.5% coupon, priced at $140 and with a strike price of $78. See all supported symbology here.


These 7 new securities are fully integrated with the existing 10, namely: FX forwards, FX options, index options, future options, equity options, futures, global stocks, ETFs, mutual funds and indices. Furthermore our multi-asset, multi-currency calculation engine captures the correlated nature of all these assets.

Posted: -

Most money managers currently lack an efficient way to test the impact of new trades prior to executing them. The various systems available in the market are large deployments that were not designed for these type of on-the-flight, exploratory analytics.


Thus, if you want to quickly test how the addition of those SPY put contracts might affect the portfolio downside in a market shock, as a for instance, you might be out of luck.


In what follows we will show how what-if analysis can be performed effortlessly in Everysk Dashboards, in just 3 steps:


Step 1: Create a clone of the portfolio

In My Portfolios tab, drag and drop the portfolio you are interested to perform what-if analysis to the central panel. Then, in the right panel, you will see a new icon to create the clone:



Step 2: Edit the clone

When you click the button from Step 1, an editor with all properties and positions will open (see figure below):



Here you can quickly change many properties of the original portfolio, such as name, date, base currency and net asset value. Additionally, you can easily modify the contents of the original portfolio as follows:


  • To remove positions, just select them and click on the trash icon at the end of the list.
  • To change a position quantity, just edit the Contracts/Shares field(s)
  • To add a new position, just click on the button +Add Position


The image above illustrates a portfolio with 100 shares of Apple and 100 shares of Facebook that has been cloned. A new hedge was added to the portfolio, consisting of 1 at-the-money put option on SPY.


Step 3: Compare Original and Clone


Finally you can superimpose the original and clone with a template such as Stress Test Comparison



The unhedged portfolio is the light green and the portfolio with the put option is the dark green. Portfolio/Wealth managers can quickly ascertain the expected behavior of the trade just before executing it. All the process takes a few seconds from beginning to end.

Posted: -

This post explains in detail how we account for short positions. To understand shorts, we really should start with longs. Suppose a portfolio manager has a hypothetical single-stock portfolio with 100 shares of IBM. As an example, Everysk might produce a distribution of future profit and loss (PL) for the stock with a minimum PL of $-300, a maximum of $450 and an expected PL is $50.


Considering that IBM costs $180/share, $18000 will be necessary to generate the distribution of PL above. In order to convert the dollar PLs to percent amounts, all we need to do is divide them by $18000 (which is the net asset value, NAV, of this single-stock portfolio).


But, what happens if the same illustrative single stock portfolio was short 100 shares of IBM, instead of long? The distribution of profit and loss would simply be the flip side of the above, namely: a minimum of $-450, a maximum of $300 and an expected PL of $-50. How about the percentage distribution? What is the NAV to use as the denominator in the calculations?


The answer will largely depend on how much margin will be encumbered to enter the short. If Regulation-T applies, the investor will be required to have an end of day margin of at least 50% of the full value of the short. Thus, in this example, the investor would be required to have $9000 encumbered. The PL variability in percent would be larger than the long example (the distribution of PL would be divided by $9000).


To complicate matters, many investors might opt for a different margin calculation such as “portfolio margin”. This margin mechanism is a risk based measure that tends to benefit investors with offsetting positions, requiring less money to be set aside.


So, instead of second guessing how the encumbered margin amount is calculated for our clients, we provide 2 ways for that information to be explicitly supplied, as follows:


Method 1: Providing a NAV for the portfolio

Providing a net asset value explicitly (we call it net liquidating value here at Everysk). This can be done when the portfolio is imported into Dashboards:



Basically, all the PL calculations in a base currency will be divided by the provided NAV (which presumably includes the margin amounts) rather than an NAV calculated by Everysk (which only includes the cash account).


Method 2: Providing a margin amount

Instead of an explicit NAV, this method requires an explicit margin. Everysk has an instrument for this, margin:



The picture above shows the specification of an explicit margin amount. Both methods will produce the same percent risk statistics.

Posted: -


This blog post illustrates how to build a Google Sheets “front end” that is integrated with PortEngine, our REST API. Our calculation engine generates JSON responses that need to be visualized somehow. We describe a simple way to programatically write the portfolio results into a Google Sheets.


We will use a library called gspread. We follow closely the recipe described here.


One step that is not clear in the recipe above is that you will need to share the Google spreadsheet, which we called portOutput, with the email contained in the json file under ‘client_email’ key.


The main function is very simple:


def main():
    tickerlist= {
            'id1': ['IBM', 85, ''],
            'id2': ['AAPL', 130, ''],
            'id3': ['CVX', 100, ''],
            'id4': ['GS', 50, ''],
            'id5': ['F', 150, ''],
            'id6': ['MMM', 30, '']
        }


    worksheet = getSheet('portOutput')
    test_st_projection(tickerlist,worksheet)
    return


This function performs 2 simple tasks, namely: 1) authorizes the user with the proper service account key (see how to get one here) to read/write to the google spreadsheet in the cloud; and 2) performs stress tests using PortEngine and writes results to the spreadsheet.


The function to authorize user credentials is described below:


def getSheet(name):
    json_key = 'gspread_key.json'
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(json_key,scope)


    gc = gspread.authorize(credentials)
    wks = gc.open(name)
    worksheets = wks.sheet1
    return worksheets


The function that performs a stress test in the portfolio for a -5% shock in the SP500 and writes results to the spreadsheet is described below:


def test_st_projection(tickerlist,worksheet):
    api_method = 'st_projection'


    # make a projection list with value and growth indices
    projection_list = ['IND:RLV', 'IND:RLG']
    args = {
        'date': '20161220',
        'shock': 'SPY',
        'magnitude': -0.05,
        'projection': projection_list
    }
    args['tickerlist'] = tickerlist

    req = api.APIRequestor(cfg.API_SID, cfg.API_TOKEN, cfg.API_ENTRY, cfg.API_VERSION)
    ret = req.request(api_method, args)
    if ret['status'] != 200:
        raise api.APIError(ret)


    # Pre-processing
    projections = ret['response']['values']
    cvarneg_proj     = [i['cvarneg'] * 100.0 for i in projections]
    cvarpos_proj     = [i['cvarpos'] * 100.0 for i in projections]
    ev_proj          = [i['ev'] * 100.0 for i in projections]
    factor_ids  = [i['id'] for i in projections]




    api_method = 'st_aggregation'
    ret = req.request(api_method, args)
    if ret['status'] != 200:
        raise api.APIError(ret)


    # Pre-processing
    aggregations = ret['response']['values']
    cvarneg_agg     = [i['cvarneg'] * 100.0 for i in aggregations]
    cvarpos_agg     = [i['cvarpos'] * 100.0 for i in aggregations]
    ev_agg          = [i['ev'] * 100.0 for i in aggregations]
    sec_ids  = [i['id'] for i in aggregations]


    # write projections
    sz = len(ev_proj)
    table = [factor_ids,cvarpos_proj,ev_proj,cvarneg_proj]
    rg = range_a1((1,1),sz,len(table))
    cell_list = worksheet.range(rg)
    idx=0
    for rows in table:
        for i,val in enumerate(rows):
            cell_list[i+idx].value = val
        idx += sz
    worksheet.update_cells(cell_list)


    # write aggregations
    sz = len(ev_agg)
    sec_tickers = getTickers(tickerlist,sec_ids)
    table = [sec_tickers,cvarpos_agg,ev_agg,cvarneg_agg]
    rg = range_a1((8,1),sz,len(table))
    cell_list = worksheet.range(rg)
    idx=0
    for rows in table:
        for i,val in enumerate(rows):
            cell_list[i+idx].value = val
        idx += sz
    worksheet.update_cells(cell_list)


The above function performs the same -5% shock twice:


  1. The first time it calculates left tail risk (CVaR_neg), expected value (EV) and right tail (CVaR_pos) per factor. In the example, the code specifies an on-the-fly 2-factor model with value and growth indices (PortEngine calculates the contribution from these 2 factors plus residual to the portfolio’s properties). Thus the final matrix, including titles, has 4 rows by 3 columns. Summing the rows retrieves the portfolio CVaR-, EV and CVaR+
  2. The second time it calculates the contribution from each security to the same portfolio properties above. The matrix that is written to the spreadsheet has 4 rows and 6 columns, one per security:

Value and growth contributions to CVaR-,EV,CVaR+


All it takes is a few lines of code to output our calculations into a spreadsheet. For more information on our API look at: www.everysk.com/api or send us a note to api@everysk.com to request your API key. Refer to the full code for this post: write_2_sheet.py

Posted: -


We could be approaching a point when it will be wise to diversify away from a purely US-centric portfolio. Others in the industry share this view:


“A lot of other markets have not done nearly as well [as the U.S.], and they look kind of cheap. So I think investors should think about diversifying, using this relative weakness in foreign markets to diversify away from the U.S.”, as stated by Jeffrey Gundlach here.


When you invest globally, foreign exchange plays a critical role on your risk/reward assessment. The relative performance of the foreign currency versus your base currency, under certain scenarios (oil down for example) can affect your portfolio in unforeseen ways. Not many systems can model the intertwining effects between currency and other assets the way we do.


We have posted several blogs covering how Everysk handles currency in the recent past. This current blog provides an index to all those posts, with a small blurb on each one:


March 16, 2016 - FX Effects - https://www.everysk.com/blog/2016/03/FX-effects


This blog was our first write-up on how currencies are incorporated into equity simulations. We augment the covariance matrix with currency information, which is simulated as a log-normal process. This early post considered that the base currency of the portfolio was always in USD. Later on, we added functionality to make base currency an user-defined field.


March 17, 2016 - FX Factor Effects - https://www.everysk.com/blog/2016/03/FX-effects-factors


This blog described how a cross-sectional factor model would take currency into account. Generally it has to proceed in 2-steps:


  1. Measure the total portfolio exposure to factors
  2. Measure each factor Beta to the currency we are interested


We described how the mapping to factors makes the system less granular to monitor currency risks.


September 9, 2016 - Base Currency - https://www.everysk.com/blog/2016/09/Base-Currency


After a few months without writing about FX, we returned with a post describing a new feature, the flexibility to change the base currency of the portfolio to any one of the 40 available currencies.


We provided an illustrative example of how Everysk simulates the currency rates with other assets to incorporate critical correlation information that would otherwise be lost.


September 21,2016 - Currency Oil effects - https://www.everysk.com/blog/2016/09/Currency-oil


This blog provided a step-by-step guide on how to use Dashboards to find the asnwer to the following question: “An institutional investor in Europe wants to increase her/his emerging markets exposure. Investment opportunities in India and Brazil are being contemplated. Given that this investor is bearish on oil, which country is more vulnerable?”


October 20, 2016 - Broker Financing - https://www.everysk.com/blog/2016/10/Broker-financing


This blog describes the subtle effects of purchasing a foreign stock with broker financing and/or outright purchase.


November 2016 - Trump Stress Tests - https://www.everysk.com/blog/2016/11/Trump-Stress-Tests


This blog post shows what market moves we forecasted on November 8, given a large MXN decline. Our conditional forecasts are very close to realized moves on those assets.


These 6 posts summarize our granular approach to modeling FX in Everysk. Please contact us at sales@everysk.com if you would like to learn more about your own currency risks going forward.

Posted: -


This post is an illustrative example on how to use PortEngine, our REST API, to compare your portfolio with a hypothetical portfolio with same stocks, but with different allocations reflecting equal risk contributions (ERC). ERC, also called risk parity, is a portfolio whereby all positions have the same marginal contribution to total risk. This approach has experienced phenomenal growth and has been advocated by important investors, most notably Bridgewater and Panagora. See interesting article here.


The second step of this example involves comparing the expected shortfall (CVaR-) for both portfolios, for a 5% shock in the SP500 and dissecting the contribution from value and growth factors to that shortfall risk. This is not a trivial calculation as we want to project the portfolio’s left tail risk to a factor model, conditional on a specific shock. We will show how this can be easily achieved using PortEngine.


Why: Comparing how both portfolios react to the same shock (in this case SP down 5%) will provide an apples-to-apples reading of how much equities risk we are assuming by deviating from ERC allocations. We will also show the contributions from value and growth factors to the left tail risk changes.


Steps: a) Given a portfolio, find the equivalent ERC allocations using Scipy’s optimization module; b) Compute the difference in left tail risk from a SP 5% shock between the original portfolio and the ERC portfolio.


The simple code below will perform all calculations:


 def main():
    # read tickers from yahoo - retain last entry
    tickerlist = {
        'id1': ['IBM', 85, ''],
        'id2': ['AAPL', 130, ''],
        'id3': ['CVX', 100, ''],
        'id4': ['GS', 50, ''],
        'id5': ['F', 150, ''],
        'id6': ['MMM', 30, '']
    }


    tickers = []
    shares = []
    for keys, values in tickerlist.iteritems():
        tickers.append(values[0])
        shares.append(values[1])
    cov, data = buildCov(tickerlist)


    # find risk parity weights
    wtsERC = solveERC(cov.values)


    # convert weights in shares
    origNLV = np.sum(np.array(shares) * data[-1:].values)
    sharesERC = wtsERC * origNLV / data[-1:].values


    # assemble a new tickerlist with ERC shares
    idx = 0
    erc_tickerlist = {}
    trades = {}
    for keys, values in tickerlist.iteritems():
        erc_tickerlist[keys] = (values[0], sharesERC[0][idx], '')
        trades[values[0]] = sharesERC[0][idx] - values[1]
        idx += 1


    # call PortEngine
    leftTail, delta_leftTail = compare_ST(tickerlist, erc_tickerlist)
    print trades
    print delta_leftTail
    return


The first function called, buildCov, simply builds a covariance matrix using Adjusted closing prices for the last 2 years. We use functions from Pandas library:


def buildCov(tickerlist):
    start = datetime.datetime(2015, 1, 1)
    end = datetime.datetime(2016, 12, 20)
    tickers = [t[0] for t in tickerlist.values()]
    data = web.DataReader(tickers, 'yahoo', start, end)['Adj Close']
    data = data[tickers]
    ret = np.log(data / data.shift(1))[1:]
    cov = ret.cov()
    return (cov, data)


The next function takes a covariance matrix and computes the weights reflecting equal risk contribution, i.e. each position has the same marginal contribution to total risk:


def solveERC(S):
    J, K = S.shape
    initW = np.ones((J, 1)) / J
    bnds = ((0, 1),) * J
    cst = prepare_constraint(J)
    res = minimize(riskParity, initW, constraints={'type': 'eq', 'fun': cst}, bounds=bnds, args=(S,), method='SLSQP', tol=1e-6, options={'disp': True})
    return np.array(res['x'])


The function above makes a call to Scipy’s optimization module. The objective function, riskParity is defined below:


def riskParity(wts, S):
    N, M = S.shape
    portRisk = np.dot(wts, np.dot(wts, S))
    mctr = wts * np.dot(S, wts)
    mctr = mctr / portRisk
    accum = 0.0
    for i in xrange(0, N):
        for j in xrange(i + 1, N):
            delta_mctr = mctr[i] - mctr[j]
            accum += delta_mctr * delta_mctr
    return 2.0 * accum


By minimizing this objective function we are minimizing the differences on marginal contribution to total risk from each position.


The following function establishes that weights should add to 100% (Caveat: this illustrative code will work with long only portfolios):


def prepare_constraint(J):
    ones = np.ones((1,J))
    constraint = lambda x: 1.0 - np.dot(ones, x)
    return constraint


Finally we can call PortEngine with 2 tickerlists, the original and the new one reflecting ERC:


def compare_ST(tickerlist, erc_tickerlist):
    api_method = 'st_projection'


    # make a projection list with value and growth indices
    projection_list = ['IND:RLV', 'IND:RLG']
    args = {
        'date': '20161220',
        'shock': 'IND:SPX',
        'magnitude': -0.05,
        'projection': projection_list
    }
    args['tickerlist'] = tickerlist
    req = api.APIRequestor(cfg.API_SID, cfg.API_TOKEN, cfg.API_ENTRY, cfg.API_VERSION)
    ret = req.request(api_method, args)
    if ret['status'] != 200:
        raise api.APIError(ret)


    # Pre-processing
    projections = ret['response']['values']
    cvarneg = [i['cvarneg'] * 100.0 for i in projections]
    cvarpos = [i['cvarpos'] * 100.0 for i in projections]
    ev = [i['ev'] * 100.0 for i in projections]
    factor_ids = [i['id'] for i in projections]


    # Portfolio CVaR-, EV and CVaR+ for the specific shock:'
    port_CVaRNeg = fsum(cvarneg)
    port_EV = fsum(ev)
    port_CVaRPos = fsum(cvarpos)


    # Contribution to portfolio EV, CVaR from Industrial and Energy sectors (%):'
    contrib_CVaRNeg = [(factor_ids[x], cvarneg[x]) for x in xrange(0, len(ev))]


    #####################################
    # Second call with erc tickerlist
    #####################################
    args['tickerlist'] = erc_tickerlist
    ret = req.request(api_method, args)
    if ret['status'] != 200:
        raise api.APIError(ret)


    # Pre-processing
    projections = ret['response']['values']
    erc_cvarneg = [i['cvarneg'] * 100.0 for i in projections]
    factor_ids = [i['id'] for i in projections]


    # Portfolio CVaR-, EV and CVaR+ for the specific shock:'
    erc_port_CVaRNeg = fsum(erc_cvarneg)


    # Contribution to portfolio EV, CVaR from Industrial and Energy sectors (%):'
    delta_CVaRNeg = [(factor_ids[x], (cvarneg[x] - erc_cvarneg[x])) for x in xrange(0, len(ev))]
    leftTail = (port_CVaRNeg, erc_port_CVaRNeg)
    return (leftTail, delta_CVaRNeg)


The first few lines from the code above specify an on-the-fly factor model with value and growth indices (residual will be computed by PortEngine):


    api_method = 'st_projection'
    # make a projection list with value and growth indices
    projection_list = ['IND:RLV', 'IND:RLG']


Then we proceed to compute the expected shortfall (CVaR-) for the original portfolio as well as the ERC allocations. The code returns all the deltas to show which portfolio is more vulnerable to an US equities shock. Granular details about the composition of the deltas in terms of value/growth explanatory power is also returned.


All it takes is a few lines of code. For more information on our API look at: www.everysk.com/api or send us a note to api@everysk.com to request your API key. Refer to the full code for this post: diff_2_erc.py

Posted: -


In the next few months we will write some examples to illustrate how PortEngine, our portfolio API, can be combined with other APIs to generate innovative ideas. The examples are meant for illustrative purposes and we hope that our API users will create interesting products out of these examples.


The first one is a contextual news engine, i.e. an engine that understands the macro risks of your portfolio and presents the user with most relevant news, given her/his portfolio’s top macro vulnerabilities.


Why: We have limited bandwidth to absorb all the news at any time, and should be presented with the most relevant ones, given our specific investments. This top-down filtering is different, and much harder, than simply presenting the user with bottom-up news for each investment company.


Steps: a) Sort various macro shocks affecting your portfolio, from worst to best, using PortEngine; b) Perform a custom web search on sorted keywords and return url links, organized from most relevant to less.


The main code is presented below:


def main():
    tickerlist = {
        'id1': ['CVX', 100, ''],
        'id2': ['XOM', 100, '']
    }
    shocks = {
        'oil over-supplied': ['USO', -0.05, ('oil', 'opec')],
        'trump': ['SPY', -0.05, ('us', 'trump')],
        'europe': ['EURUSD', -0.05, ('europe')]
    }
    service = build("customsearch", "v1", developerKey=google_api_key)
    # sort vulnerabilities and return keywords
    macro_keywords = sort_stress_tests(tickerlist, shocks)
    # custom search
    results = prepare_custom_search(macro_keywords, shocks, service, google_customSearch_id, dateRestrict='d2', num=10)
    print results
    return


The code is very simple. We call sort_stress_tests to calculate and sort the forward looking expected PL of the portfolio under 3 shocks, namely: SPY down 5%, the Euro devaluing 5% to the dollar and USO down 5%. The illustrative portfolio is comprised of 100 shares of Chevron and Exxon, each. The dictionary shocks contain various keywords that will be used further down.


Step 1) Sorting the macro vulnerabilities:


def sort_stress_tests(tickerlist,shocks):
    port_EV = np.empty(3)
    scenarios = []
    args = {}
    api_method = 'st_aggregation'
    args['date'] = '20161220'
    args['tickerlist'] = tickerlist
    req = api.APIRequestor(cfg.API_SID, cfg.API_TOKEN, cfg.API_ENTRY, cfg.API_VERSION)


    idx=0
    for keys,values in shocks.iteritems():
        args['shock'] = values[0]
        args['magnitude'] = values[1]
        ret = req.request(api_method, args)
        if ret['status'] != 200:
            raise api.APIError(ret)
        else:
            response = ret['response']['values']
            ev = [i['ev'] * 100.0 for i in response]
            port_EV[idx] = fsum(ev)
            scenarios.append(keys)
            idx += 1


    idx=np.argsort(port_EV)
    scenarios = np.array(scenarios)
    priority_keywords = scenarios[idx]
    return priority_keywords


The code above calls Everysk’s PortEngine in a loop to establish the order of top-down vulnerabilities, from worst to best. It returns the keywords for the search in the proper order.


Step 2) Given sorted keywords from Step 1, assemble a custom web search using the Google Custom Search engine API (cse).


This step involves the initial setup of a custom search engine. We will leave the first field empty so that our engine searches the whole web. Then we will give a name to this engine, macroSearch, and define that only news sources in English should be returned. For information on setting up a custom search engine, please refer to: cse


This engine uses topical searches using Schema.org. We use the following 4 schema: NewsArticle, FinancialService, Blog and BusinessEntityType. Schemas are explained in this article


After the above setup, click the create button. After a few seconds you will be presented with 3 choices: Get Code, Publish url and Control Panel. Select Control Panel.


This interface allows further customization: we will contextualize the search with various search keywords, such as: 'finance' 'economics' 'macroeconomics' 'volatility' 'risk'. This will help our search engine to narrow the universe to financial news.


Custom search interface


We are almost done. We need the ID of our customized search engine, macroSearch, and a Google API token. The ID can be retrieved by clicking in the button Search engine ID (see image above). The Google API token requires you to setup a trial account on Cloud computing platform.


The code below takes the sorted keywords, the shocks and a customsearch service and returns the url links, ordered by importance according to the user’s portfolio:


def prepare_custom_search(keywords, shocks, service, cse_id, **kwargs):
    priority_links= OrderedDict()
    for key in keywords:
        search_terms = shocks[key][2]
        search_term = ' '.join(search_terms)
        search_term = 'macroSearch:%s' % search_term
        res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
        links = []
        if 'items' in res.keys():
            for i in res['items']:
                links.append(i['link'])
        priority_links[key] = links
    return priority_links


Some of the returned links are presented below:


Priority reading:


1)www.nytimes.com/2017/01/04/us/politics/transition-briefing-trump-us-intelligence.html
2)www.cnbc.com/2017/01/03/trump-blasts-general-motors-make-chevy-cruze-model-in-us-or-pay-big-border-tax.html
3)www.marketwatch.com/story/donald-trump-would-break-with-tradition-if-the-us-avoids-a-recession-in-the-next-4-years-2017-01-03
4)www.cnbc.com/2017/01/03/gm-fires-back-at-trump-most-of-our-chevy-cruzes-are-built-in-the-us.html
5)www.washingtonpost.com/powerpost/donald-trump-meet-your-toughest-hurdle-the-us-senate/2017/01/03/43f348a4-d12c-11e6-a783-cd3fa950f2fd_story.html
6)feeds.feedblitz.com//252851302/0/usatoday-newstopstoriesHow-Trump-can-stop-North-Koreas-nuclear-threats-against-the-US/
7)www.msn.com/en-us/news/politics/trump-expected-to-pick-robert-lighthizer-as-us-trade-representative/ar-BBxPr9h?li=BBnbcA1
8)www.theguardian.com/world/2017/jan/03/trump-says-us-safe-from-north-korean-nuclear-strike-no-thanks-to-china
9)www.cnn.com/2017/01/02/politics/donald-trump-us-global-politics/
10)www.washingtonexaminer.com/trump-picks-robert-lighthizer-as-us-trade-representative/article/2610729


Oil is the second macro exposure on this portfolio:


1)www.cnbc.com/2017/01/02/opec-regains-relevance-as-oil-cuts-to-spur-backwardation-analyst.html
2)www.marketwatch.com/story/oil-prices-rise-on-signs-opec-members-will-stick-to-output-pledges-2017-01-04
3)www.cnbc.com/2017/01/02/oil-prices-rise-as-markets-eye-opec-non-opec-production-cuts.html
4)www.marketwatch.com/story/crude-oil-rallies-to-18-month-high-as-opec-output-deal-kicks-in-2017-01-03
5)globalnews.ca/news/3157104/oil-prices-hit-18-month-high-as-opec-output-deal-kicks-in
6)seekingalpha.com/article/4033832-opec-dismisses-american-shale-oil
7)www.thenational.ae/business/energy/oil-jumps-as-riyadh-confirms-need-to-apply-opec-cuts-deal
8)seekingalpha.com/article/4033868-opec-spare-capacity-will-calm-oil-markets-2017
9)www.dailymail.co.uk/wires/reuters/article-4086758/Kuwait-Petroleum-Corp-committed-OPEC-oil-output-cut-state-news-agency.html
10)seekingalpha.com/article/4034005-soaring-libya-oil-production-throwing-wrench-opec-deal


And finally Europe:


1)www.wsj.com/articles/u-s-europe-spat-over-bank-risk-set-to-drag-on-1483531585
2)www.straitstimes.com/world/europe/paris-to-woo-british-finance-workers
3)www.wsj.com/articles/stocks-slip-lower-in-europe-1483346751
4)www.cnbc.com/2017/01/03/uk-banks-investigate-move-to-mainland-europe-as-brexit-back-up-plan.html
5)www.marketwatch.com/story/as-euro-implodes-europe-needs-more-leaders-like-hans-tietmeyer-2017-01-03
6)www.weeklystandard.com/obama-in-europe-id-probably-be-considered-right-in-the-middle-maybe-center-left-maybe-center-right/article/752711
7)www.business-standard.com/article/international/a-broadway-musical-s-lessons-for-europe-117010301349_1.html
8)seekingalpha.com/article/4034111-one-small-important-view-dollars-europe
9)www.thisismoney.co.uk/money/investing/article-4059112/The-Europe-Japan-China-invest-2017.html
10)www.newsmax.com/Finance/MohamedElErian/broadway-musical-hamilton-europe/2017/01/03/id/766497


And we are done. With a few lines of code we created a smart news search, tailored to our own portfolio. For more information on our API look at: www.everysk.com/api or send us a note to api@everysk.com to request your API key. Refer to the full code for this post: custom_search.py

Posted: -



We are pleased to announce the integration of Blueleaf into Everysk Dashboards. Now registered investment advisors (RIAs) can seamlessly import their client’s portfolios in order to generate insightful and dynamic portfolio reports. Everysk Dashboards will preserve and organize all the communications for regulatory and review purposes.


In order to import a client’s portfolio, you should enter the loader interface by clicking in the button below:



Then, on the bottom left corner click on load:



You will have a choice of source: either Everysk’s free samples or Blueleaf. Select Blueleaf:



Paste your Blueleaf API token:



You will automatically see a list with all your client’s accounts. Select Kevin Anderson, for example:


All client accounts are available


Everysk Dashboards will show all the tickers and quantities before actually creating the portfolio. Furthermore, we will assign the various accounts for that household in a separate, optional column called Aggregation Labels. This aggregation will enable us to provide RIAs with granular reports on each account and their contribution to the client’s overall investments:



Finally the portfolio is created, i.e. positions and quantities are mapped:


Client positions are mapped


From here you will have literally hundreds of insightful reports at your disposal. If you are a RIA and would like to try Dashboard’s functionality, please contact us at: sales@everysk.com. In order to use Blueleaf’s API, please contact our partners at api@blueleaf.com.