Saturday, 27 July 2013

Mutual Fund Basics

What do we know about mutual funds?

I think what everyone knows about mutual fund is that “Mutual funds are subjected to market risk. Please read your offer documents carefully before investing”.

What are the market risks mentioned here? Are mutual funds subjected only to market risks?


Market risks includes risk associated with equity investments, change in interest rates, foreign exchange risk, commodity risk etc. If mutual funds are subjected only to market risk, then how would different funds perform differently? Aren’t they all supposed to be performing same way for at least mutual funds in same sector? Here comes the role of fund manager and his approach. This is also one of the key aspects of performance of a mutual fund. The key to a mutual fund is how the fund manager mitigates the market risk without impacting the performance of the fund scheme. The role of a mutual fund manager includes selecting the stocks that will deliver, diversifying the schemes and everything possible to do the balancing of risk Vs return.

Importance of market research

Even if we want to invest in shares of only one company we need to do lot of research before taking a decision. It takes lots of time and effort. The concept of mutual fund has significance at this context. 

Mutual Funds are kind of collective investment schemes, which are professionally managed by a Fund manager. The money for a mutual fund is pooled from many investors and is invested in stock, bonds short term money market instruments and other securities. Mutual funds are relatively less expensive as with minimum investment amount investor gets maximum diversification. 

Net Asset Value (NAV) of Mutual Fund:

NAV is the per share market value of a mutual fund. While buying a mutual fund, the number of shares are allotted by dividing the invested money with NAV. 
NAV of a mutual fund is calculated as below:
(Total value of all the cash + securities -   liabilities if any)/Number of shares. 
An NAV computation is undertaken at the end of each trading day based on the closing market prices of the portfolio's securities. Liabilities would include charges for fund manager and his team.

Setting Up a Mutual Fund

Mutual funds have got a 3 tier set up. First the sponsor who wants to set up a mutual fund approaches SEBI (Securities and exchange board of India). SEBI does a back ground check of personal integrity and financial sector experience etc and gives the approval. Sponsor then set up a public trust under Indian trust act 1882. According to this act it’s not a legal entity. So trustees act on behalf of them. Once after this trust is registered with SEBI it’s known as Mutual fund. The last level is AMC (Asset management company). Actual money management of investors are done by AMC.
When a new scheme is launched, it is known as new fund offer or NFO.

Investment Procedure

First the investor has to fill the NFO available with the distributor. He is supposed to read the offer document (OD) thoroughly. At least he should read the key information memorandum (KIM) available with the application. Investor has to give the cheque or draft (MF cannot collect cash). Mutual fund will give this cheque to the corresponding bank in which it has the account.

Different Type of Investment Plans:


Lump Sum Investment Plan or One Time Investment Plan: In this type of investment plan, the whole amount is invested as lump sum in a single go. This type of investment plan has got higher risk depending on the market performance from the time of buying the mutual fund.

Systematic Investment Plan (SIP): In this type of investment plan, the investment is done in instalments. There will be an effective averaging of NAV (Net Asset Value) of the mutual fund in this type of plans. So, the risk will be lesser in case of SIPs due to averaging of NAVs of various instalments. At the same time, you may be loosing on potentially higher returns of one time investment based on market performance.

Different Type of Mutual Fund Products:


Equity fund products are comparatively riskier one and the probability of higher return is also more in this case. This product can be either open ended or closed ended. Open ended products allow the investor to enter and exit the scheme at his convenience. But in case of closed ended product the investor can invest only during the NFO period. And even the redemption also happens only after the specific period mentioned in the scheme.
In equity funds, Index funds are considered as the safer one as it’s a diversified and large cap fund. It’s a passively managed one. But sector funds come under the risky category.
Again based on market capitalization equity funds are divided as

  •  Large cap-Stable and safe top 100/200 actively managed companies.
  •  Mid cap- more expense to do the market research.
  •  Small cap- relatively higher risk
The commonly knows equity fund linked schemes are growth scheme and value scheme. Growth schemes invest in the stocks of the companies where the growth is expected more than the average. But in case of value scheme the investment is done in relatively low profile companies and expecting the stock price to grow over years.

Exchange Traded Funds (ETFs)
These are the mutual fund units which investor buy or sell from the stock exchange. Here the AMC deal with the APs (Authorized Participant) few designated participants. This is comparatively less expensive and investor require one demat a/c for the trade. It can be on the basis of gold, silver, indices etc.

  • Gold Exchange Traded Funds (ETFs): Here the investment is in gold or gold related securities. This is as good as buying gold where there is no treats as keeping gold. Upon maturity investor can realize this on the prevailing rate of gold ETFs. Here again we have a custodian who does the safe keeping of physical gold.

