Algo Trading News Headlines 9/17/2018

The who, how and why of high-frequency crypto trading

(www.bravenewcoin.com)

According to the Financial Times, several leading high-frequency trading houses, including DRW, Jump Trading, DV Trading, and Hehmeyer Trading have entered the crypto asset markets last year. Several newly-launched crypto hedge funds are also using algorithmic trading strategies to generate a return on investment for their investors.

Dutch high-frequency trading house, Flow Traders BV, also recently made a move into the crypto markets, according to Bloomberg. The Amsterdam-based company is making markets in exchange-traded notes linked to bitcoin and ether due to strong investor demand for crypto investments.

Photo by  Marc Szeglat  on  Unsplash

JP Morgan Says Severe Crisis to Arrive in 2020

(www.nasdaq.com)

The consensus is that there will be a major “liquidity crisis” with huge selloffs in major asset classes, and no one to step in to buy. The losses will be exacerbated by the shift to passive management and the rise of algorithmic trading. JP Morgan says that the Fed and other central banks may even need to directly buy stocks, and there could even be negative income taxes. The bank thinks the crisis will hit sometime after the first half of 2019, most likely in 2020.

Billionaire who once built robots to trade goes to war with them

(www.economictimes.com)

Thomas Peterffy helped launch the electronic-trading revolution that transformed the US stock market. And while the billionaire hasn’t soured on automation, he’s taking a lead role fighting back against the speediest traders. 

Interactive Brokers Group Inc. announced Wednesday that it will list its shares on an exchange run by IEXNSE 0.06 %Group Inc., which was made famous by Michael Lewis in “Flash Boys.” The 2014 book documented the market’s efforts to use a 350-microsecond speed bump to eliminate advantages IEX believed the fastest traders had in US stocks. When shares of Interactive Brokers move over from Nasdaq Inc., it will be IEX’s first win in its delayed plan to list corporations.

Quant Strategy in Emerging-Market FX Posts Best Run in Six Years

(www.bloomberg.com)

A Nomura index that mimics a trend-following strategy by chasing momentum in 10 EM currencies against the dollar has outperformed the JPMorgan Emerging Market Index by nearly 20 percentage points so far this year.

/

Algo Trading News Headlines 9/11/2018

Quant Investing: What are the dangers of the Black Box?

(www.jdsupra.com)

The strong industry consensus is that computers caused that Monday afternoon “flash crash.” Algorithmic trading, where computers automatically pick stocks based on complex pre-programmed instructions, “definitely had an impact” on the market swing that day, according to U.S. Treasury Secretary, Steve Mnuchin.

Photo by  Esther Jiao  on  Unsplash

Photo by Esther Jiao on Unsplash

Rethinking the Order Book: The March Towards Automated Markets

(www.tradersmagazine.com)

Even as the digitization of trading has evolved and blockchain changes the financial landscape, existing market models have been unimaginatively carried over to electronic asset exchanges and now crypto markets. As a result, technology gaps between traders remain economically significant while the current market design perpetuates (and in some cases exacerbates) problematic features of the former system.

Citi hires derivatives duo from rival Goldman Sachs

(www.fnlondon.com)

Citigroup has made three appointments within its electronic trading business, including two hires from rival Goldman Sachs, amid a surge in futures trading this year.

/

Algo Trading News Headlines 9/10/2018

Is a Slang programming job at Goldman Sachs a technology career-killer?

(www.efinancialcareers.com)

If you work for Goldman Sachs, Slang is more than just the signifier of an informal word or phrase: it’s the bank’s very own programming language,devised by some of its most brilliant strats over two decades ago. However, depending upon who you speak to, Slang (short for Securities Language) is also a reason why working for the firm is a) incredibly interesting or b) a very quick way of ensuring you will never work anywhere but GS ever again.

Photo by  Jennifer Burk  on  Unsplash

Machine earning: how tech is shaking up bank market-making

(www.risk.net)

This requires human traders to tell quants and technologists how they do their job, which is a tense balancing act. “Clearly, there is going to be the feeling of, ‘Well, you’re just automating everything I’m doing, so what’s in it for me?’” says Ezra Nahum at Goldman Sachs.

You want a machine learning job in finance? They might be less exciting than you think

(www.efinancialcareers.com)

For starters it isn’t actually clear what machine learning actually is. The term conjures up images of artificially intelligent cyborgs poring over streams of financial data, coming up with novel trading strategies which they then test and modify — all without any human supervision.

