Economics

JAVA: VaR – BitCoin/USD

VaR – value at risk – is a risk measurement used in financial markets, risk management and financial reporting. So, simply said, VaR shows how much you are most likely to lose in the worst days of trading. The advantage of VaR is that is simple and intuitive (and is used for a bunch of stuff, mostly to calculate losses that can be incurred by having some assets and liabilities in foreign currencies). To calculate VaR you must specify a probability of that loss, usually between 1% and 5%. VaR for a specific number of days ahead is calculated using this formula:

VaRvolatility * quantile * portfolio size * sqrt(days ahead/days in year)

For most calculations for days in year, people use 252 – working days, as currency exchange rates remain unchanged during weekend days, but for BitCoin/USD exchange rate we’re going to use 365, because there is no diminished activity on the BitCoin/USD market during weekends. The confidence level we’re going to use is 95% ( so the quantile corresponding to a 95% probability is 1.65, you can find this out using statistics table or the NORMSINV function in Microsoft Excel) and we’re going to say that our portfolio consists out of 200 BitCoins. Also, we’re going to suppose that we want to know the VaR for the next 10 days:

VaRvolatility * 1.65 *  200BTC value in USD * sqrt(10/365)

Next step, is calculating the volatility:

σ = standard deviation of return * sqrt(365)

standard deviation:

σ of return = sqrt[1/N * power(sumof(x – average), 2)]

As we can see, VaR has no specific theory behind or calculations, it just uses the volatility for a specific period to anticipate future movements of the BTC/USD rate. First thing we’re going to do is to get the daily BTC/USD rate for the past year and calculate the standard deviation, then the volatility. We’re multiplying the standard deviation to the square root of 365 because variance increases linearly with time, so the standard deviation is the square root of variance and time.

Here’s how it looks in Java (we’re using data provided by CoinDesk.com):

package com.wordpress.breekmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.Map;

import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;

public class Main {

	public static void main(String[] args) {
		StringBuffer text = new StringBuffer();

		// declaring and initiliasing variables
		double sumOfReturn = 0d;
		double averageOfReturn;
		double std_dev;
		double annualVolatility;
		double VaR;
		double portfolioValue = 0;

		ArrayList<Double> list = new ArrayList<Double>();  // the list of daily BTC prices
		ArrayList<Double> returnList = new ArrayList<Double>(); // the list of daily BTC price evolution, named as return
		// Return = Price of day n divided by price of day n-1, in %

		Calendar end = Calendar.getInstance();
		end.add(Calendar.DAY_OF_MONTH, -2); // we substract 2 days because the data may not be updated to latest day

		Calendar date = Calendar.getInstance();
		date.add(Calendar.YEAR, -1); // we substract depending on the period we want to calculate the volatility for
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		try {
			// creating the URL using StringBuffer
			StringBuffer urlBuffer = new StringBuffer();
			urlBuffer.append("https://api.coindesk.com/v1/bpi/historical/close.json?start=");
			urlBuffer.append(df.format(date.getTime()));
			urlBuffer.append("&end=");
			urlBuffer.append(df.format(end.getTime()));
			URL url = new URL(urlBuffer.toString());
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null ) {
				text.append(line);
			}
			reader.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		//parsing the JSON data
		JsonParserFactory factory = JsonParserFactory.getInstance();
		JSONParser parser = factory.newJsonParser();
		Map data = parser.parseJson(text.toString());
		Map prices = (Map) data.get("bpi");

		// calculating portfolio data using latest prices
		portfolioValue = 200 * Double.parseDouble((String) prices.get(df.format(end.getTime())));

		while (date.before(end)) {  // looking up each date in the parsed data and getting the price
			list.add(Double.parseDouble((String) prices.get(df.format(date.getTime()))));
			date.add(Calendar.DAY_OF_MONTH, 1);
		}

		for (int i = 1; i <= list.size() - 1; i++) { // calculating daily return and adding it to the return list
			returnList.add(list.get(i)/list.get(i-1)*100 - 100);
		}

		for (Double returnValue : returnList) { // getting the sum of returns
			sumOfReturn += returnValue;
		}

		averageOfReturn = sumOfReturn/returnList.size(); // calculating average of returns
		std_dev = getStdDev(returnList, averageOfReturn); // standard deviation using the method
		annualVolatility = std_dev * Math.sqrt(365d); // transforming standard deviation in annual volatility
		VaR = annualVolatility/100 * Math.sqrt(10/365d) * portfolioValue * 1.65;  

		Locale usd = new Locale("en","US");
		NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(usd);
		System.out.println("Value at risk for 200 BTC during next 10 days equals " + currencyFormat.format(VaR)); //
	}