Debt Funds
These are relatively safer funds. Debt market in India is not an easily accessible one. So mutual fund industry helps the investor to trade in debt instruments. The two major risks in the debt securities trade are interest rate risk and credit risk. The interest rate risk can be overcome by investing in relatively short duration schemes. The credit risk arises mainly when the borrower turns to bankrupt. To overcome this there are credit rating agencies like CRISIL and ICRA which gives the rates from “AAA” to “D”(defaulter).
Price in a bond is calculated as the present value of future cash flow. YTM (“Yield to Maturity” denotes the rate applied to future cash flow.

     Different schemes available are mentioned below:

  •  Fixed Maturity Plans- it’s a closed end scheme where the investor is assured of fixed income.
  •  Capital Protection scheme - Here a portion of the fund is invested in debt instruments and other portion in derivative instruments like options.
  •  Gilt funds- This scheme will invest only in the securities issued by government. It’s safer one.
  • Balanced/hybrid funds - here 50% investment tin debt instruments and other 50% in equity schemes.
  • Monthly Income Plans (MIP- Here the dividends are payee monthly.
Liquid funds.
Liquid funds are the biggest contributor of mutual fund industry. All the schemes with less than one year maturity are called liquid funds. Few of the widely traded liquid funds are commercial papers, certificate of deposit treasury bills etc.


Monday, 22 July 2013

An introduction to ORM and Hibernate

For years EJB Entity Beans was the only persistence framework which managed transaction and concurrency in java. Entity Beans required a server for running and was difficult to code and debug.

ORM (Object Relational Mapping) frameworks came into picture as a lightweight and simpler alternative to EJB 2.0 entity beans as a persistence framework that manages transaction and concurrency. All the ORM based persistence framework has the agenda of mapping a defined POJO (Plain Old Java Object) entity to a database table. There will be a mapping file defined for mapping the java object to database table. In the newer version of ORMs, there is alternate mapping via annotations. These ORMs can run in server and non-server environment.

Hibernate is arguably the most prominent ORM based persistence framework available in the market for java. There is NHibernate available for .NET solution.
Some of the most prominent ORMs in java are:

  • Java Persistence API (JPA) - We will discuss JPA also to some extent here.
  • Toplink
  • iBATIS
  • Java Data Objects (JDO)

Why ORM frameworks?

  • One of the biggest advantage of using an ORM comes while we require multiple database support in a project. The ORM will take care of converting the SQL query syntax based on the underlying database using SQL Dialect.
  • ORM frameworks saves a lot of development time as it generates the SQL files and takes care of the execution. So, developer needs to take care of just populating the data object and does not have to take care of the sql symantics, setting parameters etc. there by saving development and debugging time.
  • Developers can concentrate more on business logic than managing persistence as the business objects will get directly mapped to the data in database.

ORM Vs Plain JDBC

  • ORM frameworks are slower than JDBC as it is a wrapper over JDBC and the additional query generation work needs to be done at run time using reflection and the provided mapping metadata. But most of the ORM frameworks uses caching frameworks to cache the data managed by the framework and retrieve it from cache enhancing performance. Also, on application startup, these frameworks loads all the mapping/annotated data to enhance performance.
  • Developer needs to learn and have expertise in the ORM framework to deal with the practical issues.

JPA (Java Persistence API): 

We also have JPA which is the replacement for Entity Beans in EJB 3.0.
JPA is an abstraction layer above all other persistence frameworks. They provides a plugin to these persistence frameworks. So, if you want to use hibernate as your persistence provider for JPA, just we need to mention that in the config file. Tomorrow if you see some other persistence provider will be better to serve your requirement, you can do so without much impact using JPA.

High Level Architecture and Working of Hibernate:


Configuration:
Hibernate application would be having two configuration files

  1. hibernate.properties 
  2. hibernate-cfg.xml 
The connection details, customized connection pooling for non-server environments, mapping data of various database tables to java POJOs etc. are stored in these files. For modularisation, hibernate-cfg.xml may refer to multiple mapping files in which the table to POJO mapping exists. From hibernate 3.0 onwards, mapping can also be done via annotations.

The hibernate properties file needs to be loaded by creating a hibernate configuration object as below:
new Configuration().configure();

Session Factory Object:
Based on the hibernate configuration, a session factory is created. This session factory manages the connection pool and provides connection sessions to the user as requested.

Session factory is created using below code:
sessionFactory = new Configuration().configure().buildSessionFactory();

Session Object:

A session object represents a physical database connection session. Persistent objects are managed via session object.

Session object creation code:
Session session = sessionFactory.openSession();

Transaction Object:
Transaction represents a single unit of work with the database. Transactions in hibernate gets managed by the underlying transaction manager which will be JTA or JDBC.

Transaction tx = session.beginTransaction();

Entity POJO:
With the transaction ready, all you need is the entity POJO. This is a simple java bean having properties defined as the member variables with their respective getter/setters. The java bean to table mapping can either be annotated or mentioned in a mapping file along with the mapping/annotation of java class properties to database columns.

The session object has got various methods for the DML operations to take place and finally the transaction can be committed or rolled back based on its success.

Query Object:
The query objects use HQL (Hibernate Query Language) or SQL to fetch data from database.

Criteria Object:
Criteria object is used to create and execute where clause or the filter criteria to fetch data from database.

Sunday, 14 July 2013

Finance: Introduction to Derivatives

Before coming to derivatives, let us talk about a simple trade between a farmer and a miller.

A farmer and a miller makes an agreement to trade wheat at a particular price in future. This would guard both farmer and miller against uncertainty in price. The farmer will loose any additional gains he could have achieved if there is a price rise. If the price falls, the miller will have to pay additional money for purchasing wheat thereby making a loss. This agreement can be termed Forwards. Forwards are one type of derivative trade and if you understood this trade example, you got the base of derivatives.

Derivatives are the financial instruments whose returns are derived from an underlying assets. In case of the example we discussed, the underlying asset is wheat and futures price and agreement would be decided based on the price of underlying asset, i.e. wheat. The underlying assets can be based on real physical assets (like agricultural commodities,metals etc.) or financial assets like stocks, currencies etc.

Hedging: Derivatives are used by companies and individuals to transfer any undesired price risk or unpredictability of price to another party. The other party takes the unpredictability of price risk and may achieve gain or loss based on the price of underlying commodity at the time of trade execution.
In case of the example we discussed, the farmer has hedged or removed any price risk he may have to face at the time of harvest.

Speculation and Arbitrage: The typical example of a speculator is a person who trades in stock market with the motto of making profits and is not looking forward for a physical trade. The person who buys a derivative to acquire price risk and therefore look to make financial gains out of it based on some speculations and forecast is called a speculator.

Derivatives can be classified as exchange traded and over the counter (OTC) traded.

Over The Counter (OTC) Traded derivatives

These are contracts that are traded directly between two parties without going to a regulated exchange. There is counterparty risk associated with an OTC trade.

Exchange Traded Derivatives

These are contracts that are traded over a regulated exchange. Each trade happens with an exchange and not directly with a counterparty. Since, exchange is the counterparty for trades happening over the exchange there is no counterparty risk involved here.

Types of derivative contracts:


1. Options: Options precisely means that the holder has an option to whether or not execute the trade contract. Option gives the option buyer right and not obligation to whether or not execute the trade contract.
The option buyer pays the seller an amount of money called as premium. An option to buy something is called as call and an option to sell something is known as put.
The maximum loss that an option buyer can incur is the premium itself. This is because the option buyer will execute the underlying trade only if he gets some profit. So, the option buyer can have profit of any margin and maximum loss equivalent to premium. Inversely, the maximum profit that an option seller can get would be option premium and the loss can be of any magnitude. Options can be OTC or exchange traded.
Different type of options are European option, American option, Average price option.
American option can be executed at any time before expiry, European option can be exercised only on contracted expiry date. In case of Average price option, option is exercised with average price over the settlement period.
In India, we use European options.

2. Forward Contracts: Forwards are tailor made contract between two parties that is to be executed at a future date at an agreed price. This is strictly an OTC traded derivative. The need for such a contract lies in the customization requirement of the agreement between two parties that is agreed to be done in future. If the parties are intending to do a physical transaction of traded commodity, then there needs to be  an agreement on quality of the commodity, penalty for delay etc.

3. Future Contracts: A future contract is also a contract between two parties that is to be executed at a future date at an agreed price like Forwards. But Forwards is strictly traded over the exchange and is targeted for speculators. Future contracts are traded on organized exchanges called futures markets.

4. Swap contracts: Swap is a contract in which two parties agree to exchange cash flows. This can be based on two fixed prices or floating prices. An example of swap trade is agreement between airline and fuel company. Fuel company agrees to provide a fixed price for the airline fuel at a mentioned date and the airline company is ready to give the average price on exchange index in return.

5. Exotics: There are hybrid derivatives which are combinations of one or more of the above derivatives.

Tuesday, 9 July 2013

Configuring Websphere MQ for messaging on windows with JMS

Configuring Websphere MQ for messaging on windows



1.  Create Queue Manager and Queues required for the application.

 Create queue manager
 In the websphere MQ console, Right click on queue managers->new->queue manager


 Enter queue manager name and click next till step 3
 On step 3, check the box for create server connection channel and click next

 If the default port number 1414 is already in use by some other queue manager then change the port number and click finish

Create Queue for receiving messages

Under Queue Manager Click new-> local queue
  


 Enter queue name and click finish
Similarly, you can create a queue for putting acknowledgement/response messages back after processing as required.

Generate a binding file for configuring queue managers with queue connection factories and queues with queue destinations.

1)    Go to websphere mq installation directory/java/bin
2)    Edit JMSAdmin.config
Uncomment the following values and comment other properties

