Análisis técnico y velas japonesas para inversores de medio y largo plazo partiendo de cero

Gregorio Hernández Jiménez

ha escrito muchos libros sobre bolsa, este es el segundo que empiezo a leer y el primero que termino, el otro aún lo tengo a medias.

El libro me ha permitido aprender cosas básicas sobre el trading que no sabía, explicación de los indicadores básicos, una guía de como integrar todo y sobre todo unas explicaciones con algunas metáforas muy buenas que son fáciles de recordar.

Todo lo que leí hasta ahora estaba enfocado en trading sobre Forex y cryptomonedas, este está enfocado en stocks, lo cual, combinado con las explicaciones básicas de indicadores me ha resultado muy fructífero en estos momentos.

http://www.invertirenbolsa.info/

Quantitative trading on cryptocurrency market Q3

This is the second chapter of a learning process that started last September.

Third Quarter

The third step is defined for the next 3 months, where the main goal is to define a specific strategy of quantitative trading and work on it with real money on crypto currency market.

Following the V2MOM model:

  • Vision: Have a strategy running in crypto currency market running not with a period of 2 – 3 hours, but some days (stop operating at 3m).
  • Values: have fun, learn a lot, build a team with Dani, do practices and more practices.
  • Method: learn about trading basis, do backtesting with Quantopian on stocks or Forex (analyze the results in deep).
  • Obstacles: Time.
  • Measures:
    • Make short/long decisions based on 1 hour.
    • Read at least 1 book of trading.
    • Perform backtesting with Quantopian and document the results and findings.
    • Improve and document the “mode operations” and “mode backtesting”.

Death line = June 2018

Results (July 1st, 2018)

  • Time to be accountable, let’s go…

Volume Price Confirmation Indicator (VPCI)

I have been looking for volume indicators that help me to identify the right minimum volumes to place long position, but by the moment I was not success.

This time I found this VPCI in tradingview, so let’s see how it works. The notes are very interesting basis of knowledge.

Volume Price Confirmation Indicator (VPCI)

Developed by Buff Dormeier, VPCI won 2007 Charles H Dow award by the MTA. VPCI plots the relationship between price trend and the volume , as either being in a state of confirmation or contradiction.

Fundamentally, the VPCI reveals the proportional imbalances between price trends and volume-adjusted price trends.

  • An uptrend with increasing volume is a market characterized by greed supported by the fuel needed to grow.
  • An uptrend without volume is complacent and reveals greed deprived of the fuel needed to sustain itself.

Investors without the influx of other investors ( volume ) will eventually lose interest and the uptrend should eventually breakdown.

A falling price trend reveals a market driven by fear.

  • A falling price trend without volume reveals apathy, fear without increasing energy. Unlike greed, fear is self-sustaining, and may endure for long time periods without
    increasing fuel or energy. Adding energy to fear can be likened to adding fuel to a fire and is generally bearish until the VPCI reverses. In such cases, weak-minded investor’s, overcome by fear, are becoming irrationally fearful until the selling climax reaches a state of maximum homogeneity. At this point, ownership held by weak investor’s has been purged, producing a type of heat death capitulation. These occurrences may be visualized by the VPCI falling below the lower standard deviation of a Bollinger Band of the VPCI, and then rising above the
    lower band, and forming a ‘V’ bottom.

The code

//
// @author LazyBear
//
// If you use this code in its orignal/modified form, do drop me a note.
//
study(“Volume Price Confirmation Indicator [LazyBear]”, shorttitle=”VPCI_LB”)
shortTerm=input(5)
longTerm=input(20)

src=close
vpc = vwma(src, longTerm) – sma(src, longTerm)
vpr = vwma(src, shortTerm)/sma(src, shortTerm)
vm = sma(volume, shortTerm)/sma(volume, longTerm)

vpci = vpc*vpr*vm
hline(0)
plot(vpci, color=orange, linewidth=2)

DrawMA = input(true, type=bool, title=”Draw MA on VPCI?”)
lengthMA=input(8, “VPCI MA Length”)
s=sma(vpci, lengthMA)
plot(DrawMA?s:na, color=teal)

// Uncomment this line to enable histogram
// plot(DrawMA?(vpci-s):na, color=blue, style=histogram)

