STL Container Adaptors in C++


stack
#include <stack>
stack<int,vector<int> > mystack;
empty : Test whether container is empty
size : Return size
top : Access next element
push : Add element
pop : Remove element

queue
#include <queue>
queue<int,vector<int> > myqueue;
empty : Test whether container is empty
size : Return size
front : Access next element
back : Access last element
push : Insert element
pop : Delete next element

priority queue
#include <queue>
priority_queue<int, vector<int>, less<int> > myque;
empty :Test whether container is empty
size : Return size
top : Access top element
push : Insert element
pop : Remove top element


Numeric Algorithms in C++ STL


header file required for numeric algorithem
#include <numeric>

sum of list of data
init=0
double summation = accumulate (vec.begin(), vec.end(), init);

inner product of two vectors
double ipval = inner_product(vec1.begin(), vec1.end(),vec2.begin(), init)

partial sum of vector
partial_sum(vec.begin(), vec.end(), resultvec.begin());

Compute difference between consequence elements of a vector
adjacent_difference(vec.begin(), vec.end(), resultvec.begin());

Set theory operations in C++ using STL


Set operation in STL

1. Is set A subset of set B
if(includes(vecB.begin(),vecB.end(),vecA.begin(),vecA.end(),compareFunc))
cout<<"VecA is subset of VecB";

2. The union of A and B
insert_iterator<set<int> > insertiter(resultset, resultset.begin());
set_union(first.begin(), first.end(), second.begin(),second.end(), insertiter);

3. The intersection of A and B
set_intersection(first.begin(), first.end(), second.begin(),second.end(), insertiter);

4. The difference of A and B A\B
set_difference(first.begin(), first.end(), second.begin(),second.end(), insertiter);

5. The symmetric difference of A and B
set_symmetric_difference(first.begin(), first.end(), second.begin(),second.end(), insertiter);

bit operation and set theory in C++

Set union A | B Set intersection A & B Set subtraction A & ~B Set negation ALL_BITS ^ A Set bit A |= 1 << bit Clear bit A &= ~(1 << bit) Test bit (A & 1 << bit) != 0 shift operations on negative values are undefined xor using logical operators (p || q) && !(p && q)

BOOST_FOREACH bug in eclipse

I got issue with using BOOST_FOREACH macro using in eclipse and after google i found this has raised as bug in eclipse.

https://bugs.eclipse.org/bugs/show_bug.cgi?id=332278

I opted following solution which is given on above link.

1. Goto Project Properties --> Paths and Symbols tab
2. Add name : BOOST_FOREACH(a,b)
    with value : for(a:b)

Python - matplotlib: plot graph of fincance stock qutoes

I need some utility which can work with any platform, reason in my last blog we discuss on Matlab and Gnuplot, both are good tools but i need very light-weight tool which can work windows as well linux with same code.
================================================================
Visit my online store www.desikudi.in

================================================================

I have most of data reading utility in python, so i needed tool in python. i have chosen the matplotlib module for this task.




we need to import following python modules in our program.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.finance import plot_day_summary
import datetime

I have data in dictonary format, you can found my csv datareader code, so i had written following format of code. I like date in YYYYMMDD format because sorting of data based on date is easy.

def plotData(dictdata,numday):
        qut=[]
        if len(dictdata)>0:
            i=0
            for row in dictdata:
                ts=row['timestamp']
                op=row['open']
                hp=row['high']
                lp=row['low']
                cp=row['close']
                qut.append([datetime.datetime.strptime(ts,'%Y%m%d').date(), 
                            float(op),float(cp),float(hp),float(lp)])
                i=i+1
                if i>numday:
                    break
            plotquotes(qut)


def plotquotes(quotes):
    ax = plt.axes()
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y%m%d'))
    ax.xaxis.set_major_locator(mdates.WeekdayLocator(mdates.MONDAY))
    ax.xaxis.set_minor_locator(mdates.DayLocator())
    plot_day_summary(ax,quotes)
    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    plt.show()

=============================================================
Visit my online store www.desikudi.in


Python-CSVReader and Database

I need to read some data form csv files and as it's i need to put in single mysql database table. I written very simple classes for reading data in dictonary format and sending data to mysql database.
I used two python modules
    1. csv
    2. MySQLdb

we can divide this task in two class one can handle the csv reader and another can handle database.
Now have look of first class