INITIAL_CONTEXT_FACTORY=com.sun.jndi.fscontext.RefFSContextFactory
PROVIDER_URL=file:/C:/JNDI-Directory
SECURITY_AUTHENTICATION=none

Create a directory as there in provider url or change the provider url to the location where you want to generate .bindings file.
      Run JMSAdmin.bat
      You will get an InitCtx prompt.

            Use the commands below for creating and binding queue connection factory and queue destinations and binding them with queue manager and queues.

1)Def qcf(<name of queue connection factory>)  qmgr(<queue manager name>) transport(client) port(<port number>)
2)def q(<queue destination name>) qmgr(<queue manager name>) queue(<queue name>)
(create for both sender queue and receiver queue as shown in the snapshot.)


Configuring JMS for receving/consuming messages:

The queue connection factory and queue destination can be defined in ejb-jar.xml or via j2e server's UI for configuring a message driven bean (MDB).

You can configure your own MessageListener as follows:
1. Create QueueSession - For this you need to provide jndi lookup address for QueueConnectionFactory and QueueDestination. These are used for creating a QueueSession as below.
     Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,                   "com.sun.jndi.fscontext.RefFSContextFactory");
env.put(Context.PROVIDER_URL, "file:/C:/JNDI-Directory");
Context jndiContext = new InitialContext(env);
QueueConnectionFactory queueConnectionFactory = 
(QueueConnectionFactory) jndiContext.lookup("<name of queue connection factory>");
Queue queue = (Queue) jndiContext.lookup("<queue destination name>");
queueConnection = queueConnectionFactory.createQueueConnection();
queueSession  = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