DrawBands = input(false, type=bool)
HighlightBreaches = input(true, type=bool)
length=input(20, title=”BB Length”)
mult=input(2.5)
bb_s = vpci
basis = sma(bb_s, length)
dev = (mult * stdev(bb_s, length))
upper = (basis + dev)
lower = (basis – dev)

plot(DrawBands?basis:na, color=gray, style=line)
p1 = plot(DrawBands?upper:na, color=gray)
p2 = plot(DrawBands?lower:na , color=gray)
fill(p1, p2, blue)

b_color = (bb_s > upper) ? red : (bb_s < lower) ? green : na
offs_v = 0.3
breach_pos = (bb_s >= upper) ? (bb_s+offs_v) : (bb_s <= lower ? (bb_s – offs_v) : 0)
Breached=(bb_s >= upper) or (bb_s <= lower)
plot(HighlightBreaches and Breached ? breach_pos : na, style=cross, color=b_color,linewidth=3)

Litecoin

Bitcoin and  Litecoin are the global leaders in cryptocurrency, both are powered by similar technologies with the exception that Litecoin is a modified, more efficient version of Bitcoin focused on retail applications. Litecoin, as a result, is both cheaper and faster to transfer than Bitcoin but unfortunately may not be as universally accepted as Bitcoin.

Some advantages with respect Bitcoin:

  1. Faster transaction confirmation time (4x faster than BTC)
  2. Increased storage efficiency due to scrypt usage in LTC proof-of-work algorithm
  3. More coins to reward miners (84mn to be distributed total compared to 21mn BTC).

Litecoin is one of the more popular coins. They stay in the top 5 cryto currencies but during these last weeks the news about LitePay are not helping to the project (March 2018).

Litepay

LitePay was announced to be released around the end of February 2018.

Then it was rescheduled for launching at the beginning of March 2018.

Now the launch has been postponed without defined date.

Litepal

Another payment solution for Bitcoin and Litecoin with a roadmap, that I want to follow up how they deliver.

  • Payment infrastructure ready: 1/May/2018
  • Platform, meet payments: 10/May/2018
  • Developer API release: 17/May/2018
  • Series 1 – Integration: 30/May/2018
  • Series 2 – Integration: 25/June/2018

 

Quantopian concepts

I have invested some hours learning about Quantopian environment and the basic concepts around the platform. The environment is very powerful, so I wanted to gain some basic clarity of the basis.

Quantopian platform

It consists of several linked components, where the main ones are:

  • Quantopian Research platform is an IPython notebook used for research and data analysis during algorithm creation. It is also used for analyzing the past performance of algorithms.
  • The IDE   is used for writing algorithms and kicking off backtests using historical data.
  • Paper trading ability, so you can perform simulations using live data.
  • Alphalens is a Python package for performance analysis of alpha factors which can be used to create cross-sectional equity algorithms.
  • Alpha factors express a predictive relationship between some given set of information and future returns.
  • help: https://www.quantopian.com/help#optimize-title

The workflow

To maximize the use of Quantopian is important to understand how to work on the different steps to achieve your goals.

The basis are the same ones that the ones explained on this post , and that are represented by this diagram:

I did not found a diagram in any place, so I draw my own diagram.

Workflow, step by step

1.Universe Selection : define a subset of tradeable values (stocks/futures); the universe should be broad but have some degree of self similarity to enable extraction of relative value. It should also eliminate hard to trade or prohibited instruments. (Example: select companies with >10B$ revenue and dividend rate >3%).

This is done throught the object named “Pipeline”. The idea is not to limit yourself to a set of specific stocks but define a pipeline of stocks that allow you to quickly and efficiently consider many thousands of companies.

Pipeline allows you to address all companies, then filter them.

2.Single Alpha Factor Modeling:

Initially these 4 words together sounds like chinese to me. So I will try to explain as I understood it: it’s a model composed by a single factor that tries to find a result that has statistical significance (alpha factor).

Not enough?, Ok, I will try to explain some concepts.

First, I need to review some basis of statistics.

What is an alpha factor?

In statistical hypothesis testing, a result has statistical significance when it is very unlikely that it has occurred randomly. The level of significance is commonly represented by the Greek symbol α (alpha). The significance levels of 0.05, 0.01 and 0.001 are common.

What is a factor model?

A model in quantopian is composed by a set of factors; usually it should include:

  • a factor for the market,
  • one or two factors for value/pricing,
  • and maybe a factor for momentum.