What Can The Crypto Robots Offer Us?

(www.fragland.net)

Cryptos trading robots utilize our free time and let us think on a passive income that is quite rewarding for a good future. On the contrary, when we are too busy with our own work, it can free up our time and invest on our behalf.

JP Morgan’s top quant warns next crisis to have flash crashes and social unrest not seen in 50 years

(www.cnbc.com)

The trillion-dollar shift to passive investments, computerized trading strategies and electronic trading desks will exacerbate sudden, severe stock drops, Kolanovic said.

/

Algo Trading News Headlines 8/31/2018

A Junior Analyst Created a Faulty Quant Model. The Penalty? $97.6 Million

(www.institutionalinvestor.com)

Investors placed billions of dollars into mutual funds and strategies that used models developed solely by an inexperienced analyst at Transamerica affiliate Aegon USA Investment Management, the SEC said in a statement Monday. The models contained numerous errors and did not work as promised, the regulator alleged.

Photo by  chuttersnap  on  Unsplash

Photo by chuttersnap on Unsplash

Quant house AQR hires UBS robo architect for top tech role

(www.fnlondon.com)

The firm has recruited Shane Williams — who helped create UBS SmartWealth, the Swiss bank’s robo-advisory business — as its new head of client technologies, according to an email Williams sent to friends and colleagues on August 27. He joined AQR in August and will be based in the US.

Finance: How to Make the Most of Machine Learning

(www.globalbankingandfinance.com)

As a subset of data science, machine learning uses specific algorithms and chosen datasets to train mathematical models to find patterns, make predictions, segmentation, and more.

Best Starting Kits for Algo Trading with C#

(alpaca.markets)

When it comes to algo trading and automated investment, Python is one of the biggest players in the space, but many experts also use .NET/C# for its high performance and robustness. As we did some research on toolset you might look at to start your algo trading, we wanted to share this list for you.

LUCRE automated trading system encourages crypto traders to Not HODL their cryptocurrency

(MENAFN.com)

LUCRE is a project with the ability to generate revenues in all kinds of market conditions through buying and selling with every good opportunity. Even in a current scenario of not so profitable crypto market, Lucre attempts to make a profit by making short-term trades through its Lucre trading Algo that runs on a Metatrader trading platform.

/

Algo Trading News Headlines 8/27/2018

Trading Places — Lines Blurred Between Traders And Programmers

(seekingalpha.com)

The recent WSJ article focused upon details from Adam Korn, a 16-year veteran at Goldman. He stated that success today depends less on trusting one’s gut, rather much of a trader’s job is embedded in the computer code or algorithms, which do much of the work now.

What is the real story though, what has all this computerized algorithmic trading truly done, how much value has it truly created? One question I would like to ask, is there a correlation between the explosion of our debt levels and this newly digitized financial age?

Photo by  Phil Botha  on  Unsplash

Photo by Phil Botha on Unsplash

Major Russian Airline Tests Blockchain in Bid to Track Fuel Payments

(www.coindesk.com)

According to S7, the application shares data about fuel demand on a shared ledger, a copy of which is managed by each of the three parties. Further, payments for the fuel can be conducted on the network, with digital invoices created via smart contract during each transaction.

Python Notebook Research to Replicate ETF Using Free Data

(alpaca.markets)

ETF is one of the great investment products in the last decade, and it has allowed so many people to gain the exposure to the wide range of assets easily at low cost. It is easy to buy a share of ETF without knowing what’s in there, but as a tech-savvy guy yourself, you may wonder how it works. By reconstructing the fund yourself, you may even come up with something better.

Trading Lesson: Don’t Touch That Dial. More to Come, Hedge Your Bets

(www.moneyshow.com)

In my 30 years as a trader, I’ve never seen a market like this. If the bots remain faithful to their programs, we are still likely to see higher stock prices over the next few weeks to months.

STEROID Launches New Automated Cryptocurrency Trading Algorithm

(www.bitcoinexchangeguide.com)

Algorithms run our online world, for the most part, a majority of everything done online is associated with an algorithm in one way or another. It only makes sense therefore that they would be used in the financial world as well. That is why STEROID has been developed, to create a functioning opportunity for traders on crypto exchanges.

Here’s how artificial intelligence can be used to beat the market

(www.cnbc.com)

