Sunday, 19 July 2015

Quantopian Algorithmic Trading Strategy: Portfolio allocation, Sell high, Buy low

This below algorithm should trade with the portfolio in the earlier post. In this situation we have $1 000 000 invested and no single stock has more than $350 000 invested in it. This is a trading guard as it would otherwise indicate a riskier portfolio. There is also a trailing stop at 20%. Our target is to have rather equal weights in all the stocks, and sell when it hits a maximum and go long when it reaches minimum. The maximum and minimum is determined by refreshing once a day to find the highest/lowest price in the last 7 trading days.

def initialize(context):
    set_benchmark(context.stocks)
    context.stocks = symbols(‘ANZ’, ‘MFG’, ‘NAB’,‘MFG’, ‘NAB’, ‘WBC’, ‘PNC’, ‘FLT’, ‘AGI’, ‘NCK’, ‘TRS’, ‘DSH’, ‘SOL’, ‘TLS’, ‘CCP’, ‘WOW’, ‘S32’, ‘JHC’, ‘CSL', 'NAN', 'SOM', 'SMX', 'SMA', 'MYOB', 'EPD', 'MLB')
    context.bet_amount = 1000000
    context.long = 0
    set_max_position_size(max_notional = 350000)
    context.stop_price = 0

    context.stop_pct = 0.2
 
def handle_data(context, data):
    set_trailing_stop(context, data)
         if data[context.stock].price < context.stop_price:
               order_target(context.stock, 0)

               context.stop_price = 0
    record(price=data[context.stock].price, stop=context.stop_price)

    order_target_percent(context.stocks[0], .05)
    order_target_percent(context.stocks[1], .05)
    order_target_percent(context.stocks[2], .05)
    order_target_percent(context.stocks[3], .05)
    order_target_percent(context.stocks[4], .05)
    order_target_percent(context.stocks[5], .05)
    order_target_percent(context.stocks[6], .05)
    order_target_percent(context.stocks[7], .10)
    order_target_percent(context.stocks[8], .10)
    order_target_percent(context.stocks[9], .05)
    order_target_percent(context.stocks[10], .05)
    order_target_percent(context.stocks[11], .05)
    order_target_percent(context.stocks[13], .05)
    order_target_percent(context.stocks[14], .05)
    order_target_percent(context.stocks[15], .05)
    order_target_percent(context.stocks[16], .05)
    order_target_percent(context.stocks[17], .05)
    order_target_percent(context.stocks[18], .05)

    pv = float(context.portfolio.portfolio_value)
    portfolio_allocations = []
    for stock in context.stocks:
        pos = context.portfolio.positions[stock]
        portfolio_allocations.append(
            pos.last_sale_price * pos.amount / pv * 100
        )

    record(perc_stock_0=portfolio_allocations[0],
        perc_stock_1=portfolio_allocations[1],
        perc_stock_2=portfolio_allocations[2],
        perc_stock_3=portfolio_allocations[3],
        perc_stock_4=portfolio_allocations[4],
        perc_stock_5=portfolio_allocations[5],
        perc_stock_6=portfolio_allocations[6],
        perc_stock_7=portfolio_allocations[7],
        perc_stock_8=portfolio_allocations[8],
        perc_stock_9=portfolio_allocations[9],
        perc_stock_10=portfolio_allocations[10],
        perc_stock_11=portfolio_allocations[11],
        perc_stock_12=portfolio_allocations[12],
        perc_stock_13=portfolio_allocations[13],
        perc_stock_14=portfolio_allocations[14],
        perc_stock_15=portfolio_allocations[15],
        perc_stock_16=portfolio_allocations[16],
        perc_stock_17=portfolio_allocations[17],
        perc_stock_18=portfolio_allocations[18])

def set_trailing_stop(context, data):
    if context.portfolio.positions[context.stock].amount:
        price = data[context.stock].price
        context.stop_price = max(context.stop_price, context.stop_pct * price)

def handle_data(context, data):
    rval = minmax(data)
    if rval is None:
        return
    maximums, minimums = rval
    for stock in context.stocks:
        current_max = maximums[stock]
        current_min = minimums[stock]
        current_price = data[stock].price
        current_position = context.portfolio.positions[stock]
        order_direction = calculate_direction(stock, current_min, current_max, current_price, current_position)
        order_amount = calculate_order_amount(context, stock, order_direction, current_price)
    order(stock, order_amount)

def calculate_direction(stock, current_min, current_max, current_price, current_position):
    if current_max is not None and current_position.amount <= 0 and current_price >= current_max:
        return -1
    elif current_min is not None and current_position.amount >= 0 and current_price <= current_min:
        return 1
    else
        return 0

def calculate_order_amount(context, stock, signal_val, current_price):
    current_amount = context.portfolio.positions[stock].amount
    abs_order_amount = int(context.bet_amount / current_price)
    if signal_val == -1:
        return (-1 * abs_order_amount) – current_amount
    elif signal_val == 1:
        return (1 * abs_order_amount) – current_amount
    else:
        return 0

@batch_transform(refresh_period = 1, window_length = 7)
def minmax(datapanel):
    prices_df = datapanel[‘price’]
    min_price = prices_df.min()
    max_price = prices_df.max()
    if min_price is not None and max_price is not None:
        return (max_price, min_price)
    else:
        return None

Growth Portfolio: Financials (PNC, ANZ, MFG, NAB, WBC)

Pioneer Credit

Valuation

Market Price: $1.73
Current Value ~ $2
Future Value FY1: ~ $2.25
Future Value FY2: ~ $2.30

Business
Pioneer is an Australian financial services provider, specialising in acquiring and servicing unsecured retail debt portfolios. Customers are in financial difficulty, mainly due to major life events such as unemployment, marriage breakdowns or significant health issues. PNC's debt purchases focus predominantly on credit card and personal loan accounts that are usually more than 180 days overdue.

Analysis

A positive catalyst based on their recent announcement that Pioneer Credit had signed a forward flow agreement with a major bank failed to be impounded into the stock price. By securing the forward flow agreement, the company has fulfilled customer acquisition expectations that supported its FY15 forecast outlined in their IPO prospectus. As a result of this agreement, Pioneer has agreements locked with three of the Big 4 Australian banks as well as a variety of smaller lending institutions This will support long term sustainable earnings growth as debt purchases increase. Forward flow agreements from debt sellers as well as its unique business model will drive profits over the next few years, particularly as its funding is established and ease of strategy execution. The fact the announcement failed to be supported in share price rises is surprising given the fact their share price dropped from $2 in March to a low of $1.45 in May. Analyst forecasts also expect EPS to be 14.6cents, making a PE multiple of 15.4 based on their 12 month price target of $2.25. Such expectations are in line with Managing Director’s confirmation that they were on track to achieve a net profit of $6.6 million this financial year. Because it will deliver EPS growth of 36.6% in FY15, it has high room for growth as it is trading at a high discount to its target.

Key Risks

Based on historical performance, 85% of debt purchased by PNC was from one financial group. If this client’s forward flow agreement were gone, supply of debt and hence earnings growth would drastically reduce. However, its new clients provide effective diversification and reduce risk. Nevertheless, availability of debt to purchase for its portfolio is highly dependent on the bank’s potential and agreement to sell to PNC, hence the need for forward flow agreements. This risk is increased due to increased competition which would pressure margins. Fortunately PNC has indicated its strategy includes broadening its product and service offerings. The increase in CAPEX would spur long term performance. However, investments would come at higher costs in the future given heavier regulations and higher compliance costs in the regulatory environment. There is limited information regarding implications of company strategy, for instance, limited understanding of whether their asset purchases which increase market share would hamper future performance.


ANZ

Valuation

Market Price: $32.25
Current Value ~ $37
Future Value FY1: ~ $36
Future Value FY2: ~ $38

Business

Australia and New Zealand Banking Group operates in Banking and Financial services and serves approximately 10 million global customers on retail, business and corporate clientele levels. The company operates in 33 countries across Asia Pacific, Europe, Dubai, USA and Asia. Australian operations make up the largest part of ANZ's business, dominating with commercial and retail banking lines. Operations extend across the Asia Pacific, Europe, Dubai, USA and Asia. Their strategy involves growing its Asian Pacific operational presence until 25-30% of earnings are sourced from the non-core APEA region by 2017.

Analysis

In the first half of financial year 15, cash profits rose by 5% and statutory profits rose by 3%. Flexible and accommodating credit conditions are highlighted through ANZ’s record low 0.19% loan impairment relative to total loans. Provisions likewise dropped below their 25-year average to 0.47% of assets. However in the long term earnings will suffer once such provisions and bad debts revert back to historical means. These expenses cannot fall much further, indicating banks have reached their peak of cyclical profitability. Their peak was strengthened by the favorable economic climate and strong property prices. Concerns over bubbles imply increased regulatory capital requirements, especially as the average financial leverage for Australian banks is relatively high compared to international banks at 17x. ANZ’s financial leverage ratio sits lower at 16.5x.  However, its Tier 1 Common Equity ratio (which ensures banks have a buffer to access funding in financial crises) has decreased by 0.1% to 8.7% of risk-weighted assets, 0.2% below its 9% goal. NAB and Westpac have already increased their ratio due to anticipation of APRA’s increased capital regulations.  Reports indicate Australian banks must boost their capital ratios by an average of 1.4% to be on par with the top global quartile with regards to capital. Regulatory changes combined with a slowdown in economic growth and rising interest margin pressures from competitive forces means ANZ must outperform in their operations. They are experiencing increased market share from their expansion in the Asia Pacific, where deposits and loans are growing. ANZ reaps benefits from large market cap and reputation in the wholesale deposit and funding markets and its operations in Australia’s secure socio-legal environment, as it ensures raising funds at cost effective prices. Its super regional strategy has so far been effective as profits from Asia Pacific represent 25% of total group earnings, and international and institutional banking (IIB) profits are increasing. Interim dividends were 4% higher than the first half of financial year 14 at $0.86.


Key risks

ANZ has experienced slow progress in their super regional strategy in creating an Asia Pacific connected bank. They are effectively diversifying group earnings by capitalizing on the international shift in focus on Asian emerging economies, though key risks include increased competition from global banks, slowing of Asia’s economic growth (compounded by Chinese equity market bubble and crash) and returns have rarely historically been over the cost of capital. Lesser provisions also increases risk in an economic downturn, especially as reversion in impairment depends on cyclical economic factors such as low unemployment and interest rates which maintain quality credit conditions. Such reductions in boosting earnings cannot be sustainable meaning operational revenues must grow and the company must drive cost efficiencies in their regional strategy. However it is unlikely there will be rate hikes over the next FY.

MFG:

Valuation

Market Price: $17.40
Current Value ~ $19
Future Value FY1: ~ $17
Future Value FY2: ~ $22

Business

Magellan Financial Group is a Sydney based specialist investment management business. Their asset management business line offers global equities and infrastructure investment funds for high net worth, retail and institutional investors in Australia and New Zealand.

Analysis

Their performance fee revenue of $33 million is a substantial increase of 1623% from last FY results, which drove revenues to increase by 91% to $128 million. This boosted NPAT margins to $77 million, up by 115%. Considering only 35% of total funds in management is subject to performance fees, there is room to build on this revenue growth. Funds in asset management increased from $23.4 to $31.6 billion due to growth in US (accounts for 25%) and UK (accounts for 49%) institutional clients. Australia accounts for 16%. Future growth is determined by the performance of funds in management, though based on 3 and 5-year historical performance, Magellan funds performed in the top quartile relative to competitors. Leverage also rises as there is a higher ratio of fixed costs relative to variable, and there is limited capital in their operational model. This will spur profit margins. Retail investors reap higher margins in management fees, though retail investors only account for 27%. Magellan Global Equities (MGE) is essentially a duplicate of their main retail fund though offers a catalyst in terms of extending retail distribution over fund platforms used by investment advisors, enabling self-investors convenient access to funds. Positively, growth in their distribution team will ensure higher retail sales, helped by the increase in net assets by 113% to $74 million. Moreover, they have been increasing self-managed super funds to international shares, which have appealed to clients. In Australia the minimum legislative requirement on super is set to rise from 9.5% to 12% by 2019. Their successful operations in London where over 90 clients have provided funds can easily be replicated in the US with its new management team. Their recent platform integration with AMP and Westpac for funds management will strengthen Magellan’s relations and reputation with investment advisors in Australia. However, 54% of funds are invested internationally without hedging against exposure to depreciation. Presently record low interest rates from quantitative easing in Europe, Asian and Americas from slowing economic growth spur net inflows for stocks due to the relatively lower returns in fixed income such as bonds and cash. Their business is likely to expand with such inflows in the long term as it is widely expected such rates will stay low.


Key Risks

The key risk involves effects on performance from stability in global equity markets and interest rates. In FY15 there has been increased allocations towards the cash asset type (weighted average of 11% compared to post GFC weighted average of 4%) due to recent global market instability and worries over interest rates. Performance risk is emphasised for Magellan due to relatively higher institutional mandates, which encompass a higher number of retail clients who will withdraw funds in times of poor investment returns. Currently, fund managers typicaly allocate 30% of self managed super fund capital to international shares, however Magellan has less than 0.5% in this asset type. Whilst this mitigates risk of global instability, it must increase substantially to ensure sufficient retirement capital.

NAB

Valuation

Market Price: $33.78
Current Value ~ $36
Future Value FY1: ~ $36
Future Value FY2: ~ $39

Business

National Australia Bank (NAB) is one of the four largest financial institutions in Australia in terms of market capitalisation and customers. They operate in Banking and Financial services. Their provision of products and services is mainly for Australian customers though their operations extend to Asia, UK, US and New Zealand. The group has multiple brands to market various products to different segments. Globally, their corporate business falls under National Australia Bank. In Australia, brands include NAB and UBank for banking, MLC for wealth management and insurance.

Analysis

NAB also reaps benefits from large market cap and reputation in the wholesale deposit and funding markets and its operations in Australia’s secure socio-legal environment, as it ensures raising funds at cost effective prices. Like all banks, it has reached the peak of cyclical profitability due to historically low bad debts expense (loan impairment charges at 0.18% of loans and provisions are 0.39% of assets, much lower than historical average) and the high likelihood of increased capital requirements and competitive pressures. Increased bad debts and provisions is strongly correlated with decreased returns. As bad debts cannot feasibly decrease further, the focus is on banking income to increase dividends and satisfy shareholder expectations, given its final 99c dividend was unchanged from prior FY. Interest margins are under pressure, with a group contraction of 1 basis point from FY14 due to lower earnings from assets, however NAB offset this by increasing statutory profits by 20.4% and cash earnings increased by 5.4% compared to the previous first half of FY14. 14% of earnings increase was attributed to loan impairments expense, though NAB’s main banking business in Australia increased cash earnings by 4%, largely driven by revenue growth from increased lending to households and businesses. Moreover, NAB combats regulatory risk by providing $5.5bn capital via a 2 for 25 pro rata accelerated renounceable entitlement offer to UK franchises to guard against losses, as they are exposed to macro trends in the UK, particularly with regards to commercial property. This means shareholders will have the right to purchase 2 shares for every 25 they own at $28.50 each. As expected with rights issues, EPS is falls by 4.5% and Return on Equity falls by 1.4%. If losses from compliance to regulations extend beyond the minimum required by the UK’s Prudential Regulatory Authority, the proportionate amount of increase will boost NAB’s CET1 ratio. This implies higher regulatory capital allocations pressures profit margins though reduces risk, supporting the relatively low required returns for the Australian Big 4 banks. NAB’s latest CET1 ratio is 8.87%, an increase from last FY though shows potential for improvement from the rights issue, particularly as its target range is 8.75%-9.25%. Increases in the CET1 ratio will also be driven by NAB’s divestment of underperforming British subsidiary Clydesdale, exit of its Great Western stake and UK commercial real estate. Its demerged asset of 70-80% of Clydesdale to shareholders, sold via IPO to institutional clients will list on the LSE, allowing increased focus on profitable segments such as Australian banking and wealth management lines.  Risk reduction is good news as Australian banks have high leverage relative to international banks, with NAB at 19.5x leverage (Australian mean 17x).

Key Risks

NAB has a large 33% sector exposure to emerging recovery in business lending. Previous key drivers of banking credit growth and real estate investor loans is likely to hit its peak due to the upcoming stricter regulatory environment. With low interest rates and the Australian dollar set to hit US65c, there will be less pressure in the business sectors of the economy and hence boost business lending. As common across the banking sector, there will be a reversion of impairment and provisions, though slow credit growth means this risk is not a large one. Impairment risks are further offset through low corporate leverage, attractive asset prices due to sustained low interest rates and global liquidity and minimal exposure to the slowdown in the mining sector in Australia.

WBC

Valuation

Market Price: $34
Current Value ~ $34
Future Value FY1: ~ $35
Future Value FY2: ~ $37

Business

WBC is one of the Big 4 Australian banks that provides financial services. Westpac has Australia’s largest branch network in terms of branches and ATMs. It is the second largest Australian bank by assets, and second largest bank in NZ.  Global finance capitals also host its offices including London, New York, Singapore and HK.

Analysis

Westpac’s strengths include its strong domestic network, conservative lending amounts, high liquidity and scale as well as strong interest margins. It is also reaching the peak of cyclical earnings given low interest rates and record low bad debts and provisions. Strong credit conditions meant impairment charges were only 0.11% of loans, and provisions accounted for 0.45% of total assets, much lower than historical means. Low interest rates will continue to ensure credit quality and credit growth in the medium term. However, banks are leveraged to cyclical conditions, which will remain subdued. The risk of unexpected downturns where unemployment increases and businesses fail, particularly in key cities such as Sydney and Melbourne (majority of home loans on the Big 4’s balance sheets), is unlikely. Its leverage is at 16.1x, which is lower than Australia’s mean of 17x. Westpac mitigates future regulatory risk where there will be increased capital requirements- the company will use an underwritten dividend reinvestment plan at 1.5% discount to raise approximately $2 billion of capital to shift its CET1 ratio towards the higher end of their target spectrum. Their CET1 ratio is recently at 8.76%, lower compared to FY14. Its recent financial results for first half FY15 was below expectations by 12%- profit remained flat with only a 2% increase in cash earnings. There was also a methodology change relating to adjusting a derivative valuation, which decreased non-interest income by 4%. Net interest revenues increased 5% due to a 3% increase in interest earning assets and their interest margin holding at 2.01%. Household debt being over 150% of disposable incomes means credit does not hold expansion potential. However, their 60% investment in BY Investment Management offers a catalyst based on growth in superannuation funds.



Sunday, 12 July 2015

Shanghai Sell-off

The situation unfolds as follows:
§  China attempted to slow its 2014 property boom though it slowed too quickly, resulting in the government injecting liquidity and credit into the stock market, rather than the property market.
§  Shanghai Composite Index doubled from December 2014 to June 2015.
§  Since peaking mid-June, over the past three weeks, its two main exchanges lost more than a quarter of their value. Shanghai Composite fell 25 percent despite having rose more than 80 percent over 2014.
§  This was triggered by concerns regarding overvaluation and unwinding of margin trading. Since China does not have a full capital market to support the economy, their reliance on debt financing proved excessive especially in the investment-led property sector.
§  Measures to prevent further sell off include: 73 percent of mainland shares and shareholders with more than 5 percent stake suspended from selling – in the latter case for the next six months, IPOs halted in case they diverted investments from normal sharemarket activity and boost liquidity, a stabilisation fund established by the top brokers. Brokers also pledged to purchase $19 billion worth of shares. Beijing furthermore eased regulations surrounding investments in blue chips and raised margin requirements for shorting shares with small market capitalisation.
§  Chinese economy expected to stabilise at 6.5-7 percent growth.

Buying opportunity
US institutional investors were not involved in the sell off, and there is little evidence of correlation between US stock movements and the Chinese selling. It is true that the government inflated prices present uncertainty although the government’s actions are similar to the Fed and ECB actions to inflate asset prices. With this logic Chinese markets are bound to go higher, with the government protecting against systematic risks. This was the case late Thursday as Chinese markets slowed their downturn partly in response to measures such as People’s Bank of China extending 260 billion yuan to brokers promoting margin lending, promoting interbank lending between the banks and the nation’s margin lender, and allowing banks to renegotiate maturities. 

Furthermore the downturn in the markets facilitates the reduction of interest rates via the Reserve Requirement Ratio (RRR) by the central bank, which in turn boosts consumption and investment, and the completion of infrastructure projects. Property shares such as China Vanke and Poly Real Estate grew the daily maximum amount of 10 percent. Demand for steel and hence iron ore should hence increase. 

The Chinese sharemarket does not play a central role as an indicator of economic health, unlike other overseas equity markets, as equities do not account for as significant part of household balance sheets. Neighbouring Asian markets also experience for 10-12% of direct sales exposure to China so the impact of contagion is minimal. 

On the other hand…
However the more resources committed to supporting the market, the more potential for fall out risks should a collapse continue. This is the case especially for China as the market is relatively expensive and desire to sell prevalent. By offering to essentially be the buyer this only encourages sales. This spreads loss of confidence in the government’s ability to support both the sharemarket and economy. In the short term furthermore the prices of iron ore, Australia’s largest physical export, are down 25 percent with high correlation to the 28 percent fall in the Shanghai Index. Our terms of trade are affected from these low prices despite minimal effect on China’s real economy. Overall inflated P/E ratios will reduce to reflect more intrinsic values. 

SSEC July 27 update

References:
CNBC, Australian Financial Review, Business Insider

Friday, 10 July 2015

The Crisis Greece had to have

On a more positive note, the Greek debt crisis perhaps can facilitate the realisation that there should be economic reforms for regrowth. Limited credit, supply shortages and soon-to-be hyperinflation reduces purchasing power though in the post crisis state, if the Greek output takes advantage of cheap labour and depreciation and becomes competitive, recovery can be experienced over a medium term. Meanwhile, the integrity of the Euro should improve once the EU establishes formal funding and exit rules given that Greece’s loans have been at low interest. Otherwise, other debt laden economies in the EU may cause the EU to disintegrate. Whether this is actually a positive thing in the long term comes back to the foundations on which the EU was built.

Despite there being few direct economic links between Australia and Greece, our currency should feel pressure to appreciate from investors seeking safe haven currencies. This presents a problem for the RBA given their present focus on currency depreciation through expansionary monetary policy, and further cuts (predicted at 25 basis points in August, before the RBA publishes the next set of growth forecasts) may aggravate the housing bubble through cheaper loans. This increases the risk of the collapse as furthermore the big four Australian banks source wholesale funding from the Eurozone which fuels our property purchases. However, as discussed later, it is the Chinese market that Australia should prioritise as a concern. 

Investors are playing down their fears. Firstly, the risk that their default spreads beyond the EU is minimised by the fact that the debt is only 10% in the private sector and the European banks’ holdings of Greek assets are 80% less from their peak. The remainder of the debt are held by the IMF, ECB and governments, which are in better positions to absorb losses. Such disconnection from the financial markets stems from the restructuring of debt from 2012 where it was previously held by overseas investors.

Secondly, Outright Monetary Transactions, which involve the purchase of debt of vulnerable economies by the European Central Bank, has recently been ruled as legal. Furthermore their €60 billion per month bond purchase stimulus launched in March 2015 has guaranteed consistent demand for their debt. With the central bank playing such an active role in limiting bond market contagion from Greece, investors are more confident about the ability of the EU to protect itself. Greece accounts for 2% of the entire bloc’s output and growth has returned to the nations previously affected by the debt crisis.

Because of this, Sunday’s final round of bailout negotiations should determine whether the financial market contagion will shift towards a political one.

References:
Wall Street Journal, Altair Asset Management, Financial Review

Thursday, 2 July 2015

Quantopian Algorithmic Trading Strategy: Mean Reversion

Mean reversion is a tendency for a stochastic process to remain near, or tend to return over time to a long-run average value. Interest rates and implied volatilities tend to exhibit mean reversion

The following algorithm chooses a basket of high volume securities and ranks them on the basis of 5 day returns. Stocks with the top 20% highest returns are shorted and the algo goes long in bottom 20% stocks with the lowest returns. The investment thesis behind this strategy is that the previously high performing stocks from the previous week will worsen in performance this week, whilst the lowest performing stocks from the previous week will deliver in performance. 

import numpy as np

def initialize(context):
    set_universe(universe.DollarVolumeUniverse(99, 100)
    set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))
    set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.10))
    context.long_leverage = 0.5
    context.short_leverage = -0.5
    context.lower_percentile = 20
    context.upper_percentile = 80
    context.returns_lookback = 5