Now let’s come back to Quantopian Single Alpha factor Modeling.

It is basically to define and evaluate individual expressions which rank the cross section of equities in your universe. By applying this relationship to multiple stocks we can hope to generate an alpha signal and trade off of it.

This can be done in 2 ways:

  • Manually: Hand crafted alphas. By the moment I will start with this method.
  • Deep Learning: alphas are learned directly, instead of defined by hand (Long-short term memory (LSTM), 1D convolutional nets). I will let this method for later.

Notes:

  • Developing a good alpha signal is challenging (for instance: detect an earning surprise before the formal announcement based on sentiment data).
  • It’s important to have a scientific mindset when doing this exercise.

By being able to analyze your factors in IPython Notebook you can spend less time writing and running global back-tests. It also enables you to annotate assumptions and analyze potential bias.

This is in deed the main function of Alphalens python package: to surface the most relevant statistics and plots about a single alpha factor. This information can tell you if the alpha factor you found is predictive. These statistics cover:

  • Returns Analysis.
  • Information Coefficient Analysis.
  • Turnover Analysis.
  • Sector Analysis.

3.Alpha Combination: you basically combine many single alphas into a final alpha which has stronger prediction power than the best single alpha. Two examples about how to do it:

  • Classifier (E.g.: SVM, random forest).
  • Deep Learning: alphas are learned directly, instead of defined by hand (Long-short term memory (LSTM), 1D convolutional nets).

For simplification I have started just with 1 alpha factor, so I am right now skiping this step.

4.Portfolio Construction: implement a process which takes your final combined alpha and your risk model and produces a target portfolio that minimizes risk under your model. The natural steps to perform it are:

  • Define objective: what you want to maximize.
  • Define constrains: such leverage, turnover, position size…
  • Define risk model: define and calculate the set of risk factors you want to use to constrain your portfolio.

5.Execution: implement a trading process to transition the current portfolio (if any) to the target portfolio.

Trading view pros and cons

I have been testing Tradingview for a month, doing different scripts with Pine editor and performing some backtesting annotating results, and writing assumptions, parameters…

What is really nice

  • Data from whatever market you can think.
  • You can jump from one value to other, you can visually navigate at all levels with a very good time response. The way to draw and play with standard shapes is quite impresive.
  • Pine editor is really nice, the learning curve is very short and with few hours of learning you can build thousand of things.
  • The community of people sharing ideas, scripts is very useful.
  • Timing indicator adjusted to the interval you want. For instace you can define intervals as 7 minutes, 33 minutes and so on.

What I miss

  • Pine editor should enable to package functions and enable you to play with a function with different parameters in an automated way. For instace to scan the best use of parameters.
  • Pine editor should enable you to plot outside of the main screen. The context is always the value you have in the screen, I would like to have the possibility to plot outside of that context. For instace do a simple code that scans the best use of parameters on my strategy.
  • Strategy tester: the list of trades, I can only read it, I cannot work on that data (for instance to export to excel), so the analysis of results is difficult and it’s very tedious work.
  • I cannot use other values as input for my strategies. For instance, I would like to use one value of the oil industry as input to define a signal for trading a chemical company. On Pine editor I can only work with data from the current

Bubbles

This picture simplifies the theorical stages of a bubble:

If you look for bitcoin bubble versus other bubbles you will find so many of draws done to compare this bubble with the other ones.

The funny thing is that depending of the message the newspaper/blog/author wants to sell to you, you will find a different draw.

I have seen examples where:

  • Tulip bubble is bigger than bitcoin bubble and viceversa.
  • Etherium bubble is bigger that bitcoin bubble.
  • Bitcoin rise and fall just done in 1 year (c’mon guys bitcoin started before 2017!!)

what you can never find is how the draw was done, so you can compare the figures properly.

Tradingview, Pine editor, SMA (6,70)

This code below has 2 interesting things:

  • Calculate the SMA for 6 days and 70 days.
  • Define a period of time for your backtesting

//@version=3

strategy(“SMA – 6d – 70d”, overlay=true, initial_capital=1000)