2. Registering the Listener:
                MessageConsumer consumer = queueSession.createConsumer(queue);                
                MessageListener listener = new MyListener();
                consumer.setMessageListener(listener);
                queueConnection.start();

3. Creating own Listener:
Listener class should implement jms MessageListener interface and onMessage(Message message) will have your jms message which you can process further.

4. Sending back acknowledgement or putting message via direct lookup:
You can create a queuesession as discussed earlier.
For the reply queue or acknowledgement queue creation, you can follow the below steps:
               queueSender = queueSession.createSender(queue);
               TextMessage textMessage = queueSession.createTextMessage();
textMessage.setText("Test Message");
queueSender.send(textMessage);


Various Singleton approaches in Java

Java Singleton

There are several approaches in Java to create a singleton class. The various methodologies and their pros and cons are discussed here:

1) Eager Initialization:

In case of eager initialization, the singleton is instantiated when the programs starts whether or not it gets used. The problem with this approach is that valuable resources are allocated whether or not they ever get used. If you are uncertain on whether your singleton object will be used or not and the singleton has a large memory footprint, this may not be a good choice.

public class Singleton {

    // Eager initialization happens here.
    static private Singleton instance = new Singleton();

    // Prevent instantiation by public.
    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }
}

Eager initialization relies on the fact that the JVM will initialize the class members upon loading the class. And the class is loaded when it is first referenced.


2) Lazy Initialization:

In case of lazy initialization, the object only get instantiated on the first time the getInstance() method is called. This has the advantage of not allocating the resources unless it is actually needed. The problem with this approach is that the getInstance() method needs to be synchronized. Therefore there is a performance hit when acquiring the singleton on subsequent calls.

public class Singleton {

    static private Singleton instance = null;

    // Prevent instantiation by public.
    private Singleton() {
    }

    synchronized public static Singleton getInstance() {
        if (instance == null) {
            // Lazy initialization happens here
            // on the first call to this method.
            instance = new Singleton();
        }
        return instance;
    }

}

