Friday 26 August 2016

Day Trading: Scalping Strategies

In this post, I summarise the main points from a video on whether Scalping is "legit". This video was presented by John Grady from No BS Day Trading. 

John discusses the various strategies which are used by pro traders. In fact, their own words are used in this blog post through interview and article excerpts. The aim is to prove that scalping is the way they trade. John's video provides insight into the trade management strategies of individuals who trade thousands of contracts. It covers accumulation/distribution, squeeze plays, reversing positions and moving the market as a result, averaging in an attempt to halt a move and turn losing trades into break even trades.
 
Trading Indicators

The reality is that the depth of market is really the most simplistic of trading indicators. It is also the most pure form of information. The reality is that markets is nothing more than an auction. People wanting to sell, people wanting to buy. Then there is a transaction when prices match. What you see in charts and other information is an extrapolation of the fundamental information in the order flow and trying to reduce it into a pattern, etc. This point was covered in my previous blog post. 

Proof of Speculators


Looking at the 10 year futures, the total volume was 1,313,134. That is the number of contracts traded on that day. The total open interest is 2,370,769. However, the change in open interest was 25,624. Your open interest change is less than 2%- less than 2% of your contracts traded were taken and held over night as open trades. The other 1.2mill+ were in and out closing on the same day. Therefore the majority of trading can be classified as speculation. 

Size Moves the Market

"What I've seen is that traders who don't have a strong trading methodology are often suckered down the path that the issue is their psychology. I, personally, have found it easy to locate good material about trading psychology whereas it has been very difficult to find people who can exercise and teach a winning trading methodology (at least when it comes to day trading)."

There are tonnes of material out there focused on psychology, risk control, etc. but that stuff is the easiest stuff to learn- it is easy to break down mathematically or scientifically. But when you get into the trading, you have discretion involved. You are trying to anticipate the future and this is not easy. Even algorithms are based on discretion. 


When you read interviews and articles by traders who have made it big, a lot of material doesn't make sense because there is no context or frame of reference. They have not seen the business from the inside. They haven't traded size or seen someone trade big size, or worked for a firm or bank that does major trades. 


It seems that what John is promoting is watching the order flow over time will help you put on good trades as a scalper. 


The best interview with Jack Schwager and Tom Baldwin. It sums it up perfectly.
Jack: "How did you figure it out?"
Tom: "It's like any other job. If you stand there for six months, you have to pick it up."
Jack: "How do you make your decisions?"
Tom: "You see the orders and you just trade it."
Jack: "How is size an advantage?"
Tom: "You've obviously never traded on the floor."


When you read through numerous interviews with traders, what they all say in common is that size moves the market. 


Looking at the screen shot, on left hand side, it's the 10 year treasury, middle is the 30 year, then 5 year treasury.

The Flipper- Paul Rotter

John is not saying that scalping is the only way to make money day trading. He is saying that you must understand the mindset of your competition if you want to beat the game and a large number of your competitors are scalpers who trade huge size. 


There is a guy called the "Flipper". Why is that his nickname? What he does it flip. Pretend you have the Bund trading near the support level (the level where most buyers tend to enter the stock). The Flipper might have bids in all three markets, giving the illusion that the market is strong. But, in reality, he has been getting short. When he feels the time is right, he get rid of his bids and then offers several thousand across all three markets. He is flipping his size. This triggers a domino effect. Other day traders sell to be short, people with weak long positions sell to get out because they don't want to lose any more money. While everyone else sells, the Flipper buys back his shorts and profits from the move he himself actually helped trigger. How does he trigger it? He trades size. 


One Eurex trader states that "You should see giant orders on one side of the market that would flip and go the other way". The traders, and a former Eurex official say someone was posting massive buy orders, waiting until the market moved towards that price and then selling instead- a massive head fake. The flipper does so much volume in the bund, boble and schatz that he's able to influence the whole yield curve and catch people out. 


You can see in the first profile, the market is at a high. You have a flipper and they sit here placing big orders (4312, 4794) at the high of the day, and in the 30 year- 1373 and 1334. It's an illusion sometimes. These large sell orders gives the illusion that the market runs into resistance and hold the market down. This keeps the market weak and people will sell right below it. But the flipper is actually buying between 25 and 26. Then he starts bidding his market up towards his own offers. When they get to the offers, they pull the offers. That 4794 size might disappear to say approx 1000. All of a sudden it turns from a market looking like it had resistance and now it is popping through the highs. The flipper who was long down in low prices then turns profit at 285, 290 and makes money. He plays both sides of the market. That is what flipping is and it happens on a daily basis. 