// === BACKTEST RANGE ===
FromMonth = input(defval = 1, title = “From Month”, minval = 1)
FromDay = input(defval = 1, title = “From Day”, minval = 1)
FromYear = input(defval = 2012, title = “From Year”, minval = 2014)
ToMonth = input(defval = 1, title = “To Month”, minval = 1)
ToDay = input(defval = 1, title = “To Day”, minval = 1)
ToYear = input(defval = 2018, title = “To Year”, minval = 2018)

// === SERIES SETUP ===
buy = crossover(sma(close, 6), sma(close, 70))
sell = crossunder(sma(close, 6), sma(close, 70))

// === ALERTS ===
strategy.entry(“L”, strategy.long, when=(buy and (time > timestamp(FromYear, FromMonth, FromDay, 00, 00)) and (time < timestamp(ToYear, ToMonth, ToDay, 23, 59))))
strategy.close(“L”, when=(sell and (time < timestamp(ToYear, ToMonth, ToDay, 23, 59))))
plot(sma(close, 6),”SMA 6″, orange)
plot(sma(close, 70),”SMA 70″, navy)
plot(close,”price”, red)

Pine editor, RSI + Bollinger Bands

The entry script done in Pine Editor (trading view)

//@version=3
strategy(shorttitle=”joapenBB”, title=”joapen Bollinger Bands”, overlay=true)
/////////// inputs //////////
// RSI
length = input(14, minval=1)
overSold = input(25, minval=1)
overBought = input(75, minval=1)
price = close
// Bollinger Bands
src = input(close, title=”Source”)
mult = input(2.0, minval=0.001, maxval=50)
basis = sma(src, length)
dev = mult * stdev(src, length)
upper = basis + dev
lower = basis – dev
/////////// long and short conditions //////////
bbLongCondition = crossover(close, lower)
vrsi = rsi(price, length)
if (not na(vrsi))
if (crossover(vrsi, overSold) and bbLongCondition)
strategy.entry(“Long”, strategy.long, comment=”Long”)
if (crossunder(vrsi, overBought))
strategy.entry(“Short”, strategy.short, comment=”Short”)

plot(basis, color=red)
p1 = plot(upper, color=blue)
p2 = plot(lower, color=blue)
fill(p1, p2)

The outputs of the sample backtest:

LTCEUR (Coinbase):

  • share Ratio = 0.516 (1 minute)
  • share Ratio = 0.837 (7 minutes)
  • share Ratio = 0.808 (3 hours)
  • share Ratio = 0.814 (133 minutes)

ETHEUR (Coinbase):

  • share Ratio = 0.26 (1 minute)
  • share Ratio = 0.113 (7 minutes)
  • share Ratio = 0.88 (3 hours)
  • share Ratio = 0.634 (133 minutes)

Trading view Pine Editor, hello world

Reading the book Machine Trading from Ernie P. Chang, on the first chapter it offers different oppinions about environments to gather historical data, do backtesting…

I started to analyze which one of the solutions was better to cover the whole picture proposed in the book. My analysis was basically to compare Tradingview and Ninja Trader.

I started to evaluate Quantopian, as it covers backtesting and the environment to develop is Perl on Notebook (which I am familar with), but I discarded it.

As conclusion, for my initial steps on backtesting I have selected Tradingview as tool to start building backtests scripts.

This one is the first one. It combines a simple strategy between RSI and MACD.

//@version=3
strategy(“Test-1 RSI”, overlay=true, initial_capital=1000, currency=’USD’)
/////////// inputs //////////
// RSI
Length = input(14, minval=1)
Oversold = input(25, minval=1)
Overbought = input(70, minval=1)
// MACD
fastLength = input(12)
slowlength = input(26)
MACDLength = input(9)
/////////// individual long conditions //////////
// RSI
rsiLongCondition = rsi(close, Length) < Oversold
// MACD
MACD = ema(close, fastLength) – ema(close, slowlength)
aMACD = ema(MACD, MACDLength)
macdDelta = MACD – aMACD
macdLongCondition = crossover(macdDelta, 0)
/////////// long condition //////////
// RSI and MACD
if (rsiLongCondition and macdLongCondition)
strategy.entry(“Long 1”, strategy.long)
/////////// individual short conditions //////////
// RSI
rsiShortCondition = rsi(close, Length) > Overbought
// MACD
macdShortCondition = crossunder(macdDelta, 0)
/////////// short condition //////////
if (macdShortCondition)
strategy.close(“Short 1”)