We firstly import the Python libraries we use in the algorithm. Defining the initialise function will set the stocks used in trading and establish parameters. Context refers to an empty Python dictionary, augmented so properties can be accessed via dot and bracket. In this case, we use the top 1% of stocks based on their average trading volume per day. For live trading, we assume a a $0.0075 per share commission cost with a $1 minimum cost per trade. Market impact assumptions are also defined, the algo limits trading up to 0.025 of the traded volume for any given minute, and price impact is 0.1. I will be experimenting with slippage where there is additional flexibility for each stock's spread in my next post. We specify going short in the top 20% of stocks with highest returns from their previous 5 day returns. 

    schedule_function(rebalance, 
                      date_rules.week_start(days_offset=0),
                      time_rules.market_open(hours = 1, minutes = 00))  

def handle_data(context,data):    
    record(leverage = context.account.leverage)
    longs = shorts = 0
    for position in context.portfolio.positions.itervalues():
        if position.amount > 0:
            longs += 1
        if position.amount < 0:
            shorts += 1
    record(long_count=longs, short_count=shorts)

The schedule function specifies the portfolio is rebalanced every Monday an hour after markets open (no significant difference found in this timing). Handle_data is called whenever there is a market event that occurs for any of the algorithm's specified stocks. Context and data represent parameters. We monitor and record portfolio leverage, and number of long and short positions. The for loop ensures that the counts of long and short positions are added to the plot based on position sizes. 