import csv
class myReader:
    def __init__(self, csvfile ):
        self.reader = csv.DictReader(open(csvfile, "rb"), delimiter = ",", skipinitialspace=True)
    def getRow(self):
        try:
            row = self.reader.next()
        except:
            row = None
        return row
    def __del__(self):
        print "Destorying myReader object"


after reading the row from csv file, we can directly pass to our table class which have create sql based on number of columns in row data, sometimes may be your row have less number of columns then table.

import MySQLdb
class csvTable:
    def __init__(self, db ):
        self.db = db

    def additem(self, item):
        cursor = self.db.cursor()
        vallist=''
        collist=''
        for key in item:
            if key=='':
             continue
            if vallist=='':
                vallist="%("+key+")s"
                collist = key
            else:
                vallist = vallist + "," + "%("+key+")s"
                collist = collist + "," + key
        sql = "INSERT INTO  csvDataTable ("+ collist + ") VALUES (" + vallist + ")"  
        cursor.execute(sql,item)
        cursor.close()
        return

    def savedata(self):
    '''
    commit the data in database
    '''
        self.db.commit()
        return

    def __del__(self):
        print "Destroying the csvTable object"

Now we need to write unittest function.

def processcsvfile(csvfile):
    print "inserting data of " + csvfile
    conn = MySQLdb.connect(host= "localhost",user="mysqluser",passwd="password",db="mydb")
    rd = myReader (csvfile)
    ct = csvTable(conn)
    rw = rd.getRow()
    i=0;
    while rw:
        try:
            ct.additem(rw)
        except:
            print "Unexpected error:", sys.exc_info()
        rw = rd.getRow()
        i=i+1
    print "Number of recored processed :" + str(i)
    ct.savedata()
    conn.close()


Option Pricing in Excel


Today, I am bringing one xls file for you about calculating premiums of European options using Black-Scholes pricing formula.


Excel file : option pricing 


You just need to download this xls and change the values in yellow cells only.
This excel sheet can help you to calculate the implied volatility if you have option premium.


so now using this excel sheet, you can calculate following things.
  1.  calculate the premium.
  2.  calculate the volatility.
Time out,  catch you soon, have a nice time.


If I did something wrong calculation kindly let me know with your comments. I appreciate your feedback to improve my understanding(learning).

Matlab Engine from C++


This is just for my fun, don't take seriously. I was writing a small stock screening utility for personal use, which was based on NSE(Indian stock exchange) Bhavcopy data. First I plan to write each and everything in own way, I have written half of my matrices operations in my library, then i figure out, it will took very long time to write all kind of operation and stock indicators. I also want to graph plotting with data, which I already used one tool gnuplot.
Finally I found matlab, which supports both things for me. It will do calculation and graph plotting.


Here i found they have given example code in C style format and i used to with C++ class-object re-usability, you can say, mad for writing code in OOP(oops) formats, a very bad habit. I written a small class using something called singleton design pattern[which i don't know, once somebody told me this is not singleton, but it's working perfect for me or my requirement].

First I will show you how i used my class which created above graph.
.............................. when my application startup -------------------------

MLEngine* me = MLEngine::getMLEngine();
void stockprice::drapgraph()    // This is my sample class for playing with stock data.
std::vector<double> close(close());
std::vector<double> open(open());
std::vector<double> rsi;
std::stringstream ss;
ss<<"x = 1:1:"<<ticklist.size();
std::string strcmd1=ss.str();
me->sendCommand(strcmd1.c_str());
me->sendDoubleVector(close,"close");
me->sendDoubleVector(open,"open");
double rsival,sma5val,ema5val;
me->sendCommand("rsi=rsindex(close);"); //calcualte rsi from matlab enginee
me->getDoubleVector(rsi,"rsi");  // getting calculated rsi from matlab in vector
rsival = rsi[rsi.size()-1];
me->sendCommand("sma5=tsmovavg(close, \'s\', 5,1);"); //calcualte simple moving average
me->getDoubleVector(rsi,"sma5");
sma5val = rsi[rsi.size()-1];
me->sendCommand("ema5=tsmovavg(close, \'e\', 5,1);"); //calcualte simple moving average
me->getDoubleVector(rsi,"ema5");
ema5val = rsi[rsi.size()-1];
me->sendCommand("sh(1)=subplot(3,1,1);"); // for multiploting and linking axis 
me->sendCommand("plot(x,close,x,open);");
me->sendCommand("legend(\'close\',\'open\');");
me->sendCommand("grid on;");