For an individual, the Flipper's scale is stunning. Last year, his personal trading volume alone accounted for about 180,000 contracts a day, or almost $70 billion on peak days, dwarfing all but the very biggest institutional players. He claims his average market share in the German bund was around 10% for many years. This is impressive not from the number alone but the fact the Bund is the world's second most traded futures contract after the Eurodollar. He mainly used boble and schatz for hedging purposes. 


In an interview with the Flipper (Paul Rotter), he states that his tactic is some kind of "market making" where you place buy and sell orders simultaneously, making very short term trading decisions because of certain events in the order book. For instance, he usually has a lot of orders in different markets at the same time, pretty close to the last traded price. The resulting trades are usually a zero sum game, then ultimately make a decision for a larger trade once he gets a feel for what is happening. 


So how long is he usually in a position? Paul is only looking for the next 3 to 5 ticks. Trend plays are rare, and it's a constant filling in different markets on both sides which causes constantly changing positions for hours. Opinions change several times within a minute, which is common when making short term trades. Keep in mind Paul Rotter is your competition. 


Tom Baldwin

Tom Baldwin says that trading not to lose from the floor point of view you are going to do what you have to do to not lose money. That's the goal. In doing that you end up making money because you are getting in positions that are the right way. 

If the initial trade is wrong and I lose money I don't think: I'm short 900 and its 5 ticks against me, I'm going to buy my 900, count up my losses and start over. What I do from a floor point of view is trade the position. That might involve buying 3000 at whatever price to get out, carry the market with me and sell it higher. When you are wrong, you are going to make the market move- people who are wrong generally move markets. So if I'm going to buy 900, I might as well buy all I can, it's probably just going to be around 1500 and in the process it is going to move the market and then I will make money on what I end up being long and then if I get reinforced by the rest of the world and they continue to buy, well I will just continue to buy. 

So what started off as a losing proposition, being short, turned out to be a big winner. His size helps to cause the break through to the highs. Everyone behind him carries it higher. 

Harris Brumfield

Interviewer: Did you trading style change over the ten years you were on the floor?
HB: Well, I changed stuff all the time, but the style itself- being very active, putting on position trades and scalping around them- never has changed. 


So, his basic strategy was trying to pick a direction, but when picking the direction, he is scalping around it all the time. 


Interviewer: What was the typical size for you?
HB: In the 10 year T note pit, I participated in about 20% of the volume, on average. With the Bund, I traded as many as 130,000 sides in four hours. 


This is another example of a trade who trades huge size, and is basically a scalper. He talks about moving from the pit to the screen- "also, the funds could be anonymous on the system, which allowed them to sell 30,000 and buy 20,000 instead of just selling 10,000- they could bluff and get away with it. They can't do that through the phone clerks and the pits- you can pick them off all day long." 


Basically, they work orders on both sides to net out to net 10,000. Looking at the screenshot, people ask how do we get 46163, 46124 size between two prices. The answer is that they are working an order to net out a certain amount. It is intentionally designed to confuse new traders. They don't understand that in the game, it's not just all in or all out. This is a poker game. Say a guy thinks prices are going up. He won't just sweep the market and buy 270, 275. That is too much risk and will move the market against himself. He will linger back and sell some at 255, if he can hold the market down, he can buy some at 240, 245. Then he does it again. Sell, buy, sell, buy. Only every time it goes up, he sells a bit less and buys a bit more. So that, over the course of half an hour, he nets out to be long. He tries to sustain the highs hoping he can create a move to break the highs. And then he gets paid from his positions at 240, 245 and break even at the higher prices.


The New Market Wizards: Conversations with America's Top Traders

Bill Lipschutz was not actually a scalper. But if you read the interview, you start to realise what he is talking about in reference to size and how it moves the market. He was basically short the dollar and got trapped in a bad move against him. 


