# my net house

WAHEGURU….!

## Monthly Archives: January 2017

## Hacker’s Guide to Quantitative Trading(Quantopian Python) Part 2

January 3, 2017

Posted by on Quantopain Provides required API functions,Data,Helpful-community as well as batteries included Web-based Dashboard to play with Algorithmic-Trading, Create Your own trading Strategies, and launch your Trading model in live Market.

Here I will only talk about code and how it should be written to create your own Trading Strategy.

There are basically Two methods.

**initialize() and handle_data()**

initialize act as initializer for various variables. same as __init__ method in Python.

Now what kind of variables we have to declare in initialize() function is dependent on your strategy. we can select limited number of stocks,days,type of trading,variables required for Algorithms.

A very simple example of initialize() code could look like as follows:

```
def initialize(context): # consider context just as 'self' in Python
context.stocks = [sid(24),sid(46632)] # sid stands for stock_id
```

initialize() also contains the stuff that can be used many times or all the times in our Trading Algorithm:

1. A counter that keeps track of how many minutes in the current day we’ve got.

2. A counter that keeps track of our current date.

3. A list that stores the securities that we want to use in our algorithm.

**Whatever variables that you define here will remain persistent (meaning that they’ll exist) but will be mutable. So that means that if you initialize context.count as 0 in initialize, you can always change it later in handle_data(). **

A Simple Example of handle_data():

```
def handle_data(context,data):
for stock in context.stocks:
if stock in data:
order(stock,1)
```

**Momentum Strategy:(Common Trading Strategy)**

In this strategy we consider Moving average price of stock as an important factor to make decision to put a security price in Long or Short.

Here is simple explanation of momentum Strategy:

**● If the current price is greater than the moving average, long the security **

**● If the current price is less than the moving average, short the security **

Now we will use Quantopian API to implement this strategy for Trading. instead, our algorithm here is going to be a little more sophisticated. We’re going to look at two moving averages: the 50 day moving average and the 200 day moving average.

David Edwards writes that “the idea is that stocks with similar 50 & 200 day moving averages are more likely to be fairly valued and the algorithm will avoid some of the wild swings that plague momentum strategies. The 50/200 day crossover is also a very common signal, so stocks might be more likely to continue in the direction of the 50day MA because a lot of investors enter and exit positions at that threshold.”

The decision-making behind Moving-average is as follows:

**● If the 50 day moving averages is greater than the 200 day moving average, long the security/stock. **

**● If the 50 day moving average is less than the 200 day moving average, short the security/stock**

So now Let’s make a Trading Bot!

1. First we have to create our initialize() function:

```
def initialize(context):
set_universe(universe.DollarVolumeUniverse(floor_percentile=99.5,ceiling_percentile=100))
```

”’Set universe is inbuilt function by Quantopian which provide us the stocks with-in required universe. Here we have selected stocks those we have DollarVolumeUniverse with 99.5% and 100% as our floor and ceiling. This means that we’ll be selecting the top 99.5 ~ 100% stocks of our universe with the highest dollar*volume scores.

Please read the comments in the code.

```
context.stocks_to_long = 5
context.stocks_to_short = 5
context.rebalance_date = None # we will get today's date then we will keep positions active for 10 days here
context.rebalance_days = 10 # it is just an assumption now for 10 days or finer value
```

Now we have defined required __init__ parameters in initiliaze() let’s move to

**handle_data()**

```
def handle_data():
if context.rebalance_date!=None: # if rebalnce date is not null then set next_date for changing the position of algorithm
next_date = context.rebalance_date + timedelta(days=context.rebalnce_days) # next_date should be that days away from rebalnce_date
if context.rebalance_date==None or next_date==get_datetime(): # if today is that day after 10 days when we market long/short for out stock
context.rebalnce_date = get_datetime() # set rebalnce_date for today so next_date will be set to again 10 days ahead from rebalnce_date
historical_data = history(200,'1d',price)
```

Get historical data of all stocks initilized in initiliaze() function, ‘1d’= 1 day,200=days,’price’=we are only fetching price details because that is only required for our strategy, may be for some strategy volume of stock could be more beneficial

```
past_50days_mean = historical_data.tail(50).mean()
past_200days_mean = historical_data.mean()
diff = past_50days_mean/past_200days_mean-1
# if diff>0 we will long if diff<1 we will short
buys = diff[diff>0]
sells = diff[diff<0]
# here we will get list of securities/stocks whose moving average will be
# greater as well as less than 0
buys.sort() # sorting buys list why? - getting top securities from top- more is better
sells.sort(ascending=False) # reverse sorting sells list - getting top seurities from bottom, less is better because we are selling agiainst market
buys = buys.iloc[:buy_length] if buy_weight !=0 else None # buy_length = number of securities we want to purchase ,
sells = sells.iloc[:short_length] if short_weight !=0 else None # short_length = number of securities we want to short
```

