Category: API

Use-cases, tutorials, sample code and videos on the StockViz API

A Simple Bollinger Band Trading Model

Bollinger Bands have quickly become one of the most commonly used tools in technical analysis. Bollinger Bands consist of three bands – an upper, middle and lower band – that are used to spotlight extreme short-term prices in a security. The upper band represents overbought territory, while the lower band can show you when a security is oversold. Most technicians will use Bollinger Bands in conjunction with other analysis tools.

A simple BBand strategy is buying stocks that break the lower Bollinger Band. It is expected that the price of the stock will revert back above the lower band and head toward the middle band.

You can build you own Bollinger Band based strategy that scans all the Nifty 50 stocks for a potential break using the StockViz Technical API in a few lines of code.

# get the index constituents and loop through them
constituents = common.getConstituents("CNX NIFTY") 

for cc in cleanConsts:
     ticker = cc["SYMBOL"]
     # get the latest technicals
     techs = common.getTechnicals(ticker) 
     t = techs[len(techs)-1]
     # get the latest price
     price = common.getLivePrice(ticker)

     #make the decision
     if t["BB_DN"] > price:
		#there was a breakdown

		print "Buy:", ticker
		common.placeTrade(ticker, 1, "buy")

You can read the whole code on GitHub

Source: investopedia

Related

Calculate PEs for all Indices

index PE

Some investors like to use the PE ratio of an index to time their entry and exit. This is especially true about the widely tracked Nifty 50. However, there are advantages to rolling your own.

Annual vs. Quarterly EPS

The most popular approach of calculating PE is by dividing the price by the last reported annual EPS. This is probably fine most of the time. However, we prefer to add up the last 4 diluted quarterly EPS so that we have the latest numbers.

Closing vs. Live Prices

Once again, a matter of preference. Since most data points present the PE based on the last close, it may be useful to calculate it based on the live price, just to see the difference.

Other indices

Whereas the Nifty index PE can be obtained from a number sources, what about the other indices? And sector-wide PE estimates? By having a script handy, you can always have a ready reckoner of where things stand.

The Code

The StockViz API exposes the QuarterlyEps endpoint that returns the quarterly basic and diluted EPS in descending order of periods. You can use this to calculate the annualized number, grab the live price and adjust it by the stock’s weight within the index to arrive at the index EPS.

for cc in constituents:
	ticker = cc["SYMBOL"]
	#print ticker,

	price = common.getLivePrice(ticker)
	#print price,

	epss = common.getEps(ticker)

	annualEps = 0
	for i in range(0,4):
		annualEps += epss[i]["EPS_DILUTED_AEI"]

	#print annualEps, price/annualEps

	if annualEps != 0:
		indexPe += price/annualEps * cc["WEIGHTAGE"]

	indexPe /= 100

You can download the entire code on GitHub.

Previously

A Stochastic-MACD Model for Trading Nifty Stocks

Glenda Dowie has an interesting post up on investopedia:

Looking for two popular indicators that work well together resulted in this pairing of the stochastic oscillator and the moving average convergence divergence (MACD). This team works because the stochastic is comparing a stock’s closing price to its price range over a certain period of time, while the MACD is the formation of two moving averages diverging from and converging with each other. This dynamic combination is highly effective if used to its fullest potential.

To derive a buy signal out of these two indicators, first make sure that the MACD is trading over its signal line and then make sure that the %K crossed the %D in the last couple of days.

The problem with any multi-signal approach is that it requires you to track multiple stocks:

Because the stock generally takes a longer time to line up in the best buying position, the actual trading of the stock occurs less frequently, so you may need a larger basket of stocks to watch.

This is where you can use the StockViz API to make life simpler.

The StockViz Technical API for Equities (doc) gives you more that 50 technical stats to play with. The stochastic fields are “STOCH_FAST_D” and “STOCH_FAST_K” and the MACD fields are “MACD” and “MACD_SIGNAL.”

Here’s how it works.

Pseudocode