def rebalance(context,data):
    prices = history(context.returns_lookback, '1d', 'price')
    returns = (prices.iloc[-1] - prices.iloc[0]) / prices.iloc[0]
    returns = returns.dropna()
    open_orders = get_open_orders()
    if open_orders:
        eligible_secs = [sec for sec in data if sec not in open_orders]
        returns = returns[eligible_secs]
    lower, upper = np.percentile(returns, [context.lower_percentile,
                                           context.upper_percentile])
    long_secs = returns[returns <= lower]
    short_secs = returns[returns >= upper]
    long_weight = context.long_leverage / len(long_secs)
    short_weight = context.short_leverage / len(short_secs)
        if security in long_secs:
            order_target_percent(security, long_weight) 
        elif security in short_secs:
            order_target_percent(security, short_weight)
        else:
            order_target(security, 0)
            
    log.info("This week's longs: "+", ".join([long_.symbol for long_ in long_secs.index]))
    log.info("This week's shorts: "  +", ".join([short_.symbol for short_ in short_secs.index]))

Returns are calculated for the past 5 days based on prices. The algorithm drops stocks where prices are not available and removes stocks that are still in open orders. Cut-offs are defined in terms of return percentiles. We select the stocks based on their performance to go long and short in, then allocate even weights in each long short position. The if, elif and else statement instructs buying/selling of securities depending on their returns, or otherwise close the position. The log shows the securities in each long and short portfolio for each week. 