What he says in this interview is "All I wanted to do was to make it through to the Tokyo opening at 7pm for the liquidity. If you really have to buy $3 billion, you can do it in Tokyo, you can't do it in the afternoon market in New York- you can't even do it on a normal day, let alone on a day when major news is out. My strategy was to try to cap the dollar in New York. Normally, if you sell several hundred million dollars in the afternoon New York market, you can pretty much take the starch out of the market. I sold $300 million, and the market went right through it."

What is he saying? Looking back at the screenshot (even though it's for Treasuries, not dollars), he was short in a big way. The market is heavily moving against him. If he can sell $200-300 million of the dollar, he can stop the market going up and slow down the market through the overnight. As it turns out, the market ignores him and keeps going up. There's nothing illegal about how he is trying to cap the market, you can usually do it with that size. They pick spots where they know that their size can influence the market. They hope they have reinforcement behind them. Sadly for Bill, he did not. 


HFT: Spoofing

It's funny how regulators are saying they are "catching up" with sending false signals on the market when this practise has been happening ever since the inception of markets. It's just easier with electronic markets, because nobody knows who you are when you place the orders. But this tactic was used in the pits- you would have a trader who used 5-6 brokers to help him execute his trades. So, he might be wanting to sell 2000,3000 contracts, then have brokers come in that work for him who bid right beneath him, then he would get his contracts off and the brokers then lower their arms. It's the same thing. Regulatory agencies are trying to squash this type of action, but right now it is still rampant. 


Conclusion

Another misconception is that computers are basically the same as people were, trying to get the best price, they will also get out when momentum stops. That's why you see more range, more choppy  days and it is hard to get follow through with more and more people playing for shorter term moves. It leaves you in the position where if you're going to be a day trader, you need to at least begin trying to understand the mindset of Paul Rotter, the Baldwins, etc. Those are the guys who influence the market. If they make trades that influence the market, you want to ride their coat tails. Be in the same direction as them. 

Thursday 25 August 2016

Order Flow Trading

Today I came across a video presented by John Grady from 'No BS Day Trading'. In this video, John talks about how order flow is the fundamental core principle behind trading. In this blog post, we discuss what really drives price movement using the Treasury market as an example and how scalping is effective in profiting on intraday price movements.  

I found his information to be very interesting as I had never previously considered scalping to be a trading strategy. In my next blog post I will cover various scalping strategies and automation through algorithms. 

The real reason most traders lose 

The majority of traders come in from retail side. They are looking at things that don't have impacts on the market. Things like Moving Averages, MACDs, charts. They are trying to make decisions based on that but they miss the fact that all the indicators are driven by order flow. I.e. The actual transactions that are taking place that drives the market up or down. 



In the example, we are looking at Treasury Futures. Bids are in Blue, Asks are in Red. In the middle you see prints. With Jigsaw, it splits the up tick and down tick data. In the first screen, it is the 10 year Treasury Market.  The second screen is the 30 year, third is 5 year and then it is the ultra bond. 

For the 10Y Treasury Futures, the most recent prints is 349 into 115 (11 and a half) and 192 up into 120 (12). There are some buyers hitting 120 and some sellers who are hitting 115. That is what shows up in the blue and red. The second column shows days volume profile. That is, this is the total accumulated profile for this session. 


Let's shift focus to the 4th profile- If you're the only guy in the offers and I'm the only one bidding, 66 is bid at 20 and 137 is offer at 21. 
If I account for all 66, and you account for all 137, we are the only two people in the market. In order for something to happen, one of us must hit the other one. 

Let's say I'm the buyer and I start buying and I buy your 137 and then I bid 200 at 21. So now I take it up a notch- 21. Now you are the offer at 359 at 22. Imagine then I hit all 359 at 22. Now I lift that and bid another 300 at 22. Now you are the offer at 244 at 23. I buy your 244 at 23, I bid 300 at 23. Now you are starting to get worried because I'm continuing to press the market against you. 

So you offer 214 at 24. I buy 214 at 24. I bid 300 at 24. When it hits that point, you start to feel the pain from the P and L stand point. So, instead of just offering 214, you begin hitting me with 200, hit 200, hit 200. But the problem is no matter how many you sell at 24, I just keep buying. Then I buy at 25, then I buy at 26. 

The point is that I am driving the market against you by clearing out all your offer orders. I am pressing it up. Ultimately, if it was just me and you, I will run the market up until your forced to liquidate, that is, your forced to start buying. But in this hypothetical world where we are the only traders, I am the person selling to you and I will take all your money. 


This is what is happening at the core fundamental level. You can't build a methodology for day trading if you don't understand how the game works at the core fundamental level. What  encounter a lot is that people don't grasp the concept of E.g. If i were to buy all 137 contracts, and then I bid at 21 for another 200, the bid price will go up. Taking the bid up to 22, taking the bid up to 23. People struggle to understand this. 

One side is trying to dominate the other side. They are trying to make the other side exit. You press the market against the losing side so far they can't stand the pain and exit for a loss. The other side liquidates for a profit. 
With sellers, they try to make the people start selling for a loss, when they start that the sellers are working buy orders to cover a profit. 

The majority of people are speculators. There are times when the heavy buying and selling press it far enough the other side gives up and gets out. The market will re trace itself and then go flat. People get confused about how it can go to 12, 5, 12 and flat line. One side wins, one side loses, market comes back and nobody wants to play anymore. 


So what is order flow?


Order flow is the orders coming into and out of the market. You have sellers offering and buyers bidding. Eventually they match up, and one way or another one gives up- in the previous example, if I were buying all 137 at 21, I then have to bid at 21 to get more contracts. 


Why is it important to watch order flow when trading? 


It's important because it lets you know how much size is trading at certain prices. It can give you an indication of areas that might be just back and forth chop. E.g. first screen there are just approx 80k offer sizes, an approximate 4 tick range. You had a dead market trading a lot of volume. That volume just says its a choppy nothing area and there is no reason to be involved there. On the other hand, if they executed all the way up to 15 and 155, that may trigger some more buying that runs through that. Order flow that takes place getting through that point will tip you off to what is the next movement for a few ticks. This relates to scalping. 


Lessons learned while trading for prop trading firms


Where does John come up with my methodology and how am I accurate? Working for a prop firm. Not as much training is in prop firms as people think there is. Difference is there are no charts and indicators, they just show you the ladders and say "stare at this and figure it out". HFTs in particular are almost 100% order flow oriented. They are looking for places to get in without risk, trying to front run and scalp it out with no risk. The best guy was moving the market due to transaction size. This triggers other people to make the same order. This wave is created by heavy hitters. If it not a string of stop orders that move the market. 


Misconceptions about pro vs. retail


The misconception is that pro traders try to take retail money. This is only true to an extent. The pro trader is battling it out against other guys who are trading as huge positions. When a major move takes place, you can have smaller ones getting hit and it will help move the market. The main market driver is due to size. 


The importance of a good platform


Retail traders are starting to see what they have been missing because they now have access to better platforms at reasonable rates.

Jigsaw is one of them. This is another reason why retail traders struggle and fail. They cannot see the ladder or depth of market. Other platforms are not good at showing prints accumulating. Nobody had access to a decent ladder. Most used to or still have Xtrader. This was super expensive per month just for access. 


Getting the edge: Scalping vs. Swing Trading Styles


There is the common conception of scalpers work with 1 ticks. E.g. Buy 115 and work 12s. Not the case - sometimes when market is slow it is a potential methodology, but usually they are looking for the next 3-5 and sometimes beyond that tick. The idea is that you are trying to get involve din areas where it seems like the pressure is in your favour. The idea is more like watching order flow (does it look like buyers are going to lift the offers or sellers are pressing the market down to lows?) I don't need to see anything else to get a feel for that. All other indicators and charts are basing their indicators off the ladder. 


What does getting the edge mean? 


In the most ideal scenario, if you thought the market was going to go up, you would see 2094 start to print, as it prints, you would buy it, market goes bid at 12, instantly orders start hitting 125 (buyers start buying at 125), big bid behind you at 12. You instantly sit in a break even trade. Someone buys 125, you are one tick in your favour. If you choose, the trade at worse is a break even trade. Ideally, the perfect scenario, you bid, market goes up, you have the edge. 


Reading the tape vs. traditional technical analysis


Charts only show you the price. They do not show you how the market traded at the price. Did the market bounce at a certain price because it was light volume after a number release and people were flying by the seat of their pants trying to trade a highly volatile response? Or did it get to that price by steadily trending down and then bounce because a huge amount of money came in to defend that price and attempt to press it back the other way? It makes a big difference if you're looking to trade in that area.


So, if you watch order flow instead, you can see 2000 on offer, and you can watch 1800 trade into the 2000. So you actually know buyers are actually buying at 12. Therefore, rather than randomly placing a buy limit at 115 or 11, or buy stop at 125, you can pin point entries and exits because you can see someone is buying 12. You know there are buyers at 12, so you might as well hit it as you know buyers are coming in behind you. 

With traditional tech analysis, people don't pay attention to the prints and from execution, you save ticks by paying attention. Say you might want to be long and your thinking about hitting 12, but you realise no ones actually hitting 12 yet, I can actually get in at 115 as not as many people bidding. You save yourself that tick by not randomly hitting out there and selling 115 or hitting 12. 


Also, charts only show the past. Everyone in the world is looking at the same obvious support, resistance, moving averages, pivots, etc. Just because someone is watching a price does not mean he is willing to trade that price. A support level is not a support level unless there are enough buy orders to over whelm sell orders and prevent it from moving lower. 


During a particular day, trades on one side may go for a price where they believe there will be stops and the stops are there so they get paid. On a different day, the stops may not be there and they will not get paid. Either way, they react to what happens a the markets hits those prices. If the stops are not there, the traders making the run do not sit and wait hoping they will be there later. They begin exiting in an attempt to not get stuck on the wrong side. They will always adapt based on how orders are moving. 

Misconceptions about HFT

If an HFT program or trader plans to buy, the program won't just step up and buy just because there are 192 contracts priced into 2094. The program is going to wait until it sees more size trading. Waiting to see 1000, 2000 print into that 2094 and then the program executes. It is trying to get the edge.

In floor trading, the guys work out who the big traders are. That is, individual traders themselves and who is a broker for big institutions. E.g. Person A watches and sees a broker for Goldman Sachs is about to offer out. So he turns to the first bid near him and hits their bid E.g. hits someone's bid at 10. He is now short. Then he turns around and waits to see if he is correct. Say the broker starts offering. The broker offers at 11, 10, 9, 8 he is moving the market with huge size. Person A then buys at 8. That is what floor traders used to do, it is what scalpers and HFT traders do now.

Why is it important? They are influencing the market on a moment to moment basis. This feeds into charts for technical analysis. The idea you can predict the future one or two hours out is usually not accurate. So much can influence the market in such little time from size. If you think that HFTs have replaced scalpers, you're wrong - HFTs are working orders across multiple exchanges, most is in the realm of stocks. The reason why they can't pull it off in futures is that most futures are locked into a single exchange. 


The luck factor

There is always a luck factor no matter what everyone says. Find something that works and stick with it. E.g. if you see its hammering bids, stay away might work (unless you short- but sometimes you might be that guy who goes short too late).
The way you ride it out depends on whether you have proper risk parameters in place. 


Q and A with John Grady


- How do you use the Ultra Bond? What is the difference between the Ultra Bond and the 30 year?
The difference other than contract specifications if that UB offers a little bit of a clue, it is light volume and it has been moving a bit more from a readable stand point than the 30 year. the 30 year does not move as much as it does before, as everyone is transferring to shorter term. People who are trading longer term ignore the 30 year now and go towards UB. 


- I'm a new Trader: Which is best 5 , 10 or 30 year?
You have to watch them all. Every market has its own nuances. The overall concepts are the same but execution is different. If you trade treasuries, it is important to trade all of them. Once you become familiar to the ladders, it becomes easier. 


- NasDaq: I am having trouble reacting fast enough to the numbers. Advice?
I advise against those markets but if you are going to trade them, I find that you must use stop orders. You have to anticipate where the run is going to take place, don't rely on yourself clicking yourself out of an order. It is hard to get the edge in a thin market like that. Prefer thicker markets.


- False or fake orders. E.g. Flash orders.
Spoof orders or flash orders ; you must view them in the context of the situation. If it is an area and there breaking down, those orders are probably real. The sell orders are always there, sometimes you notice there is 4000 on the offer and that will drop to 2000. How you play that depends on numerous factors. it does matter sometimes and with regards to ice bergs you have to pay attention to it. An ice berg order in the middle of a range at noon hour probably won't mean much, but following a news event has importance. 


- Why do you not use a Foot print chart as an order flow tool?
This chart shows volume on different time periods. Foot prints are a personal preference. I am biased to strictly staring at bid ask. It is cleaner but some people like foot prints to look back the past 2 minutes or 5 minutes. Some people think they react faster just looking at the ladder.


- Big money moves the orders? Why not just filter so you see big orders only
Often people disguise their orders. oddly enough, if one order of 3000 drops in one market, it is quite frequent that the market just stops. It doesn't go one way or another. It is a conglomeration of size. it is not one guy who is moving the market, it is a guy moving 1000, 5 guys moving 200, 3 guys moving 3000. He will buy and sell in a range until he nets out.
Sometimes it is helpful when market moves one day but you want more information looking at the accumulation of inside prints. 


- When do you reset the inside prices?
Sometimes we forget the exact price where it strikes. So if market went back there, you can recall. Therefore we should leave insides up. 


- On the ES Chart, there is a big reversal. Is it possible that the big money traders are the same traders that bid it back up? 

Absolutely. The initial bump back is probably a short sale covering. All the orders feed off each other. Then you end up with heavy money starting to reverse it too. That is why you don't just sit there, you want the edge. 

- Does the market tend to run from low volume area to low volume area?
Actually it is the opposite usually but depends on the context. Eventually it moves into thin area and then develops in a thick area. there are periods of run, cover, run, cover. 


- How many trades do you execute on average in bonds?
Maybe 5 to 15, depending on the day. Sometimes I can do 20 trades but slow days I can just do 2 trades. Do not focus on number of trades, focus on whether it is a good trade. Do not worry about how many trades you make.


- Do you use the reconstructed tape on treasuries and do you see the big orders on the ladder?
Do not use the reconstructed tape on treasuries as just watching the amount of size is enough to follow the flow. There is so much more size in treasuries than stock indices. 


- Do you look at or use cumulative delta?
Cumulative delta is a way to track from the start of session that executes at bid and how many execute at the ask. Jigsaw has a feature called strength meter and a quick way to figure it out is the ribbon at the bottom. Red: how many hit into bid, Blue: How many hit into the offer. 


- Do you watch previous days, or only profile of current session?
I only use the current one, but just be aware of previous action on previous days. For example, between 115 and 13 with 80k volume, the next day I remember there was an 80k heavy volume, so if it gets there again it will probably chop around again. 






Monday 8 August 2016

Quantopian Hackathon

Last Saturday we attended our first Hackathon held at the Tyro FinTech Hub. The event was hosted by Dr. Tom Starke. 

The hackathon was based on Quantopian, an online crowd sourced hedge fund platform that just received $250m in funding from hedge fund manager Steve Cohen of Point72. 

The aim was to construct an algorithm that had low beta (-0.3 to 0.3) and made use of sentiment data (StockTwits). This daily sentiment data included variables such as date, equity, number of bearish signals, number of bullish signals, the intensities of each signal scored, and total messages generated (including neutral). 

Ideally, when designing an algorithm, you firstly work in a research phase and then an implementation phase. In the research environment, we interact with data and quickly iterate on different ideas in a notebook. That way, you can make sure your designing your algorithm on the data you want, and make sure the data is reliable and valid to use in a trading strategy. I like to think of it as the data science part of algo trading. Here you can also construct your own method of filters and scoring, simple examples include making ratios, finding net differences, etc. More information on how to do this in Quantopian can be found in their pipeline tutorial.

Our strategy combined the sentiment data with Bollinger bands. 

Put simply, if the price falls below the recent lower band, then we long the market and short the bond market. However, if the sentiment signals were negative, we would short the market and long the bond market. 

If the price is above the recent upper band, then we short the market and go long the bond market. However, if the sentiment signals were positive, we would long the market and short the bond market. 

Basically we are trying to use mean reversion, but transitioning to momentum based on sentiment signals. 

Here's the detailed version.
  • Open positions at the start of the day and close positions 5 minutes before market day end. 
  • Default slippage and transaction costs were used
  • We had the algo go through the S&P100 and aggregate the sentiment score. 
  • The score itself was: the sum of log[(bullish intensity +1)/(bearish intensity + 1)]
  • In the bollinger band, number of non-biased standard deviations from the mean is 0.6 
  • If price is below recent lower band then we long the market BUT
    • If score is less than -0.5
      • Have 150% portfolio value shorting market
      • Have 50% portfolio value long 1-3 year treasury bonds
  • If price is above recent upper band then we short the market BUT
    • If score is more than 1.5
      • Have 150% portfolio value long market
      • Have 50% portfolio value short 1-3 year treasury bonds 
The Code

import talib 
import pandas as pd
import numpy as np
from quantopian.pipeline import Pipeline
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.data.psychsignal import stocktwits as psychsignal
from quantopian.pipeline.data.builtin import USEquityPricing


def initialize(context):
    
    context.spy = sid(8554) 
    context.shy = symbol('SHY')
   
    # Open positions at start of the day, one minute into the day.
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
    
    # Close positions five minutes before the end of the day.
    schedule_function(close_positions, date_rules.every_day(), time_rules.market_close(minutes=5))

    #Setting default slippage and commission
    set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
    set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1))
    
    context.stop_price = 0
    context.stop_pct = 0.98

    pipe = my_pipeline()
    attach_pipeline(pipe, "pipeline")