Now here we have buys and sells are two lists!! (remember carefully) all the decisions are going to be made based on these two lists

We can also implement risk factors in out Trading Strategy. Let’s implement minimum form of Risk-Factor, 0.02% of last_traded_price that means if security is going to much lower than that then we will exit.

We will go through each security in our data/universe and those who will satisfy condition of ‘buys’ and ‘sells’ list will be bought/sold.

```
# if security exists in our sells data
for sym in data:
if sells is not None and sym in sells.index:
log.info('SHORT:%s'%sym.symbol)
order_target_price(sym,short_weight.stop_price=data[sym].price_stops[sym])
# here stop_price is the price of security in real-time+change happend in stops
# order_target_price is inbuilt function.
# if security exists in our buy data
elif buys is not None and sym in buys.index:
log.info('Long:%s'%sym.symbol)
order_target_percent(sym,buy_weight,stop_price=data[sym].price-stops[sym])
else:
order_target(sym,0)
```

The `order_target_percent` method allows you to order a % target of your portfolio in that security. So this means that if 0% of your total portfolio belongs in AAPL and you order 30%, it will order 30%. But if you had 25% already and you tried ordering 30%, it will order 5%.

You can order using three different special order methods if you don’t want a normal market order:

```
#`stop_price`: Creates a stop order
#`limit_price`: Creates a limit order
#`StopLimitOrder`: Creates a stoplimit order
```

**How Trading Differentiates from Gambling:**

Most of times when you find that you are able to get good returns from your capital you try to beat the market, Beating the market means most of the traders tried to earn much more than fine earnings are being returned by the market for your stock, Such beating the market process can be done by various actions like reversing the momentum or looking for bad happenings in the market(which is also called finding the shit!)Some people are really good at this kung-fu but as you are just budding trader and you have only limited money of yours, So here one important thing should be remembered, **“”Protect your capital””**. – That’s what most of the Big banks do and if they will hire you as their Quant or Trading-Execution person they will expect same from you. Big banks have billions of dollars that they don’t want to loose but definitely want to used that money to get good returns from market.

So they follow one simple rule for most of the times.

**Guaranteed returns even if those are low.**

[Make sure returns should be positive after subtracting various costs like brokerage,leverage etc, Because getting positive returns by neglecting market costs is far easy but such strategies should not be used with real money.]

So the real key is think like a computer programmer at first place, something like it should work at first place, so first thing to make sure is getting returns even low but stable returns by calculating various risk-factors.

I am quoting some of informative things from SentDex Tutorial:

Most individual traders are trading on account sizes of somewhere between maybe $25,000 and $100,000 USD, so their motives are to hopefully increase that account size as much as possible, so this person is more likely to take part in High Risk High Yield (HRHY).

Most people who use HRHY strategies, tend to ignore the HR (High Risk) part, focusing on the HY (High Yield).

**The same is common with gamblers,even over astronomical odds with things like the lottery.**

In other words, always ask yourself – what’s about the market that makes my strategy work? Because, at the end of the day, algorithmic trading is more about trading than about algorithm.

## Hacker’s Guide to Quantitative Trading(Algorithmic Trading) Part 1

January 3, 2017

Posted by on **Quant-ita-tive Analytics:**

Word Quant is derived from Quantitative Analytics. In present system finacial market is very heterogeneous in nature, With coming of many private banks in financial sector