Holding all other variables constant while changing the lower and upper percentile to 5 and 95% respectively yields a higher return of 8.5% compared to 2.9%. 


Key terms

Alpha: The excess return relative to the return of the benchmark index is a fund's alpha.

Beta: A measure of the volatility, or systematic risk, of a security or a portfolio in comparison to the market as a whole. 

Sharpe ratio: The Sharpe ratio is the average return earned in excess of the risk-free rate per unit of volatility or total risk. Simply put, it is the risk adjusted return. 

Sortino: A modification of the Sharpe ratio that differentiates harmful volatility from general volatility by taking into account the standard deviation of negative asset returns, called downside deviation. The Sortino ratio subtracts the risk-free rate of return from the portfolio’s return, and then divides that by the downside deviation. A large Sortino ratio indicates there is a low probability of a large loss. 


Information Ratio: A ratio of portfolio returns above the returns of a benchmark (usually an index) to the volatility of those returns. The information ratio (IR) measures a portfolio manager's ability to generate excess returns relative to a benchmark, but also attempts to identify the consistency of the investor. This ratio will identify if a manager has beaten the benchmark by a lot in a few months or a little every month. The higher the IR the more consistent a manager is and consistency is an ideal trait.

Max drawdown: An indicator of the risk of a portfolio chosen based on a certain strategy. It measures the largest single drop from peak to bottom in the value of a portfolio (before a new peak is achieved).