# Before Trading Start

def before_trading_start(context, data):
    # Store our pipeline output DataFrame in context.
    context.results = pipeline_output('pipeline')
    

# Create Pipeline

def my_pipeline():
    pipe = Pipeline()
    
    #Adding pipeline factors
    NYSE_screen = (morningstar.share_class_reference.exchange_id.latest.eq('NYSE'))
    SPY_screen = (morningstar.valuation.market_cap.latest.top(50, mask=NYSE_screen))
    
    pipe.add(psychsignal.bull_scored_messages.latest, 'bull_messages')
    pipe.add(psychsignal.bear_scored_messages.latest, 'bear_messages')
    pipe.add(psychsignal.bullish_intensity.latest, "bullish_intensity")
    pipe.add(psychsignal.bearish_intensity.latest, "bearish_intensity")
    pipe.add(psychsignal.total_scanned_messages.latest, "total_messages")
    
    pipe.set_screen(SPY_screen &  (psychsignal.total_scanned_messages.latest>10))
    
    return pipe

def calculate_score(results):
    score = np.sum(np.log((results['bullish_intensity']+1)/(results['bearish_intensity']+1)))
    # score.columns = ['score']
    return score

def rebalance(context, data):
   
    score = calculate_score(context.results)
        #current_position = context.portfolio.positions[context.spy].amount
    price=data.current(context.spy, 'price')
    
    # Load historical data for the stocks
    prices = data.history(context.spy, 'price', 15, '1d')
    
    upper, middle, lower = talib.BBANDS(
        prices, 
        timeperiod=5,
        # number of non-biased standard deviations from the mean
        nbdevup=0.6,
        nbdevdn=0.6,
        # Moving average type: simple moving average here
        matype=0)
    # If price is below the recent lower band 
    # portfolio value into SPY
    #if price <= lower[-1] and current_position <= 0 and data.can_trade(context.spy):
    if price <= lower[-1]:
       # print 'here'
        if score < -0.5:
            order_target_percent(context.spy, -1.5)
            order_target_percent(context.shy, 0.5)
            context.stop_price = (2-context.stop_pct) * data.current(context.spy, 'price')
        else:
            order_target_percent(context.spy, 2.0)
    # If price is above the recent upper band 
    # portfolio value to short SPY
    #elif price >= upper[-1] and current_position >= 0 and data.can_trade(context.spy):
    elif price >= upper[-1]:
        if score > 1.5:
            order_target_percent(context.spy, 1.5)
            order_target_percent(context.shy, -0.5)
            context.stop_price = context.stop_pct * data.current(context.spy, 'price')  
        else:
            order_target_percent(context.spy, -2.0)

    