CNBC’s Bob Pisani is joined by Sam Masucci, ETF Managers Group CEO, to discuss how he’s using an AI program to pick stocks.

/

Algo Trading News Headlines 8/23/2018

Barclays hires AI specialist from Goldman intrading revamp

(www.fnlondon.com)

The hire is another sign of Barclays’ intent to ensure its markets business can compete with rivals in the City and on Wall Street, which are increasingly turning to new technologies to improve performance and cut costs.

No Quant Is Safe as Global Stress Hits Risk Parity Where It Hurts

(www.bloomberg.com)

Risk-parity’s travails might test faith in the trading style over traditional allocations. It’s among the worst-performing categories tracked by JPMorgan, falling 1.2 percent this year. That compares to a 2.1 percent gain for long-short equity funds, 1.7 percent for macro funds, and 2.9 percent for balanced mutual accounts, according to data published by the U.S. bank earlier this month.

UBS trials Netflix-style algorithms for trading suggestions

(www.cnbc.com)

UBS is looking at applying recommendation algorithms to suggest trades to its asset management and hedge fund clients, similar to those used by a host of consumer technology companies.

Market makers, takers and fakers: US exchanges are losing fast

(bravenewcoin.com)

The great ETF debate rages on and there’s a lot of conjecture as to why the SEC should or shouldn’t approve one. But what needs to be addressed foremost is the immaturity and unreliability of many of the exchanges that bitcoin derives its “global spot price” from — that number now over 210 — and the obstacles they may encounter going forward.

Indicators That Could Have Made You 626% ROI During The Recent Bloodbath

(cryptodaily.co.uk)

Those indicators are the 5 EMA and 10 EMA as can be seen on the daily chart for BTC/USD. These indicators have been signaling the direction of every bullish and bearish wave throughout the correction period.

/

Algo Trading News Headlines 7/26/2018

Look Ma, No Code! Meet The IITians Who’ve Built A Code-Free Algo-Trading Platform

(inc42.com)

“Currently, almost 42% of the trade in the Indian market is done through automated algorithmic trading systems. But most of this trading activity is done by high net worth individuals (HNIs) and AIMs. We feel that the retail guys haven’t been given enough horsepower in it. So, we are trying to do just that,” says Ayush Gangwar, CEO of Kuants.

Photo by  Tra Nguyen  on  Unsplash

Photo by Tra Nguyen on Unsplash

Data, Data, Data! 11 Great Financial Data Vendors

(blog.alpaca.markets)

Whether you’re a financial firm or an individual trader, financial data is key for putting together any good strategy. With so many vendors on the market today, many good options get lost in the noise. Here are 11 great financial data vendors.

Can using Bitcoin trading robots help you earn money?

(ambcrypto.com)

With a set of pre-written codes that help in directing the Bitcoin Trading Robots take decisions on your behalf. Moreover, one can find these robots to be more intelligent in it and thus learn from the market trends as well.

New course in algorithmic trading at Saïd

(cherwell.org)

The technique works through using algorithms to replicate patterns in behaviour, and using the resulting estimates to make investment choices, removing human bias and emotion altogether.

Although algorithmic trading has been used for some time, its dominance in financial sectors is growing, and is estimated by the School to account for 20% of hedge funds.

Quant hedge funds lose their allure as performance sags

(www.ft.com)

Investor inflows to computer-powered “quantitative” hedge funds have halved this year to the most sluggish pace since 2009, after a spate of poor performance from many of the industry’s biggest players.

/

9 Great Tools for Algo Trading

In the last 5–10 years algorithmic trading, or algo trading, has gained popularity with the individual investor. The rise in popularity has been accompanied by a proliferation of tools and services, to both test and trade with algorithms. I’ve put together a list of 9 tools you should consider using for your algo trading process.

Photo by  Adrian Curiel  on  Unsplash

Photo by Adrian Curiel on Unsplash

Web Services:

The following are managed-services that you can use through web browsers, and don’t require much setup from the user. As someone who’s recently started in this field, I found it easy for new algo traders to try out.

(1) Quantopian:

1_xmqbJh3dGQIXylJTSCD7dA.png

A Boston-based crowd-sourced hedge fund, Quantopian provides an online IDE to backtest algorithms. Their platform is built with python, and all algorithms are implemented in Python. When testing algorithms, users have the option of a quick backtest, or a larger full backtest, and are provided the visual of portfolio performance.