In order to scan all the Nifty 50 stocks:

  1. grab all the constituents of the index through the SymbolsOfIndex endpoint
  2. iterate through them and get the technicals
  3. check if the MACD is over the signal line. If it is, then check if the stochastic cross-over occurred over the last couple of days
  4. If both the conditions are met, then place the trade

Code

You can find the code on GitHub. We have extracted some shared code out into a “common” module. The main file reads much cleaner this way.

The code should be run at the beginning of the day and you can track the progress of this system through your StockViz account.

Stocks picked up today

stochastic-macd portfolio 20.02.2014

Note: You have to link your Mashape and StockViz accounts for the Accounts API to work (doc.)

Previously

 

Building a Cross-Over Trading System

Investors often use moving averages to time their entry and exit into the markets. One of the most often used signals are the “Golden Cross” (for entry) and the “Death Cross” (for exit.)

The Golden Cross represents a major shift from the bears to the bulls. It triggers when the 50-day average breaks above the 200-day average. Conversely, the Death Cross restores bear power when the 50-day falls back beneath the 200-day.

The problem with most technical signals is that it requires you to inspect a chart of the stock you are interested in. However, with the StockViz API, you can automate just about every step of the process from checking for the cross-over to placing the trade.

Technical API

The StockViz Technical API for Equities (doc) gives you more that 50 technical stats to play with. Here’s how you access it in python:

unirest.get("https://stockviz.p.mashape.com/technicaldata/technicalsEquity",
     params={
          "symbol": ticker
     },
     headers={
          "X-Mashape-Authorization": mashape_auth,
          "Accept": "application/json"
     }
);

The result is a time-series in ascending order of dates. By comparing the last two elements, you can check if a cross-over occurred or not.

Accounts API

The StockViz Account API (doc) allows you to directly place trades through StockViz. These are “dummy” trades that update your portfolio. This allows you to track the performance of your investment strategy over a period of time.

Placing a trade is just another call to the API:

unirest.get("https://stockviz.p.mashape.com/account/OrderEquity", 
	params={
		"symbol": symbol,
		"qty": qty,
		"bs": buyOrSell,
		"t": "regular",
		"px": price,
		"asof": strTime
	},
	headers={
		"X-Mashape-Authorization": mashape_auth,
		"Accept": "application/json"
	}
);

Now all you have to do is run the script at the beginning of the day and you have your basic automated cross-over trading system. You can read the whole code here. The script runs the cross-over system for the NIFTYBEES ETF [stockquote]NIFTYBEES[/stockquote]

Note: You have to link your Mashape and StockViz accounts for the Accounts API to work (doc.)

Previously

A News Reading and Sentiment Analysis App

We previously discussed how you can pull news items for specific topics/stocks using the StockViz News API. But all that the script did was show you a link to the news item. But who has the patience to click on a link, go to the website only to get annoyed by the ads? Wouldn’t it be nice if you could just read the news then and there?

Goose

Python Goose is an open-source article extractor written in python. It takes any news article and extracts the main body of the article and also all meta data. By adding a few lines of code, you can convert the previous script into a news reader of sorts that displays just the article, minus the cruft.

4 lines of code:

import the library: from goose import Goose
initialize goose: g = Goose()
extract the article: article = g.extract(url=r[‘SOURCE’])
clean the article: cleaned = article.cleaned_text.encode(‘ascii’, ‘ignore’)

You can see the whole script here.

Sentiment

One of the advantages of Mashape is that there are number of other APIs that you can access from within your account. Most of these have a “freemium” plan, just like our API. One of these is the Free Natural Language Processing Service.

The NLP Service takes a URL and returns the sentiment (positive, negative, neutral) along with a sentiment score.

2 lines of code:

make the call: response2 = unirest.get(…)
read the sentiment: sentiment = response2.body[“sentiment-text”]

You can see the whole script here.

Now you can tailor the what, when and how of the news you want to track. You could bundle all this up with a fancy user interface. Or pipe this through a messaging API (like SendHub?) Chief ingredient: your imagination!

Previously