#stop loss specifications:
def handle_data(context, data):
    
   
    set_trailing_stop(context, data)
    score = calculate_score(context.results)
    if score > 1.5:
        if data.current(context.spy, 'price') < context.stop_price:
            order_target(context.spy, 0)
    elif score < -0.5:
        if data.current(context.spy, 'price') > context.stop_price:
            order_target(context.spy, 0)


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

def close_positions(context, data):
    order_target_percent(context.spy, 0)
    context.stop_price = 0
    









Thursday 4 August 2016

Bitcoin vs. Ethereum

Ever heard of Ethereum? A new cryptocurrency created in 2015, it’s been dubbed Bitcoin’s experimental younger brother.

Like Bitcoin, Ethereum is a decentralized cryptocurrency. Unlike Bitcoin, it runs smart contracts which execute autonomously through code. The smart contracts can interact with other contracts, make decisions, store data and send the currency to others. For instance, a parent’s contract can automatically transfer money to their child every Christmas. Contracts are specified by their creators, but the execution is done on the Ethereum network. The contracts will only be eliminated if self destruction was part of their programmed code.


Ethereum hasn’t reached the scale of Bitcoin but it has increased in value to a market capitalization of around $1 billion. It is currently the second most popular cryptocurrency behind Bitcoin. One unit of this currency, known as an Ether, is currently worth $10.52 following a hack on its system in June. Prior to the hack, the price was reaching highs of almost $20.   