Wednesday, 1 July 2015

Grexit: The Default Situation

Greece's debt burden stands at 180 percent of their GDP, and rather than depending on a 30 percent write down on their debt, it seems its creditors - that being the IMF, ECB and European Commission - are more willing to negotiate maturity extensions and interest rate cuts. 

The probability of Grexit occurring has therefore risen extensively with the declaration of a six day bank holiday after creditor negotiations broke down over the weekend. Although it can be avoided if the citizens vote to accept the bailout terms offered by the EU and the IMF on the July 5 referendum. These terms include raising taxes and cutting pensions to pay off debt. However even so it is still possible Greece will return to the drachma, the most reasonable means in which the banks can reopen and avoid a malfunctioning banking system. Alex Tsipras, the nation’s prime minister, had accused the EU of blackmailing Greece in their endeavour to undermine democracy and this only pressures the Greeks to vote no.
This meant the EU stops its current bailout scheme on June 30, thereby causing the European Central Bank to limit the amount of emergency liquidity that Greece’s central bank can pass onto its lenders. It seems that Tsipras is resorting to the Greek people’s pride though it will be essentially what they think they are voting for that counts. If there is a belief that voting no equates to quitting the EU, they will most likely vote yes. However if they believe that the referendum is based solely on whether they accept the creditor’s terms, a “no” vote will be more likely. Tsipras therefore is arguing that rejecting the creditor’s terms will not lead to Grexit.
It seems therefore he is relying on the pressure of a vote against to negotiate for a more favourable deal with the creditors. However it will be difficult to maintain such hopes as by June 30 the IMF still will not receive 1.6 billion euros and come July 20 the European Central Bank will not be paid either. Plus, the government’s proposal included 8 Billion Euros in additional measures, eight times the agreed amount by the previous government to creditors.  
Furthermore the banks will become insolvent as not only are they direct creditors of the government, almost half of their capital consists of deferred tax assets – an allowance for their lower taxes given their past losses. Bad debt will also rise further with the state of the economy. Therefore to raise capital, without support from the ECB, IMF or EU, a portion of deposits would be converted into new bank shares. This occurred in 2013 to sustain position in the EU in Cyprus though in Greece those affected will not be the uninsured deposits over 100 000 euros. The banking system may furthermore collapse as the state owned banks would likely introduce the 1980s style lending practices where scarce credit was allocated to repay party favours.
The implications of voting no, and therefore bringing back the drachma, would be a fall in currency to 50-60 percent of the euro, imported commodities such as petrol, and huge inflation. Even if they vote yes Greece may not stay in the EU as the creditors will not favour deals with Tsipras, instead, new elections are introduced and if the opposition wins despite their current fragmented state, creditors may be more willing to restart negotiations. Greece also has yet to allow free competition in the market; the previous bailout initiative failed to pressure them to remove red tape that discourages entrepreneurship, and the power of protected oligopolies. Without EU pressure this is sure to remain the case.
Australia’s shares suffered a $40 billion fall as a result of potential Grexit and Greece’s default, as the collapse of debt negotiations led to global sell off. Most sectors were affected with the exception of gold miners, most likely being investors seeking safe haven assets. This had the ASX200 at its lowest since January. Japan’s NKY and HK’s Hang Seng likewise both fell more than two percent. However Greece’s exit should have longer term and larger impacts on debt laden nations such as Italy and Spain.
If this threat of default had occurred earlier when the EU nations were weaker, I believe Spain and Italy would have followed. If it is a successful exit then it may provide incentive or a precedent for other debt markets to follow. If Italy now was to commence deals over its debt and those were rejected then the entire integrity of the EU will be threatened as they are the third largest economy in it. With the markets predicting a 30 percent chance of Grexit, it should have been expected that the bond yields for Italy, Spain and Portugal increased 30 basis points to isolate the rest of Europe from the fallout. German bond yields fell, as these bonds are considered safe investments during crises. Other safe havens are the Swiss Franc and British Pound, particularly as the British banks are less exposed to Greece than three years ago.
Nonetheless most markets recovered, with significant one day moves still less than the last Greece debt related crisis in 2012.
The bottom line is without the EU, Greece will experience further income inequality and poverty. I believe those who argue for the upside of Grexit on the economy are wrong, as Greece has structural failings, rather than fiscal. Geopolitical risks will also be aggravated from default and Grexit. If the electorate votes no, implications will extend towards the stability of Europe from irresponsible politicking, and a lack of skills that other governments such as France rely on. A change of currency, geopolitical reorientation and bankruptcy will only expose this. Therefore I believe a vote for the deal, followed by government change, and a focus on the cause of the crisis rather than its symptoms, is the most reasonable means to commence a slow path towards recovery.
References:
Reuters, ABC news, Wall Street Journal, Financial Review