	private static double getStdDev(ArrayList<Double> list, double average) {
		Double sumOfDiff = 0d;
		for (Double returnValue : list) {
			sumOfDiff += Math.pow(returnValue - average, 2)/list.size();  // formula of standard deviation
		}
		return Math.sqrt(sumOfDiff);
	}
}

Indeed, VaR based on historical data is the simplest way to do it, but also the least precise and most primitive way to do it. There are a lot of different ways to calculate VaR, like using Monte Carlo or some additional conditions.

Bitcoin price with WinkDex API (in JavaFX) – Part II

As previously mentioned in this post, WinkDex API allows users much more than simply get the price and timestamp from their site. You can also get a series of prices and dates and build your own Bitcoin price chart easily and this is what I’m going to show you in current post. (more…)

Term of the day: White Elephant

One of the most interesting terms in economy is ”White Elephant” and it came from a traditional Asian practice when people that were disliked by the ruler received an white elephant (albino) which was considered sacred and it was forbidden to put it to work. Same in economy, an ”white elephant” is an asset or investment that is very costly to maintain and it is not profitable at all.

A very good example of an ”white elephant” asset is the Enron Dabhol power plant in India, that due to political reasons, was unused by the company and never made a cent of revenue to the company that built it in the middle of nowhere.

Bitcoin price with WinkDex API (in Java) – Part I

WinkDex offers developers a tool (API), so that developers could get the most accurate Bitcoin price at the moment and in the past so that the latter could create web apps or even phone apps showing information about Bitcoin market. Their documentation offers example of API implementation using cURL – A command line tool for getting or sending files using URL syntax (Source: wikipedia), which is mostly used with php.

(more…)

Monte Carlo Method (Part III – Option pricing)

Now that we are familiar with both the Monte Carlo Simulation and option concept, we can move on to determining a way to apply Monte Carlo in option pricing. The are a numerous option pricing models, each with specific assumptions that apply to specific option types, but the most famous is the Black-Scholes model and we will cover this model at a later date in order to compare the results of Monte Carlo Simulation to the results obtained by applying Black-Scholes model (which is believed to be one of the most exact option pricing model).

We’re going to apply the Monte Carlo simulation to calculate the value of an European call option (an options that gives the right to buy shares only at a specific date in the future!), because Black-Scholes can be applied only to European options (one of its limits) and we have to be able to compare the results and see the error rate.

(more…)

Monte Carlo Method (Part II – Financial derivatives)

Before we move on to applying the Monte Carlo Method (or Monte Carlo Simulation) to calculating the value of financial derivatives, we have to understand very well what is a financial derivative, what kind of financial derivatives exist, differences between them and what factors actually influence the value of a financial derivative.

Simply put, derivatives are one of the three financial instruments: stocks (equities and shares)  and debt (for example: mortgages and bonds). A derivative is a contract and like every contract it ensures to the parties some rights and obligations and it has a value. The object of this contract is called an ”underlying” and it can be an asset or an interest rate. So basically, the subjects (parties) of this contract are ”making a bet” over the value of an asset, an index or an interest rate (to be more specific, over the future value of the asset, index or interest rate). They do so from different reasons: to protect themselves from price movements (called hedging) or to speculate from this price movements and earn money.

(more…)

Monte Carlo Method (part I)

Today, I’m going to explain as simple (and as thoroughly) as possible a method used in a lot of areas for different computations and for obtaining number results based on random samples. I’m not just going to explain it, but also show how to apply this method in Java (if someone wants the Python version, just let me know in the comments section).