When people talk about Ethereum, they usually also refer to the Dao, a Decentralized Autonomous Organisation. Its goal is code the decision making tools and rules in an organisation, which in turn would result in decentralized structures as the need for documents and governing persons is eliminated. The Dao can be thought of as a crowd sourced venture capitalist company. People add funds to the Dao through buying tokens that symbolize ownership. The funding was reportedly the biggest crowd funding campaign ever. After funding, people submit proposals to the Dao regarding how to allocate its funds and members vote to approve the proposals.  This is different to equity stake- the contributions give voting rights, not ownership. Nobody owns the Dao as it is software running on the Ethereum network.  

Some claim Bitcoin and Ethereum are direct competitors whilst others perceive the two cryptocurrencies as complimentary features of the innovative blockchain economy. Bitcoin’s niche is its role in virtual gold, providing a reliable monetary system unaffected by uncontrolled inflation and political interference.  Ethereum’s niche involves evolving into a universal computer having a blockchain-based coding language allowing codified contracts and decentralized applications.

However, neither cryptocurrency actually has their operations so clearly specified. They have similarities and minimal barriers to user migration. For instance, the smart contract platform Rootstock.io is a threat to Ethereum, as it does everything Ethereum does with the added bonus of extra security on the already more secure Bitcoin network.  But given its growth statistics, Ethereum is starting to catch up as an investment tool. Their competition will result in better cryptocurrencies.