Thursday, 9 April 2015

Macro Trends April 2015: Forecasts, Rationales, Effects


This post refers to our forecasts and justifications for six economic variables which are central to investing strategies, and reflected in future valuations. These variables include the economy, GDP growth, the exchange rate, RBA cash rate, unemployment rate, 10 year bond yield and inflation rate for Australia. Investors should remember that the share market tends to factor in perceived and forecasted economic strengthening before it happens, but less likely to acknowledge economic weakening.

Economy: short term decline over 2015, medium term growth due to depreciation

The economy is experiencing below trend growth, rising unemployment and a weak fiscal budget. This is mainly from drops in commodity prices, lack of reforms and instability in the political environment, with cuts to public investment, low business confidence and hence slow credit growth, and falling capex in mining sectors. Generally, the Australian economy needs to transition from a focus on mining capital expenditure and high commodity prices towards non mining sector, property investment and consumption, with stronger government spending on infrastructure.
The main risks to the economy are derived from the exchange rate, trade weighted index- including iron ore export prices, employment growth, consumer confidence and the timing of both fed and state infrastructure investment. The RBA cash rate seems to be mainly affecting the housing market. Consumption and investment are less interest sensitive relative to previous cyclical downturns, which plays a role in the RBA setting the cash rate to its lowest since the 1960s. Therefore I believe the RBA’s stimulus is missing the big picture of strengthening the economy’s structural and cyclical weaknesses.
Declining growth over 2015 is likely however with the depreciation of the Australian dollar to a forecasted 70-75c mark, it should accelerate growth in the medium term, especially with regards to export competitiveness.  The RBA is likely to use its policies to target the currency.

