Pages

Saturday, April 11, 2020

MongoDB: Analyzing Data with Aggregation

Here is the sample code to analyze data with the Aggregation Framework within MongoDB.



Sunday, April 14, 2019

Connect to Oracle Database from Python or R

1. To connect to Oracle in Python

     1)  conda install -c anaconda cx_oracle 

2.1) Method 1:


    import pandas as pd

    import cx_Oracle


    con = cx_Oracle.connect('pythonhol/welcome@127.0.0.1/orcl')

    query = 'select * from departments order by department_id'     
    df_ora = pd.read_sql(query, con=con)
    df_ora.head()

    con.close()

2.2) Method 2:
    import cx_Oracle
    con = cx_Oracle.connect('pythonhol/welcome@127.0.0.1/orcl')
    cur = con.cursor()

    query = 'select * from departments order by department_id'
    cur.execute(query)
    for result in cur:
        print(result)
    cur.close()
    con.close()



2. To connect to Oracle in R
1)  install.packages("ROracle")

2) Method 1:
   library("ROracle")
   drv = dbDriver("Oracle")
   host = "hostname"
   port = "1521"
   sid = "SID_NAME"
   connect.string = paste(          "(DESCRIPTION=",
         "(ADDRESS=(PROTOCOL=tcp)(HOST=", host, ")(PORT=",port, "))",
         "(CONNECT_DATA=(SID=", sid, ")))", sep="")
   con = dbConnect(drv, username="uid", password="pwd", 
                   dbname=connect.string, prefetch=FALSE,
                   bulk_read=1000L, stmt_cache=0L,
                   external_credentials=FALSE, sysdba=FALSE)
   res = dbGetQuery(con, "select * from dual")
   print(res)
   dbDisconnect(con)

Wednesday, December 21, 2016

Quantopian(Python) vs Quantmod(R)

1, Sid-by-side comparison

2, Code snippet:

    from rpy2.robjects import r
    from pandas_datareader import data, wb
    import talib
    import numpy
    import matplotlib.pyplot as plt

    IBM = r("getSymbols('IBM', src='google', from='2013-01-01')")
    f = data.DataReader(ticker,'google')
    f['SMA_50'] = talib.SMA(numpy.asarray(f['Close']), 50)
    f.plot(y= ['Close','SMA_20','SMA_50'], title='AAPL Close & Moving Averages')
    plt.show()

3. Module Installation

    conda install rpy2
    conda install -c quantopian ta-lib

    # more inteteresting modules
    conda install -c quantopian zipline
    conda install -c quantopian pyfolio
    conda install seaborn
    conda install quandl

Sunday, August 21, 2016