me->sendCommand("sh(2)=subplot(3,1,2);");
me->sendCommand("plot(x,rsi);");
me->sendCommand("legend(\'rsi\');");
me->sendCommand("grid on;");

me->sendCommand("sh(3)=subplot(3,1,3);");
me->sendCommand("plot(x,ema5,x,sma5);");
me->sendCommand("legend(\'ema5\',\'sma5\');");
me->sendCommand("grid on;");
me->sendCommand("linkaxes(sh,\'x\');"); //// for multiploting and linking axis
.............................. when my application exit -------------------------
        MLEngine::releaseMLEngine();


Now have look of this class.


#include<engine.h>
#include<vector>
class MLEngine
{
public:
static MLEngine* getMLEngine();
static void releaseMLEngine();
void sendCommand(const char* _cmd);
void sendDoubleVector(const std::vector<double> & _vecdouble,const char* _name);
void sendLongVector(const std::vector<long> & _veclong,const char* _name);
void getDoubleVector(std::vector<double> & _vecdbl,const char* _var_name);
private:
static MLEngine* m_pMLEngine;
Engine *m_pEngine;
MLEngine(void);
MLEngine(const MLEngine&){}
MLEngine& operator=(MLEngine&){}
virtual ~MLEngine(void);
};

Now we will look implementation of some of important attribute and behavior of this class.

getMLEngine : this will give you handle of matlab engine, which we are releasing in releaseMEEngine.
MLEngine* MLEngine::m_pMLEngine =NULL;
MLEngine* MLEngine::getMLEngine()
{
if(!m_pMLEngine)
m_pMLEngine = new MLEngine(); 
return m_pMLEngine;
}

void MLEngine::releaseMLEngine()
{
delete m_pMLEngine;
m_pMLEngine = NULL;
}

sendCommand : this used for sending command from C++ application to matlab engine.
void MLEngine::sendCommand(const char* _cmd)
{
if(!m_pEngine) return;
engEvalString(m_pEngine, _cmd);
}

sendDoubleVector : This use to send vector data to matlab engine and create matlab variable with given name. This name can use in next command to refer this data.
void MLEngine::sendDoubleVector(const std::vector<double> & _vecdouble,const char* _name)
{
if(!m_pEngine) return;
mxArray * mx1 = mxCreateDoubleMatrix(_vecdouble.size(),1, mxREAL);
       std::copy(_vecdouble.begin(), _vecdouble.end(), mxGetPr(mx1));
engPutVariable(m_pEngine, _name, mx1);
}

getDoubleVector : This used to get the data from matlab engine with given name.
void MLEngine::getDoubleVector(std::vector<double> & _vecdbl,const char* _var_name)
{
if(!m_pEngine) return;
mxArray* pMx =  engGetVariable(m_pEngine, _var_name);
if(pMx==NULL)
return;
int size = mxGetNumberOfElements(pMx);
_vecdbl.clear();
_vecdbl.resize(size);
double *data=reinterpret_cast<double*>(mxGetData(pMx));
for(int i=0; i<size; ++i){
_vecdbl[i]= data[i];
}
mxDestroyArray(pMx);
}

Now go and enjoy matlab engine and C++ but take care of linking part, which I haven't added here.

Single Instance application

Today, we are going to learn, how to create a application, which launch only a single instance on system.
1.create a system level object.
2. checking, is that object already exist or not.
  a. if not exist launch application.
  b. if exist check is that zombie process or alive
    i. if alive instance, don't launch new instance just prompt a message to user and exit.
    ii if zombie process, destroy the object and launch new instance of application.

I am providing sample code windows MFC application, here i used the mutex as system object.

This code should put in initinstance of winapp MFC class.
Based on this you can create a class and create a global object that class.
CString strTitle;
strTitle.LoadString( AFX_IDS_APP_TITLE );
HANDLE hmutex = OpenMutex( MUTEX_ALL_ACCESS, TRUE, strTitle );
if( hmutex!=NULL )
{
DWORD dwRet = WaitForSingleObject(hmutex,10);
If(dwRet!=WAIT_ABANDONED){
ReleaseMutex(hmutex);
}
else{
          AfxMessageBox( "App already exist", MB_OK | MB_ICONEXCLAMATION, (UINT)-1 );
return FALSE;
}
}
hmutex = CreateMutex( NULL, FALSE, strTitle );

you can use similar logic using pthread or boost thread to create application on linux, unix environments.
Thanks to reading this.