GDP growth: 2.4% over 2015 and into early 2016 from end of mining growth and absence of investment

 We forecast GDP to grow at 2.4% over the remainder of 2015 and early 2016. GDP growth was 2.5% over 2014 to the December quarter, the second consecutive quarterly contraction. Gross domestic income also declined 0.2% due to falling terms of trade. Factors driving the slowdowns include inventory declines and lack of both public and private investment, which outweighed growth in consumption and net exports. Constrained wage growth meant reduction in savings to increase consumption. Flat commodity prices and the delay in transitioning towards non mining private investments due to lack of business confidence means this underlying trend is set to continue. Mainly industrial and commercial services would benefit from this GDP growth given the fed government follows through with infrastructure spending. The financial sector is being stimulated through low bad debts expenses and increased productivity, so the GDP growth will help lending growth which is currently slowed down by low consumer and business confidence related to job security.

Exchange rate: depreciate to 70-75c due to rate hikes in US and terms of trade decline

Current depreciation is partially due to the termination of quantitative easing in the US this year, which slows down the carry trade from US dollar denominated capital markets to Australia. Carry trade refers to where investors borrow money at a lower interest rate economy, converting it to a currency in a higher interest rate country and investing it in the highest rated bonds of that country. Decline in the terms of trade and general unfavorable growth outlook will also play a role in depreciation. Nevertheless the depreciation will be at a lesser extent compared to the Euro and the Yen. Quantitative easing in Europe and Japan is causing capital to flow towards higher yielding Aussie bonds. There is also still support for the Australian dollar from Chinese investors, emphasising on our economy’s wealth profile.
The energy and transportation sector are most affected by the $A depreciation. Depreciation increases the $A value of offshore earnings and revenue denominated in $US, though also increases costs for importers where their cost base depends greatly on the overseas value chain.