Total annual Ethereum issuance is restricted to 18 million per year. This reflects it being an inflationary currency, with an inflation rate of approximately 20% of current supply. The future value will decrease as the currency is sent to the miner rather than the program. Total Bitcoin supply has a limit of 21 million coins. The amount issued is halved every four years. The most recent halving in July sees Bitcoin’s inflation rate decreasing to a rate of 5% per year. The continuation of this produces a deflationary currency, encouraging savings and profiting those who bought in cheaply.

So what type of people prefer Ethereum to Bitcoin? Ethereum users are less politically and economically conscious. They are happy with ultimate authority in the inventor Vitalik Buterin.  They are more focused on how industries can take advantage of Ethereum. Bitcoin users are more supportive of individual sovereignty, hence the emphasis on decentralization. Metcalfe’s law expresses the network effect, where a network’s value depends on its number of users. People are more likely to join already popular networks, so Bitcoin has the first mover advantage.

When something is popular it is important it is secure. Bitcoin enables coins that have been sent to be locked for a specified time period. It’s effective in transaction processing. Ethereum however is Turing compete, expanding its instructions into a coding language like JavaScript. But, this actually increases risk of an attack. Basically anybody can program up a smart contract for the Ethereum network. Whilst innovative, the number of bugs and the recent hack has shown it is not a reliable base for the new blockchain economy. Additionally, given the investments in hashrate (Bitcoin’s hashrate is 1.8 whilst Ethereum’s hashrate is 3), the monetary cost to breech Bitcoin’s security is proportionately greater.

Both cryptocurrencies have a Proof of Work blockchain, with Ethereum mining at 25 transactions per second performed by graphics cards and Bitcoin mining at 3 transactions per second performed by ASIC devices. Whilst Ethereum is more scalable, its proposed transition to Proof of Stake will move away from decentralization.

Ethereum can be summarized as an innovation taking advantage of blockchain technology, supportive of Bitcoin though does have the same structure. Its rising popularity makes it a competitive cryptocurrency, and its volatility makes it a great trading tool. Both Bitcoin and Ethereum must overcome challenges to establish themselves, though the industry’s intellectual minds will no doubt see to that.