now most the private banks also invest their account holder’s fund into the stock market as a safe trading, with very low but almost guaranteed returns(money they earn from trading

There was an exception of this ‘safe investment’ term used by banks when whole economy crashed and millions of people suicided,lost their homes,lost their jobs,lost their lives

as well as most the small countries like in Europe like greece,____,____, were almost finished.

**Main reason of this whole disaster happened in digital age was due to ‘not looking into data properly’**.

Now we can also use term Quantitative Analytics is process where a

person/Mathematician/Expert/Data Scientist/Computer-Programmer(with domain specific knowledge) parses,analyses and develops results from MBs , GBs or sometimes TBs of data to produce results those results are based on history of trading. Such results helps BIG banks or big investors in the Financial market to build trading Strategies with the target to gain maximum profit from trading equities or at-lest to play safely with their money which results low but assured returns.

**Statistical science Plays an important role in study of Quantitative Analytics:**

Statistical Science deals with every aspect of our life. Before going further into Statistical science we have to understand the meaning of ‘Statistics’.

According to Dictionary of Statistical terms:

**“”Numerical data relating to an aggregate of individuals or the science of**

**collecting,analyzing and interpretation such data.””**

There are various Statistical methods those are used to analyze the data which is Quantitative(HUGE with number of variables or SMALL with number of variables and Quant’s job is to analyze how those variables are correlated) in nature for example: **using grouping,measures of location:average-mean,median,mode,,**

**measures of spread-range,variance and standard deviation,skew,identifying patterns, ****univariate and multivariate analysis, comparing groups,choosing right test for data.**

**Word Quant comes from:**

Word Quant come from the the person who use Mathematical formulas and machine learning techniques to predict output of stock market. There are various other profiles as well, Like Quant Developer- Trading strategy written in steps(not programming) is provided to programmer with domain specific knowledge of financial system.

it is job of Quant developer to convert Trading Strategy into Live Trading System(System that buy or sells stocks,options,futures to get profit from market).

**Mathematician and Quant:**

The relationship between Quant and Mathematician is quite close or in some sense

it can be stated that Quant is the person having fun in real life with Mathematics. Quant calculate various factors while implementation an algorithm/equation in real-time trading system. with showing results to other people in the form of graphs rather than complicated equations of significances.

So in some sense Quant uses serious Statistics to get sense out of data and tell people why his/her trading strategy is better to produce profit from the financial market. As a Quant developer only job is to write code for equal

Algorithms those are being used but as a Quantitative Analytics we can assume one has to have various skills of statistics which help to make sense out of Stock-Trading-Data.

**Process(!steps) of doing Quantitative analytics:**

**Take Care of Data**: At first as a analyst you should not get yourself lost in the data.

**Frequency Distribution**: Find frequencies of occurring values against one variable.

Histograms are best for Frequency Analysis.

**Find Descriptive Statistics**: We can use Central tendencies(mean,median,mode) and

dispersion(range,standard deviation,variance) to learn more about data.

**Comparing means**:Need to perform various tests on your Data like T-Tests.

**Cross Tabulation**: Cross tabulation tells what are the relations among different variables.

**Correlations**: Find relationship between two variables

** Never mix Correlation and Cross Tabulation between your thoughts.

**Trading Strategy/Algorithm:**

When Traders buy/sell stock/options/future in trading market based on various calculations to make decisions, Combination of such decisions is called Trading Strategy. Strategy can be built applied without using any Programming Language. In Algorithmic trading A Quant+developer come up with self-running computer program(Trading Strategy/Quantitative model) that is built based upon various trading decisions to automate

whole process of buying/selling stocks.

Tips and Tricks while building Quantitative models:

* Important things about Your Trading model is it should be good on Back-testing(Make sure back-testers will be different for stocks as well as for futures) but as well as it should be as good on forward testing(paper trading).

* You need Separate Model for Separate Trading. Trading model(Strategy) working at Bitcoin Market will not be beneficial for Stocks.

* You should run Strategy as an experimental Project for various Days to get data from results, Read the data and refine the Strategy.

* Every Strategy is sort of sensitive to various risk factors.

* Think about **risks** , Think about Eliminations.

* Run Multiple models at same time, Some will loose some will win.

* One strategy is not enough , Strategies loose it’s Efficiencies after certain period of time.

* Back-testing is not always true. Never try to create model that matches 100% to your back-testing because that would be over-fitting rather than try to create generalized/simple models which will be more effective to predict abrupt changes in the live-trading.

* What actually happens is strategies are catching strategies.

* Right now every Strategy need a human to operate.

* If we know what kind of shields we have given our model we will get to know that either such kind of things those are coming in-News can effect

our strategy.

* Only Human is not well enough to do trading by it’s own. We must use trading strategies to come out as great trading with profitable returns.

* Diversification of Strategies are as important as required.

* Momentum trade’s behave is somewhat in loss and sometimes very ”good” Profit, Because on Momentum we try to find what’s hot in market and that hot could go so high as well as so low.

* A trading model may not take consideration of Earth-Quake, some kind of Govt. fall into any country but humans can.

* Now using the Sentiment Data analysis tools we can incorporate news while building a strategy but for most of the backtesters does not contain that news data to check performance of strategy. So if you say news data record will increase the chances of working that might not be true all the time.

* Sometimes using a news data as input can cause overwrite of entire model because ‘news are not true always’ 🙂

* Keep reading new Ideas on Blog Posts, Look for interesting Books.

* Learn how to interpret the live market.

* As in the programming we say it mostly does not work at the first time, that is also true with trading strategies. 🙂

* Back-test is at-least good not to give -ve results, Highest the Sharp ratio great is the significance of strategy.

* Data you use to build your own strategy is equally important as important as the factors you are considering to build your model.

* You could come to situations where you feel either you need to stop usage of perticular strategy or modify it.

* Back-test is null Hypothesis.We assume that at this specific case our model is accurate.

* Always concentrate on Sharp Ratios.

* Quantitative Trading is suitable for technically anybody. Quantitative Trading could be slow or Fast, One does not need to be a Math Ninja or Computer Wizard to do Quantitative Trading.

* It is always good to start with Simple Strategies present in Public Domains, implement those, run tests, tune,Play and get rich, 🙂

* It’s better if you go with Open-Source Languages because those can very easily turn into live trading systems.(Python or C++)

* Choosing a standard Language is always a great idea because wide range of library support is there to build things! 🙂 😀 * (Python)