RBA cash rate: drop to 2% in the next few months to promote depreciation

The current rate sits at 2.25% though we forecast a cut to 2% in the next few months. Due to the lack of fiscal stimulus and structural policy inertia, the RBA must step up to drive the depreciation of the Australian dollar whilst improving employment and economic growth. The depreciation of the Australian dollar has been trending for some time however it must fall further according to a trade weighted perspective against the US dollar. This depreciation would trigger inflation and GDP growth which reduces the need to maintain such a historically low cash rate. Industrials, consumer goods, financial and real estate sector are likely to benefit. Households who have recently been exhibiting low propensity to consume will increase their consumption. This is also the result of stimulatory interest rates which ensures low mortgage rates, with wealth generated from the property price boom. Multiplier effects flow through to all sectors. A cyclical trajectory forms as unemployment reduces, increasing earnings for real estate investment trusts.

Unemployment rate: increase to 6.5% due to discouraged jobseekers, subdued GDP growth and lack of new jobs being created by the economy

The current rate of unemployment is 6.3%, unemployment refers to those who have not worked for more than a month as a proportion of the labor force. We forecast this rate to increase 0.2% to 6.5%. Whilst in January unemployment rose 0.3% and the 6.3% in Feb and March was a decline of 0.1%, we expect employment growth to stay weak parallel to the weak GDP expectations. Participation rate which followed a declining trend line in 2014 is still being limited by discouraged jobseekers, implying the real problem is being masked by statistically measured unemployment. The economy is not creating enough new vacancies to absorb the number of new entrants into the labor market, plus a strong GDP of 3% pa is needed to support stronger employment rates. Unemployment would affect all sectors especially consumer discretionary, as the marginal propensity to spend is boosted when consumers have job security.

10 year bond yield: increase to 2.65% from QE in Japan and Europe

This yield represents the benchmark risk free rate for investor decisions. It is currently 2.48% and we forecast it to increase to 2.65%. Internationally, bond yields are being slowed by quantitative easing policies from slow economic growth, as evident in Japan and Europe. This results in capital outflow towards more attractive bonds (Australia) which will trap such countries in a cycle to lower their yields further.  This will improve our financial sector as low interest rates make bank equity more appealing due to dividend yields and earnings growth will accumulate through low lending rates.

Inflation Rate: increase to 2.5% over 2015 and 3% in 2016 from depreciation and tradeables


The current rate sits at 1.7% though 12 month forecast is an increase to 2.5%. Headline inflation fell to 1.7% from 2.3% in the last quarter of 2014. Falling petrol prices sustain inflation from other areas which is why our inflation forecast still remains well below 3%. Meanwhile underlying inflation, derived from volatility movements in commodities such as fuel, was 2.3%, driven by non-tradeables. Tradeables prices should rise in the next few months and converge with the strong pricing trend of non-tradeables due to depreciation of the Australian dollar. The depreciation is not only against the US dollar, the $A is expected to depreciate against the Chinese Yuan, increasing prices of imports from China, further generating inflationary pressures. In 2016 we therefore forecast a 3% inflation rate. Such inflation has both positive and negative impacts on consumer staples and discretionary- inflation allows cost increases to be easily passed onto consumers to maintain margins though expenditure is reduced.