Live-trading was discontinued in September 2017, but still provide a large range of historical data. They also have a serious community of developers, and now hold an ongoing DAILY contest with 10 winners awarded each day for a total of $5,000 per month in prize money (*updated from previously written as "periodically hold contests"). Quantopian provides capital to the winning algorithm. 

(2) QuantConnect:

1_eQopy9i2kr63RFeCFQq-sA.png

QuantConnect, is another platform that provides an IDE to both backtest and live-trade algorithmically. Their platform was built using C#, and users have the options to test algorithms in multiple languages, including both C# and Python.

QuantConnect also embraces a great community from all over the world, and provides access to equities, futures, forex and crypto trading. They offer live-trading integration with various names such as InteractiveBrokers, OANDA, and GDAX.

(3) QuantRocket:

QuantRocket is a platform that offers both backtesting and live trading with InteractiveBrokers, with live trading capabilities on forex as well as US equities. It’s specifically designed for trading with InteractiveBrokers, and sets itself apart with its flexibility.

QuantRocket supports multiple engines — its own Moonshot, as well as third party engines chosen by the user. While QuantRocket doesn’t have a traditional IDE, it is integrated well with Jupyter to produce something similar. One thing to keep in mind is that QuantRocket is not free. Pricing plans start at 19.99/month USD, with annual options.

Local Backtesting/LiveTrading Engines:

In today’s software world, you have lots more freedom if you make some effort outside of those managed-services. If you are comfortable this way, I recommend backtesting locally with these tools:

(4) Zipline/Zipline-Live:

quantopian/zipline
zipline - Zipline, a Pythonic Algorithmic Trading Librarygithub.com

Quantopian’s IDE is built on the back of Zipline, an open source backtesting engine for trading algorithms. Zipline runs locally, and can be configured to run in virtual environments and Docker containers as well. Zipline comes with all of Quantopian’s functions, but not all of its data. To balance that, users can write custom data to backtest on. Zipline also provides raw data from backtests, allowing for versatile uses of visualization.

Zipline discontinued live trading in 2017, but there is an open source project Zipline-live that works with Interactive Brokers. It has many of the same features Zipline does, and provides live trading.

(5) BackTrader:

backtrader - Backtesting / Trading
from datetime import datetime import backtrader as bt class SmaCross(bt.SignalStrategy): params = (('pfast', 10)…www.backtrader.com

Backtrader is currently one of the most popular backtesting engines available. It was built using python, and has a clean, simple, and efficient interface that runs locally (no Web Interface). One thing to keep in mind, backtrader doesn’t come with any data, but you can hook up your own market data in csv and other formats pretty easily.

Starting with release 1.5.0, BackTrader has live-trading capabilities. It’s been a popular choice with algo traders, especially after Zipline discontinued live trading.

(6) IBPy:

blampe/IbPy
IbPy - Python API for the Interactive Brokers on-line trading system.github.com

IBPy is an unaffiliated third party python wrapper for InteractiveBroker’s Trade Workstation API. Before IB started providing their official API library for python, this was the only way to connect to TWS for algorithms written in python.

IB has released an official python SDK, and this library is heading towards begin obsolete(while still being relevant for python2 users). But there still remain a significant number of live trading engines/tools that still use this library, and it’s good learning material for whoever wants to learn about implementing API’s.

While it’s good to learn about this library since it’s ubiquitous, if you are starting fresh, we recommend IB’s official python SDK.

Alpaca Trade API Python SDK is even much simpler to use!

Analytical Tools:

Back testing will output a significant amount of raw data. Some IDE’s will provide basic visualization and analysis, usually algorithm performance. If you’re looking for deeper evaluation, I recommend these tools:

(7) Pyfolio:

quantopian/pyfolio
pyfolio - Portfolio and risk analytics in Pythongithub.com

Pyfolio is another open source tool developed by Quantopian that focuses on evaluating a portfolio. What sets Pyfolio apart, is its ability to introduce degrees of uncertainty to a static set of data points, and evaluate Bayesian metrics from the user’s portfolio. The Pyfolio API offers a number of visualizations, which can be found on their GitHub repository.

(8) Alphalens:

quantopian/alphalens
alphalens - Performance analysis of predictive (alpha) stock factorsgithub.com

Alphalens is also an analysis tool from Quantopian. Unlike Pyfolio, Alphalens works well with the raw data output from Zipline, and rather than evaluate the portfolio, is performance analysis of predictive stock factors. Alphalens has its own range of visualizations found on their GitHub repository.

1_HnTL1cG_aBDoyBDyOzfkew.png

Median Daily Returns by Factor Quantile — one of the visualizations that alphalens offers

(9)TradingView:

1_Vy5CbHA0AdW7pwSmiwoZng.png

TradingView is a visualization tool with a vibrant open-source community. It’s entirely web-based, and allows users to visualize data, whether the data is the result of paper trading or algorithmic back-testing. Like Quantopian, TradingView allows users to share their results and visualizations with others in the community, and receive feedback.

(Bonus) Execution Platforms aka Broker-Dealers:

(10)InteractiveBrokers:

1_jAUoYLH-Fa3CyOtsfzsW3w.png

InteractiveBrokers is an online broker-dealer for active traders in general. They have been in the market since 1978. Algo trading isn’t IB’s focus, but multiple engines offer live trading through integration with their Trader Workstation. We’ve mentioned IB several times in this article — they’re just that good!

(11)Alpaca:

1_bhSUXCHVNP_JQmsMHklPlg.png

Finally, Alpaca! Alpaca was founded in 2015, and is an up and coming commission-free, broker-dealer designed specifically for algo trading. Alpaca also has a trade api, along with multiple open-source tools, which include a database optimized for time-series financial data known as the MarketStore.

The brokerage is scheduled to be publicly available this September (you can play around with the MarketStore right now), but if you can’t wait, head over to our website and jump on the waitlist for a chance at early access!

Alpaca | Algo Trading Commission Free with REST API
Lower your cost, Maximize your profits. Algo trading commision free.alpaca.markets

Miscellaneous Tools to Take a Look At:

  • qtpylib — another simplistic python backtesting engine
  • Multicharts — proprietary trading platform for forex and equities
  • WealthLab — desktop tool which allows C# backtesting, with live trading exclusive to Fidelity
  • Enygma Catalyst — for crypto trading
  • MetaTrader — backtesting/livetrading desktop app, de-fact in forex

I hope this quick primer on tools available right now was useful. If you liked it, please leave a clap (or two, I don’t mind). If you think there are tools that I missed, leave a comment below! I always appreciate any, and all feedback.

by Rao Vinnakota

/

I am a College Student and I Built My Own Robo Advisor

I’m Rao, and I’m an intern at Alpaca working on building an open-source robo advisor. I don’t have much experience in the space, and I had to find a lot of answers. While there’s a wealth of material available on the web, very little is organized. This post is the combination of various threads and forums that I read through looking for answers.

“Yes, you an do it too!”

“Yes, you an do it too!”

What is a Robo Advisor anyway?!

Robo advisors are automated advising services that require little to no user interaction. They specialize in maintaining portfolios based on the investors chosen risk level. Btw, they were launched at the start of the financial crisis in 2008.

The actual logic for a robo advisor is straightforward.

  • Allocation” — Given a risk level, portions of capital are allocated to different positions.
  • Distance” — Over a regular time interval, the adviser scans to see if there’s a significant change in the portfolio balance, and
  • Rebalancing” — If necessary, rebalances.

Allocation:

The process of allocation is where different weights are assigned to asset classes based on the developer’s algorithm. These asset classes cover the various aspects of the market, and keep a diversified portfolio. Wealthfront sees these asset classes as:

  • US Stocks
  • Foreign Stocks
  • US Bonds
  • Foreign Bonds
  • Inflation Protection

Each of these assets is represented with ETFs, who capture a broad look at the asset class.

Distance:

Rebalancing a portfolio comes with a certain amount of overhead and cost. To avoid this, the robo advisor computes a “distance” vector. To trigger a rebalance, this distance will have to be greater than a given threshold. Most robo advisors usually have this threshold set to 5 percent.

The distance in this case, is the individual change in weight of each position. This is done by first calculating the current allocation. This is the value of a position against the total value of the portfolio. If any one position has a weight that’s 5 percent greater (current_weight/target_weight > 1.05), then the robo advisor will trigger a rebalance

Rebalancing:

Rebalancing is the act of buying and selling to return the portfolio to its target state. It’s important that all selling is done first. Once all cash available is gathered, necessary purchases are made.

To calculate how much to sell, use the target allocation of cash (weight * portfolio value), and see the number of shares that result from that cash. The difference between the number of shares currently held and the target level of shares is the amount to buy/sell.

Implementing a Robo Advisor with the Vanguard Core Series:

Now that we’ve established the various parts of what makes a robo advisor, we’ll start executing the steps to build one. We’ll build our robo advisor using Quantopian’s IDE.

When implementing our advisor, I find it easiest to do in steps. Quantopian’s IDE can only run backtests on a full algorithm. What that means, is there’s no “halfway” development. So, each step is a self-contained algorithm by itself.

Note: The implementation of Vanguard’s Core Series is using the information found here. The portfolio includes a 2% investment in a money market fund, but that isn’t available on Quantopian, so for the purposes of this tutorial, we’ll ignore it.

Risk-Based Allocation:

The first step, is to determine our universe, and assign weights using risk level. Our universe will be the Vanguard Core series:

  • VTI — Domestic Equity
  • VXUS — International Equity
  • BND — Domestic Fixed Income (Bonds)
  • BNDX — International Fixed Income (Bonds)

The risk level is actually the ratio of fixed income to equity, with equity being more volatile. So, a risk level 0 would have all capital allocated to fixed income (BND, BNDX), while a risk level of 5 would be 50/50. All 11 possible risk levels are catalogued in a dictionary, with the keys being the risk level, and values being tuples containing weight allocation:

risk_level = 5
risk_based_allocation = {0: (0,0,0.686,0.294),
                         1: (0.059,0.039,0.617,0.265),
                         2: (0.118,0.078,0.549,0.235),
                         3: (0.176,0.118,0.480,0.206),
                         4: (0.235,0.157,0.412,0.176),
                         5: (0.294,0.196,0.343,0.147), 
                         6: (0.353,0.235,0.274,0.118),
                         7: (0.412,0.274,0.206,0.088),
                         8: (0.470,0.314,0.137,0.059),
                         9: (0.529,0.353,0.069,0.029),
                         10: (0.588,0.392,0,0)}

The next step will be to implement our allocation in Quantopian. For this step, the only methods we’ll need are initialize and handle_data. The rest are superfluous.

The initialize method is the main. When a backtest is started, it automatically calls initialize. So, initialize will be the function that contains the dictionary for risk levels, as well as choosing the risk levels. The handle_data method is called automatically after initialize. It’s here that we’ll actually purchase the positions outlined in initialize.

Both initialize and handle_data have the variables context and data. Context allows the user to store global variables that get passed from method to method. Data helps the algorithm fetch different sorts of data. (Note: This is a change from Quantopian 1 where data was the object where global variables were stored).

Let’s get started. In initialize, copy and paste the following code:

context.stocks = symbols(‘VTI’, ‘VXUS’, ‘BND’, ‘BNDX’)
context.bought = False

risk_level = 5
risk_based_allocation = {0: (0,0,0.686,0.294),
                         1: (0.059,0.039,0.617,0.265),
                         2: (0.118,0.078,0.549,0.235),
                         3: (0.176,0.118,0.480,0.206),
                         4: (0.235,0.157,0.412,0.176),
                         5: (0.294,0.196,0.343,0.147),
                         6: (0.353,0.235,0.274,0.118),
                         7: (0.412,0.274,0.206,0.088),
                         8: (0.470,0.314,0.137,0.059),
                         9: (0.529,0.353,0.069,0.029),
                         10: (0.588,0.392,0,0)}
    #Saves the weights to easily access during rebalance
context.target_allocation = dict(zip(context.stocks,
                            risk_based_allocation[risk_level]))

    #To make initial purchase
context.bought = False

The variable context.stocks is a list of stock objects. The symbols function turns the strings into objects. The objects have attributes like current price, closing price, etc. Using that list, as well as the dictionary for allocation, we’ll create a second dictionary context.target_allocation. The keys are each ticker (VTI, VXUS, etc.) and the values are the ticker’s weights. This dictionary will be useful for both allocation and rebalancing.

Copy and paste the following code to create handle_data:

if not context.bought:
        for stock in context.stocks:
            amount = (context.target_allocation[stock] *
                      context.portfolio.cash) / data.current(stock,’price’)
            if (amount != 0):
                order(stock, int(amount))
                #log purchase
            log.info(“buying “ + str(int(amount)) + “ shares of “ +
                     str(stock))

         #now won’t purchase again and again
         context.bought = True

The variable context.bought refers to the value originally set to False in initialize. Since handle_data is called every time a market event occurs. So, using context.bought ensures the shares are only bought once.

To buy shares for each stock, the list of stock objects is iterated through. For each stock, the total number of shares are calculated by allocating the proper amount of capital (weight * capital), and then dividing that capital by the current price. Since we can only buy whole shares, leftover capital is added back to the cash on hand.

Lastly, for a smoother backtesting experience, all transactions are logged. The log is in the lower right hand corner. Build the current algorithm. Set the start date to June 2013 or later as the ETF BNDX was first tradeable on June 7, 2013.

Calculating Distance:

Before rebalancing a portfolio, it’s best to first calculate if the current portfolio is worth rebalancing. In more sophisticated robo advisors, this step would have a target portfolio calculated with an algorithm. For this example, our target portfolio is going to be the initial allocation defined by the risk level in initialize.

As the value of each position fluctuates, their portfolio weight may change too. The distance vector will be the change in weight of each individual position. Calculating the distance takes place in three steps:

  1. Calculating the current weights of each position
  2. Calculating the target weights (already done)
  3. Comparing the two weights

We want to check the balance daily, so we’ll go ahead and add the following function , before_trading_starts, to our code:

def before_trading_starts(context, data):
    #total value
    value = context.portfolio.portfolio_value +
                                         context.portfolio.cash
    #calculating current weights for each position
    for stock in context.stocks:
        if (context.target_allocation[stock] == 0):
            continue
        current_holdings = data.current(stock,’close’) *
                      context.portfolio.positions[stock].amount
        weight = current_holdings/value
        growth = float(weight) /
                        float(context.target_allocation[stock])
        if (growth >= 1.025 or growth <= 0.975):
            log.info(“Need to rebalance portfolio”)
            break

We first calculate total value. Since that value doesn’t change, it can be down outside the loop. Then, each position’s individual weight is calculated, and compared to the target weight (we’re using division since we’re interested in the relative growth of the position, not the absolute). If that growth exceeds the threshold (currently 2.5%) or is under the threshold (de-valued), then a rebalance is triggered. We don’t have an actual rebalance function written, so for now, we’ll simply log that a rebalance is necessary. It’s important to note the break added. Once the algorithm realizes that it’s time to rebalance, there’s no need to continue checking the rest of the stock. It creates a better best-case scenario.

However, we’re not actually done. We have to call before_trading_start, but calling it in a loop is inefficient. That’s why we’ll use the schedule_function command in initialize. Add this line of code to the end of the function block:

    schedule_function(
    func=before_trading_starts,
    date_rule=date_rules.every_day(),
    time_rule=time_rules.market_open(hours=1))

This schedules a distance calculation as the market opens every day. By computing the distance in the morning, we have the time and space necessary to execute rebalancing actions.

Rebalancing

The act of rebalancing a portfolio occurs in two steps. First, all assets that need to be sold are sold, and then all assets that need to bought are bought. Selling first makes sure that we don’t run out of cash.

The following is the code for a rebalance function:

def rebalance(context, data):
    for stock in context.stocks:
        current_weight = (data.current(stock, ‘close’) *
                          context.portfolio.positions[stock].amount) /
                          context.portfolio.portfolio_value
        target_weight = context.target_allocation[stock]
        distance = current_weight — target_weight
        if (distance > 0):
            amount = -1 * (distance * context.portfolio.portfolio_value) /
                     data.current(stock,’close’)
            if (int(amount) == 0):
                continue
            log.info(“Selling “ + str(int(amount)) + “ shares of “ +
                      str(stock))
            order(stock, int(amount))
    for stock in context.stocks:
        current_weight = (data.current(stock, ‘close’) *
                          context.portfolio.positions[stock].amount) /
                          context.portfolio.portfolio_value
        target_weight = context.target_allocation[stock]
        distance = current_weight — target_weight
        if (distance < 0):
            amount = -1 * (distance * context.portfolio.portfolio_value) /
                     data.current(stock,’close’)
            if (int(amount) == 0):
                continue
            log.info(“Buying “ + str(int(amount)) + “ shares of “ +
                      str(stock))
            order(stock, int(amount))

The selling and buying mechanics are the same. The only difference is when selling stock, you use a negative value when calling the order function. In both cases, we take the absolute difference in weight (target — current), and use that value to find the number of shares to buy or sell.

Multiple Universes

Vanguard provides several more universes beyond the core-series. Currently, we’re able to manipulate the risk level, and observe the outcome. Let’s add the functionality of also being able to select a universe.

The first and straightforward method, is to implement multiple dictionaries. Here’s how something like that would look. The CRSP series was added to our algorithm. The user now chooses both the universe and the risk level.

    core_series = symbols(‘VTI’, ‘VXUS’, ‘BND’, ‘BNDX’)
    crsp_series = symbols(‘VUG’, ‘VTV’, ‘VB’, ‘VEA’, ‘VWO’, ‘BSV’, ‘BIV’, ‘BLV’, ‘VMBS’, ‘BNDX’)
    #universe risk based allocation
    core_series_weights = {0: (0,0,0.686,0.294),
                           1: (0.059,0.039,0.617,0.265),
                           2: (0.118,0.078,0.549,0.235),
                           3: (0.176,0.118,0.480,0.206),
                           4: (0.235,0.157,0.412,0.176),
                           5: (0.294,0.196,0.343,0.147),
                           6: (0.353,0.235,0.274,0.118),
                           7: (0.412,0.274,0.206,0.088),
                           8: (0.470,0.314,0.137,0.059),
                           9: (0.529,0.353,0.069,0.029),
                           10: (0.588,0.392,0,0)}
    crsp_series_weights = {0: (0,0,0,0,0,0.273,0.14,0.123,0.15,0.294),
1: (0.024,0.027,0.008,0.03,0.009,0.245,0.126,0.111,0.135,0.265),
2: (0.048,0.054,0.016,0.061,0.017,0.218,0.112,0.099,0.12,0.235),
3: (0.072,0.082,0.022,0.091,0.027,0.191,0.098,0.086,0.105,0.206),
4: (0.096,0.109,0.03,0.122,0.035,0.164,0.084,0.074,0.09,0.176),
5: (0.120,0.136,0.038,0.152,0.044,0.126,0.07,0.062,0.075,0.147),
6: (0.143,0.163,0.047,0.182,0.053,0.109,0.056,0.049,0.06,0.118),
7: (0.167,0.190,0.055,0.213,0.061,0.082,0.042,0.037,0.045,0.088),
8: (0.191,0.217,0.062,0.243,0.071,0.055,0.028,0.024,0.030,0.059),
9: (0.215,0.245,0.069,0.274,0.079,0.027,0.014,0.013,0.015,0.029),
10: (0.239,0.272,0.077,0.304,0.088,0,0,0,0,0)}

    #set universe and risk level
    context.stocks = crsp_series
    risk_based_allocation = crsp_series_weights
    risk_level = 1

The user can use the three variables, context.stocks, risk_based_allocation, and risk_level, to set both the universe and the risk level.

What’s Next

Developing in Quantopian is a great experience — they provide lots of useful tools. But, it’s also limiting, being forced to only work in one file, etc. To build further on this robo advisor, I plan to migrate my work so far to the backend, and use Quantopian’s open source python library Zipline to run backtests. The next installment will cover all this and more!

You can find the algorithm here. Try it yourself!

by Rao Vinnakota

/

Algo Trading News Headlines 6/7/2018

How a job invented by Goldman Sachs took over the banking industry

(news.efinancialcareers.com)

It’s not just GS though. In the past few years, strats have caught on elsewhere too. Deutsche Bank now has them. So does Morgan Stanley. So does J.P. Morgan. So does Credit Suisse. And wherever there are strats, there is strat hiring. Morgan Stanley, for example, currently has around 50 strat vacancies. Insiders say Deutsche Bank’s strats team, set up by ex-GS strat Sam Wisnia, has gone from zero to over 100 in four years

Photo by  chuttersnap &nbsp;on  Unsplash

Photo by chuttersnap on Unsplash

Hedging with Machine Learning

(themarketmogul.com)

Before McDonald’s could introduce Chicken McNuggets, they had to hedge against the cost of chicken. If chicken prices rose dramatically, they would no longer be able to offer the product. After some time, a financial consultant determined that there were two costs associated with raising chickens. That is grain and water.

9 Most Commonly Asked Questions About MarketStore And Answers To Them

(blog.alpaca.markets)

In social media and offline, we’ve been answering questions and responding to comments, but today we wanted to take the opportunity to put all the queries and responses together in one post and share it with the entire community so everyone can get a look at the responses on a single post.

/