Covariance formula with CDF (Hoeffding's Covariance Identity)

{\displaystyle \operatorname {cov} (X,Y)=\int _{\mathbb {R} }\int _{\mathbb {R} }F_{XY}(x,y)-F_{X}(x)F_{Y}(y)dxdy}


A complete proof of above lemma can be found on page 241 (Lemma 7.27) of Quantitative Risk Management: Concepts, Techniques and Tools.

Hint: 2\(cov(X_1, X_2) = E[(X_1-\tilde{X_1})(X_2-\tilde{X_2})]\),
where \( (\tilde{X_1}, \tilde{X_2}) \) is an independent copy with the same joint distribution function as  \( (X_1, X_2) \).

Link to MathJax

Monday, August 15, 2016

Mathematical Programming and its modeling langues

Python is widely used in Mathematical Programming as a modeling language.




In commercial products, Gurobi has built its interactive shell in Python.




In open source world, Pyomo from Sandia National Lab use Python to offer an AMPL-like modeling language. Pyomo uses GLPK solver by default, but other solvers, such as GLPK, Gurobi, COIN CBC, can also be selected.




GLPK (GNU Linear Programming Toolkit) supports MathProg, which is also referred as GMPL (GNU Mathematical Programming Language). GLPK provides a command line tool glpsol, which is convenient for users to solve various optimization problems with well designed reports.




PuLP is an LP modeler written in Python. PuLP can generate MPS or LP files, and can call GLPK, COIN CLP.CBC, CPLEX and Gurobi to solve linear problems.


SolverStudio makes it easy to develop models inside Excel using Python. Data entered into the spreadsheet is automatically available to the model. SolverStudio supports PuLP, COOPR/Pyomo, AMPL, GMPL, GAMS, Gurobi, CMPL, SimPy.



Wednesday, August 10, 2016

OLS in Python

There are a few ways to perform Linear Regression(OLS) in Python.


Here is a short list of them:


1: > pandas.ols(y, x)
2: > pandas.stats.api.ols(y ,x)
3: > scipy.stats.linregress(x, y)
4: > import statsmodels.formula.api as smf
    > results = smf.ols('Close ~ Open + Volume', data = df) # df is a DataFrame



Friday, July 29, 2016

Interior Point Methods

Interior Point Methods are a class of optimization algorithms for solving linear or nonlinear programming problems.


It finds the optimum solution by moving inside the polygon rather than moving around its surface.


History:


In 1984, Karmarkar "invented" interior-point method.
In 1985, Affine-scalling method was "invented" as an intuitive version of Karmarkar's algorithm.
In 1989, it was realized that Dikin(USSR) invented Affine-scaling(Barrier method) in 1967.


Interior point method was the first practical polynomial time algorithm for solving linear programing problems. Ellipsoid method's run time is polynomial, but in practice, the Interior Point Method and variants of Simplex Methods are much faster.


Here goes technical in summary:


1. Primal objective with log barrier function: G(μ) = cx - μ Σ ln(xj)


2. Central path algorithm: μ from infinity to 0.


3. Min with constraint Ax=b?

    ∇G(μ) perpendicular to Ax=b;
    <cj-μ/xj> is linear combination of A's rows;
    <cj-μ/xj> = yA for some y;


    Let sj = μ/xj, then
          yA + s = c  ==> yA ≤  c, this the dual constraints.


4, Duality gap: cx - yb = (yA+s)x - y (Ax)
                                     = sx
                                     = nμ

5. Conversely, if all sj xj = μ, then on central path.
    To follow Central Path, use "predictor-corrector".


6. Improvement direction? "Affine-scaling"
    From current x, s, μ ==>  x+dx, s+ds, μ+dμ
                                    ==> sj dxj + xj dsj = dμ     (1)
    Also A(x+dx) = b    ==> Adx = 0                      (2)
            yA + s = c        ==> (dy)A + ds = 0           (3)


    To solve (1)-(3), rescale "affine scaling", all xj = 1 ==> sj = μ
    The equations say
           μdx + ds = 1dμ
           Adx = 0                ==> dx  A
           (dy)A + ds = 0      ==> ds  A


    ==> project 1dμ into A and A




Note: some of the information comes from course "Advanced Algorithms" as follows:


MIT 6.854/18.415J: Advanced Algorithms (Fall 2014, David Karger)
MIT 6.854/18.415 Advanced Algorithms (Spring 2016, Ankur Moitra)

Monday, May 23, 2016

Memoization in Python

# -*- coding: utf-8 -*-
"""


File name: fib_mem.py

Created on Mon May 23 14:50:39 2016


Source: MITx: 6.00x Introduction to Computer Science and Programming

Output:  222232244629420445529739893461909967206666939096499764990979600

PEP8 Style Compliant:
In Spyder: Preferences -> Editor -> Code Introspection/Analysis,
 near the bottom right, check Style analysis (pep8).


The 2nd way to run it:
 - Comment out "@my_memoize"
 - Uncomment "fib = my_memoize(fib)"
 - Run


The 3rd way to run it:
 >> from fib_mem import fib
 >> print(fib(300))


Tested on Python 3.x
"""


##########################################
# Example 1



def my_memoize(f):
    cache = {}


    def helper(*x):  # Refer to Item 18 of "Effective Python"
        if x not in cache:
            cache[x] = f(*x)
        return cache[x]
    return helper


@my_memoize
def fib(n):
    if n <= 1:
        return n
    else:
        return fib(n-1) + fib(n-2)

# fib = memoize(fib)
print(fib(300))



##########################################
# Example 2 (stack overflow)
def functionDecorator(f):
    def new_f():
        print("Begin", f.__name__)
        foo() # using f() instead
        print("End", f.__name__)
        return new_f


@functionDecorator
def foo():
    print("inside foo()")


foo()
print(foo.__name__)


###############################################################


"Python is basically pseudo code, ..." -- Brett Slatkin, The author of "Effective Python".


Saturday, May 7, 2016

Matrix Calculus

What's the partial derivatives (w.r.t. Î¼ and Î£) of this function?

       \ln(L)= -\frac{1}{2} \ln (|\boldsymbol\Sigma|\,) -\frac{1}{2}(\mathbf{x}-\boldsymbol\mu)^{\rm T}\boldsymbol\Sigma^{-1}(\mathbf{x}-\boldsymbol\mu) - \frac{k}{2}\ln(2\pi)

Yes, it's a beautiful formula: log-likelihood function of mvn distribution.

The answer can be found on page 40 of this book: The Matrix Cookbook

You will find equation (81), (57) and (61) are useful to get the partial derivatives.


The partial derivatives are used in Vibrato Monte Carlo method, which is a Path-wise/LRM hybrid method.

Note that there are a few alternative approaches to valuate financial derivatives which have non-differentiable payoff functions.

  • Likelihood Ratio Method (LRM) 
  • Mallianvin Calculus (Stochastic Calculus of Variations)
  • "Vibrato" Monte Carlo Method


Sunday, January 24, 2016

QuantLib in C++

QuantLib is an open-source C++ Library for quantitative analysis in Finance, and the QuantLib project was started by a few Quants in 2000. Now QuantLib project is Luigi Ballabio and ferninando Ametrano.

Secondly, QuantLib has been ported to other languages:

    R: RQuantLib
    Python: PyQL
    Java: JQuantLib
    Excel: QuantLibXL

QuantLib.org provides a very good API Doc, but you may still want to take a look at other sources for API documents. The following is a short list of links for QuantLib API Docs.

QuantLib SourceCodeBrowser
QuantLib Java API Docs
QuantLib API Docs generated by Doxygen(v0.3.4)
Implementing QuantLib
C++ Design Patterns and Derivatives Pricing 2e
QuantLib on YouTube

In addition, some commercial software products are also available: QRM, FinCAD, Numerix, SunGard-FastVal, Savvysoft, Quantifi, Pricing Partners Cie, Bloomberg, Intex.

http://libguides.caltech.edu/LindeFinance

Saturday, January 9, 2016

Print a float or double in C++?

#include <iostream>
#include <bitset>
#include <cassert>

using namespace std;

int main(void)
{
const int n = sizeof(float)* 8; //32 bits
float f = 975.75;
unsigned int u;
assert(sizeof(f) == sizeof(u));
std::memcpy(&u, &f, sizeof(f));
std::cout << n << ": " << bitset<n>(u) << endl;
//32: 01000100011100111111000000000000

const int nd = sizeof(double)* 8;
double d = 975.75;
unsigned long long ull;
assert(sizeof(d) == sizeof(ull));
std::memcpy(&ull, &d, sizeof(d));
std::cout << nd << ": " << bitset<nd>(ull) << endl;
//64: 0100000010001110011111100000000000000000000000000000000000000000

std::system("pause");
return 0;
}

To confirm the conversion, please check out: http://www.binaryconvert.com/index.html

Wednesday, December 30, 2015

Built-in Smart Pointers in Modern C++

C++ is a general programming language that supports raw pointers. To use the raw pointers, we have to manage the memory carefully with new/delete, new[]/delete[], or perhaps C-style malloc/free pairs. The memory leak is always a potential risk -- imagine a runtime_error just occurred. Detecting tools like Valgrind or Garbage Collectors like Boehm GC[using mark-sweep algorithm] may be helpful to some extent, but it's still our responsibilities to make sure that the memory is properly managed and thus less time is left for the actual business needs.

Smart pointer is one answer in the language level. Actually, smart pointers were introduced in C++98. With the move semantics, they got even better in C+11.

Topics in C++ built-in smart pointers could be intricate if we dig them further deep into areas, such as GC algorithms, thread safety and exception safety. In this post, I'll compare the various smart pointers in a high level, and summarize it in a simple table. For the detailed discussion and the guidelines to use them, please refer to Chapter 4 of Scott Meyers' "Effective Modern C++", or <memory> on cplusplus.com.


raw pointer
auto_ptr
unique_ptr
shared_ptr
weak_ptr
Language support
Always allowed
Deprecated in C++11
C++11 (replacing auto_ptr)
C++11
C++11
What are they
T* t
T *t[n]

Wrapper of raw pointer
·   A smart ptr uniquely owned -- no two unique_ptr instances manage one object
·   It provides a limited GC
·   It contains a stored ptr and a stored deleter.
 .  Move-only type.
·  A smart ptr shared ownership group
·   It contains a stored ptr and an owned ptr to control block.
·  Stored and owned ptrs may refer to one object.
·   Empty shared_ptr
·   Null shared_ptr
·  A smart ptr holding non-owning ref. to an object managed by shared_ptr.
·   It models the temp ownership


Use Cases
Almost never in practice
Prefer to unique_ptr
 .  A ptr w/ exclusive ownership.
 .  Used in Pimpl idiom
 .  A ptr w/ shared ownership.
 .  A shared_ptr like ptr in risk of dangling.

How to use
new/delete
new[]/delete[]


up = make_unique<T>();//C++14
up = make_unique<T[]>();
up.get_deleter();
T* rp = up.get();
T* rp = up.release();
up.reset(p);//destroy & own p
*up
up->v1
shared_ptr<T> up{move(up)};
sp = make_shared<T>(n);
sp = make_shared<T[]>(n);
sp.use_count()
sp.unique()?
T* rp = sp.get(); // stored ptr
sp.reset();
*sp
sp->v1
sp1=allocate_shared<T>(alloc,10);
weak_ptr<T> wp(sp);
sp1=wp.lock()
wp.use_count()
wp.expired()?
wp.reset();

Pros


·   Small and fast. Little overhead over raw pointer.
·  Easy to convert to shared_ptr
 . Allowed to custom deleter (using lambda expression)
 . Capture closure support
 . Low overhead (2 x unique_ptr)
 . Works in multi-threaded 
       environments.
 .  Prevent shared_ptr cycles.
 .  shared_ptr <==> weak_ptr
Cons


·  Not capoyable
 .  Circular reference
 .  Exception: bad_weak_ptr



"The present is the past rolled up for action, and the past is the present unrolled for understanding." - Will Durant. 

REPL, Online IDE and Tools for Static Code Analysis

The code in general programming languages like Java and C++ and code is usually compiled and tested in IDEs. In other scripting languages, it's common to see a REPL (read-eval-print loop) language shell -- interactive interpreter.

REPL environment allows us to run the code piece by piece. This is very handy for testing purpose sometimes. Now there are some solutions in Java and C++.
[My thinking of picking a pair of similar tools comes from Hotelling's law -- "Linear City Model", though many more other tools are available, too.]

1. cint and igcc are two REPL simulators for C/C++.
2. javarepl and Eclipse's "scrap book" are two REPL simulators for Java.
3. ideone, codechef, and coding-ground provide online compiler suites for various programming languages(C++, Java, Scala, R, Python) by using cloud computing technologies.
4. cppcheck and cpplint.py are two tools for C++ static code analysis.

Coding ground is my favorite. It supports almost all popular languages, and claims 100% cloud. Best of all, it displays the command line and allows me to change the compiling options!

* As of December 2015, coding ground works well on my PC. It has an Android app for Tutorialspoint, but it's slow and Coding Ground on my Galaxy Note 4 is not working as well as it is on PCs.

Monday, December 28, 2015

Move Semantics and Constructors

C++11 includes four types of constructors:
  1. Default Constructor
  2. Conversion Constructor (disabled if explicit)
  3. Copy Constructor (const &)
  4. Move Constructor (&&)
C++11 also allows two types of assignment operators:
  1. (Copy) Assignment Operator (const &)
  2. Move Assignment Operator (&&)
The following is the sample code to demonstrate what they look like:

// MyCPP11Container.cpp

template<typename T, int value>
class MyCPP11Container
{
public:
 MyCPP11Container() {                                  // 1. DEFAULT CTOR
  /*intended to be empty*/
 }
 explicit MyCPP11Container(int) : MyCPP11Container() {  // 2. Disable CONVERSION CTOR
                            // DELEGATE CONSTRUCTION
  m_pData = new T(value);
 }
 MyCPP11Container(const MyCPP11Container& other) : m_pData(NULL) { // 3. COPY CTOR
  *this = other;
 }
 MyCPP11Container(MyCPP11Container&& other) : m_pData(NULL) {      // 4. MOVE CTOR
  *this = std::move(other);
 }
 virtual ~MyCPP11Container() { // DESTRUCTOR
                if (m_pData != NULL) {
      delete m_pData;
                }
 }

 MyCPP11Container& operator=(const MyCPP11Container& other) { // ASSIGNMENT OPTR
  if (this == &other) {
   return *this;
  }
  delete m_pData;
  m_pData = new int(*(other.m_pData));
 }

 MyCPP11Container& operator=(MyCPP11Container&& other) {      // MOVE ASSIGNMENT OPTR
  if (this == &other) {
   return *this;
  }
  delete m_pData;
  m_pData = other.m_pData;
  other.m_Ptr = nullptr; // So the destructor doesn't free memory multiple times.
 }

 operator T() const { return *m_pData; } // type conversion: (T).

private:
 T* m_pData;
};


// C++11 version of swap in <utility> behaves like this:

template <class T> void swap (T& a, T& b) {                 // moved in <utility>
  T c(std::move(a)); a=std::move(b); b=std::move(c);
}

Note that swap() has been in <algorithm> until C++11. std::move() in <utility> is the new semantic move, which is different from the ranged std::move() in <algorithm>.

typename remove_reference<T>::type&& move (T&& arg) noexcept;  // <utility>



Parallel Programming Paradigms - MPI, OpenMP and CUDA


MPI
OpenMP
CUDA
Description

Multi-threaded API
Parallel Computing Platform
and API (NVIDIA GPU)
Compiler
mpicc
gcc –fompenmp -Igomp
nvcc (LLVM-based)
Headers
#include <mpi.h>
#include <omp.h>
#include <cuda_runtime.h>
CFlags
-I/usr/lib/openmpi
-L/usr/lib/openmpi/…/lib
-lmpi
lgomp
-I/usr/local/cuda/include
-L/usr/local/cuda/lib
-lcudrt
Memory Model
Shared memory and Distributed memory
Shared memory multiprocessing
Shared memory
Concepts
Point-to-point messaging
Broadcasting (1 to M)
Scatter/Gather. Support R, C++, Java, Fortran, Python.
An add-on in compiler
Designed to work with C/C++ and Fortran. More effective for parallel computing: e.g., fast sort algorithms of large lists.
Variates
OpenMPI, MPICH2

SIMD, SIMT, SMT
Pros
More general solution;
Can run in clustering environments;
Distributed memory is less expensive
Easier to program;
Can still run the program as a serial code(no code change);

Scattered reads;
Unified virtual memory;
Fast shared memory;
Full support for integer and bitwise operations.
Cons
Code change from serial to parallel version;
Harder to debug;
Bottleneck of network communication.
Difficult to debug synchronization bugs and race conditions;
Requires compiler support;
Only in shared memory architecture;
Mostly used in loop parallelization.
Memory copy between host and device may incur performance hit due to bandwidth and latency;
Thread group with 32+ threads for best performance;
Valid C/C++ may not compile;
C++ RTTI is not support(?).

The information sources in the above table include, but not limited to, open-mpi.org, openmp.org, nvidia.com and Wikipedia.org.

Saturday, December 26, 2015

Eclipse CDT, a C++ IDEs on Windows

In addition to VC++, a few open sourced C++ IDEs are also widely used on Windows: Code::Block and Eclipse CDT.

Eclipse CDT is available in Eclipse IDE for C++ Developers or as a plugin in Eclipse. Here is how to set up Eclipse CDT for C++11.
  • Install New Software... in Eclipse IDE for Java Developers            
        (web url: http://download.eclipse.org/tools/cdt/releases/8.8)
  • Install a C++ Compiler (e.g., Cygwin including g++ and make)
  • Create New C++ Project
  • In C/C++ Build > Settings > Other Flags Box, append "-std=c++11"
The following is the screenshot of my Eclipse 


Note: RAND_MAX is a macro defined in <cstdlib>. RAND_MAX = 32,767 in VC++, while RAND_MAX = 2,147,483,647 in GNU g++.

C++ 11 New Feature List (for Quants)

This is a list of C++ 11 (https://isocpp.org/wiki/faq/cpp11) new features (relative to C++98):
  • RValue Reference and move ctor.
  • Lambda Expression (for functional programming)
  • Concurrency API (future, async)
  • New Smart Pointers (unique_ptr, shared_ptr in <memory>)
  • Fixed-length <array>
  • <random> supports Mersenne Twister(MT19937) PRNG and distributions.
  • Enhanced Containers: <forward_list> and hashed <unordered_map>
  • Compile-time static_assert with <type_traits> for template code
  • noexcept, unexpected() and the enhanced <exception>
  • <regex> with EMCAScript syntax and backreference
  • RTTI: auto, decltype, and typeid 
  • Misc (ranged for loop, nullptr, non-type template parameters)

C++ Standard Library(since C++98), which is based on STL (designed and developed by Alexander Stepanov and Meng Lee), contains key components called containers, algorithms, functional and iterators.

Here the discussion is focused on Iterator, since it is very relevant to the performance. As shown in the following graph, C++/STL has 5-category iterators. Another way to present the iterator hierarchical relationship is using UML class diagram, with Input/Output as the bases at the top and Random Access Iterator at the bottom. A rule of thumb for choosing the iterators is to pick the weakest iterator first to accommodate the most efficient algorithm.

For example,
Forward Iterator: std::replace()
Bidirectional Iterator: std::reverse()
Random Access Iterator: std::sort()

Just for fun, I collected some C++ and OOP buzzwords and put them in a table.

RAII
Resource Acquisition Is Initialization
CADR
CTOR Acquire, DTOR Release, scoped-based res mgmt
RTTI
RunTime Type Info
BSS
Block Started by Symbol. Memory Layout: Stack, [Free Memory], Heap, Initialized Data, BSS, Text.
vtable
Virtual function Table
STL
3-legged STooL: Algorithm, Iterator, Containers
Algorithms
Algorithms use iterators and containers
Iterator Types
Input/Output, Forward, Bidirectional, Random Access
Container Types
Sequential, Associative. <forward_list>, <unordered_map>
Smart Pointer
Various raw pointer wrappers in <memory>
Pragma once
Directives similar to Include Guard
ADL
Argument-dependent lookup, Koenig Lookup
Move Semantics
Most pervasive C++11 feature. Move CTOR,  Move Assignment Operator for perf. Perfect Forwarding?
Move CTOR
Move Constructor
Rvalue Reference
<utility>
Boost
Open Source Library, some added in C++11/14.
Empty Aggregate Initialization
Could be very tricky.
Non-type Template Parameters
Enhanced template.
Exception-Safety
Basic and Strong exception safety. noexcept, throw, try-catch, unexpected() in <exception>. logic_error, runtime_error in <stdexcept>
Thread-Safety
<thread>, <future>. async(), future.get(), timeout.
volatile for hardware access, std::atomic for MT.
<random>
RAND_MAX? Platform-indep? Various Probability Distributions.
assert vs static_assert
#define NDEBUG vs compile-time assert. <type_traits>
OOP Key Concepts
Encapsulation, Inheritance, Polymorphism
SOLID
Single-responsibility, Open for extension/Closed for modification, Liskov substitution, Interface segregation, Dependency inversion.
LLVM
Low Level Virtual Machine, Clang compiler
JIT vs AOT
Just-in-time(CPU cycle stealing) vs Ahead-of-time Compilation
SIMD
Single Instruction, Multiple Data -- Flynn's Taxonomy. Intel MMX, SSE, AVX. 64bit CPU has 16 GPRs.
Hi-C Lo-C
High Cohesion, Low Coupling
GoF
Gang of Four, author of “Design Patterns”
IoC
Inversion of Control. Dep. Inj. Implements IoC for resolving dependency. No need to create the object by yourself. Template Method is another IoC example.
Pimpl
(Opaque-pointer)
Pointer to IMPLementation, Compiler firewall idiom, Handle class, “Cheshire Cat”.
Forward Declaration
Reduce build time


"... as you learned more [C++11], you were surprised by the scope of the changes. auto declarations, range-based for loops, lambda expressions, and rvalue references change the face of C++, to say nothing of the new concurrency features. And then there are the idiomatic changes. NULL(0) and typedefs are out, nullptr and alias declarations are in. enums should now be scoped. Smart pointers are now preferable to built-in ones. Moving objects is normally better than copying them."
  -- 
Scott Meyers, in 
"Effective Modern C++" 2015.