So, what’s Monte Carlo Method? Well, according to wikipedia, Monte Carlo method is used mostly in physical and mathematical problems and is very useful when it is difficult or impossible to apply other mathematical methods. Not very clear, is it? In a (very) simplified version, Monte Carlo can be explained like this: a method that uses randomly generated numbers to calculate something. This method is used in mathematics, physics, engineering, finance, AI development etc, but I am more interested in it’s financial applications, financial derivatives and investments evaluation to be more precise. There is no consensus on how Monte Carlo should be defined, so it will be easier just to show you. It is important to know that usually Monte Carlo methods works with pseudo-random numbers as well.

(more…)

Faircoin

FairCoin logo

You like Nextcoin? Well, you’ll definitely like this coin as well. Some people were saying about Nextcoin that it was unevenly distributed , making it difficult to small investors to compete with big ones. Using PoS, it is indeed hard to forge any coins if your stake is only a couple hundred coins.

Seeing this as a disadvantage of Nextcoin, the founders of Faircoin decided to distribute to everyone who gets an address (49750 people at most) during first 5 days. This means, everyone will get at least 1000 coins ( 5 million cap – 0.5%, divided by 49750 addresses). The rest of 0.5% are kept for bounties and supporting the community.

Here are some technical specifications:

  • 50,000,000 premined coins
  • Flat 6%/year minting reward, halving every year until baseline of 1.5%
  • 30/90 days min/max weight
  • 10 minutes block target
  • 30 minutes difficulty retarget
  • 0.001 coin mining reward

The launch is going to be in about an hour, so check it out! You may be pleasantly surprised!

Rubycoin – A precious gem for the digital age

Rubycoin logo

Recently, mid-february, a new coin has been launched – Rubycoin. As I said before, most people trading coins are not professionals that read charts all day long, study source code and technical specifications. But, this group of people is the one that really makes the price fluctuate, as per their behavior. Although, there are ”professionals” all over the web throwing predictions about the future of some coins that are influencing the outliers (of cryptocurrency business), it is still the personal opinion and feeling of ”amateurs” that decide the future of a coin.

Now, Rubycoin insipres confidence. It has a beautifully designed logo, a Windows and Mac wallet (as well as the source code), a really cool website and some good promo videos. I believe this is enough to get people’s attention and make them interested.

As soon as you get interested you need to find out more about it, how transparent is it, how active is the community and dev team and maybe some technical specs. Well, here it is:

  • The Rubycoin team is extremely active and invested in this project;
  • The community responded real well to this coin and really invested, with already a dozen pools, exchanges, faucets, articles, games etc developed;
  • The cap is exactly 60 000 000;
  • The premine is 1.2 milion (2% of the total amount possible) used for development and marketing purposes;
  • Difficulty retargets every block;
  • Block reward for the first 5 months is going to go down like this – 500, 250, 125, 75, 50.

Although there are some accusations towards the devs for the last few days, just take a minute and check it out:

http://rubycoin.org/

https://bitcointalk.org/index.php?topic=459622.1600

Heavycoin

Hey, guys! Browsing bitcointalk.org for some new, interesting and full of potential cryptocoins I stumbled upon HeavyCoin (HVC).

A coin launched without any innovations is already failed. Not in this case, considering the new stuff HVC brings to the table. The founders of HVC claim that it is one of the most secure coins at the moment and it sounds like truth to me, considering their 4 functions combined in a secure way. Although I have nothing against pre-mined coins, I think it is a good ideea to premine only 1-2% for maintenance and development and leave the rest to mine, this way ensuring a transparent and decentralized mining community. Now, here it gets interesting. This coin’s cap is not established yet, but is expected to be somewhere between 63 000 576 and 128 000 000. Actually, this coin promotes democracy, so the cap will be decided by votes. Also, your vote could decide the max block reward (not more than 1024, but how cool is that?!).

One more thing, HVC is an adept of CPU-only mining and proof-of-work. Reading carefully about this coin, you kind of see it has a special “personality”, it just stands out among others.

Soon, the IPO is going to end (since it started on 17th of February), so if you are interested you can still invest, but hurry up! IPO is over on 3rd of March. As of now, the total amount of investment is around 163 BTC, so you could easily get a good share.

Anyhow, keep an eye on this coin. I’ve got a really good feeling about this.

The PRE-ANN thread:

https://bitcointalk.org/index.php?topic=470391.0