The subsequent calls for fetching the singleton object will have to go through the synchronization block which is a performance hit. This will also result in parallel threads in wait stage.


3) Lazy Initialization with double check:


This is a methodology is used to overcome the performance issue with lazy initialization. We do a double check to ensure that the subsequent calls for acquiring singleton object after its creation does not have to go through a synchronized block.

public class Singleton {


    private volatile Singleton instance = null;
    
    // Prevent instantiation by public.
    private Singleton() {
    }
public static Singleton getInstance() { if (instance == null) { synchronized(
Singleton.class) { if (instance == null) { instance = new Singleton (); } } } return instance; }
}

But this approach fails in a multiprocessor environment and is not recommended.
Further details : http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-toolbox.html

4) On Demand Initialization with a holder class:

This method relies on the JVM only intializing the class members upon first reference to the class. In this case, we have a inner class that is only referenced within the getInstance() method. This means SingletonHolder will get initialized on the first call to getInstance().

public class Singleton {

    // Prevent instantiation by public.
    private Singleton() {
    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    } 

    /**
     * Singleton implementation helper.
     */
    private static class SingletonHolder {
        // This gets initialized on first reference
        // to SingletonHolder.
        static final Singleton instance = new Singleton();
    }
}

In this case, the singleton object will not get allocated until it is used and we did not need to incur the overhead of a synchronized method call.
The only issue we have here is that a serialization/deserialization or by using reflection, we can create a new instance of this singleton class. For solving the serialization/deserialization scenario breaking the singleton, we can override readresolve() method. For handling the instance creation via reflection, all we can do is to enable java security manager property. This will restrict the access of private constructor via reflection.

5) Enum approach with Java 5:

There is one more, probably the best way to do it if you are using Java >= 1.5 according to 'Effetive Java' author 
Joshua Bloch. I personally feel that the above methodology(number 4) is the best approach among all. 
In Java 5 and above, you can use Enum – this way you get Singleton functionality easily and don’t have to think about serialization as you get it for free:


public enum YourSingleton {
INSTANCE;

public void doStuff(String stuff) {
System.out.println("Doing " + stuff);
}
}

Now you can use it and be completely sure it’s Singleton:
You can make call to the methods as following:
Singleton.INSTANCE.doStuff("some stuff");

Monday, 8 July 2013

Working of a typical MVC2 Architecture and its control flow


In this blog, we will have a look at the basic handling of MVC2 frameworks  we have in the market.

Below is a block diagram representing typical MVC2 framework:
MVC2 Architecture
Typical MVC2 Architecture


Front Controller Servlet implementation

A typical MVC2 framework will have a front controller servlet. The purpose of a front controller design pattern is to provide a centralized access point to all the presentation tier requests. This will also help to have common code for request handling, authentication, authorization, delegating to business layer, forwarding request to appropriate view and validation. These processing can also be split by using intercepting filters. You can define a intercepting filter in web.xml and do the pre-request processing and post-response processing. For example, we can check whether the user is logged in user pre-request processing of a filter.

Typical work flow of an MVC2 architecture

There will be a front controller servlet defined for the MVC framework in web.xml. When the browser send request to the web server, it delegates the request to the front controller servlet based on the url filter defined in the web.xml for the MVC framework, for example it is *.do for struts framework.
The framework controller servlet will be having an init-param defined for MVC config file in web.xml. Based on this parameter, controller servlet caches the MVC config mappings. There will be a request url to controller mapping defined in the MVC config file, along with a validator and views to be displayed for various outcome. 
The controller calls the necessary server-side validations before proceeding further. There will be also a client-side validation before the request is sent from the browser, using javascript generated by the custom tags defined by the MVC framework. 
After the server side validation is done, the corresponding DAO layer is called either directly or via a service layer to populate the model java bean. This java bean holds the necessary information for the view JSP to populate the appropriate data and display. The controller dynamically decides whether or not to display the view defined in the MVC config file mapping based on the processing of model done.
The controller will forward the request to the View with model data. 
There can be a separate RequestDispatcher component for forwarding the request by setting the populated model as an attribute. In RequestDispatcher, we decides the view based on the outcome returned by the controller and the outcomes defined in the MVC config file.

Template Design Pattern: The forwarded View will be displayed in a consistent look and feel by making use of template design pattern. This is done by defining a Template.jsp with a defined header, footer, sidebar etc. The body of the view will be changing with the View JSP based on request processing. The http request will always be forwarded to the Template.jsp, but the body variable of the jsp will be sent as an attribute to the template.jsp.

I think this is all you need to know to implement your own MVC framework or to understand the base of any MVC framework.