├── LICENSE.txt ├── 9781430267157.jpg ├── FinancialCppSamples ├── FinancialSamples │ ├── jamroot │ ├── luatest │ ├── stock-setup.py │ ├── LuaWrap.cpp │ ├── MathFunction.cpp │ ├── IntRateEngine.cpp │ ├── CommonStock.cpp │ ├── matrix-setup.py │ ├── Stock_Py.h │ ├── LuaMain.h │ ├── Cxx1xExamples.h │ ├── OpenMpTest.h │ ├── PlotViewer.cpp │ ├── OpenMpTest.cpp │ ├── PlotViewer.h │ ├── FactorialTemplate.cpp │ ├── CommonStock.h │ ├── MathFunction.h │ ├── Matrix_Py.h │ ├── ParallelRandomWalk.h │ ├── SecantMethod.h │ ├── BisectionMethod.h │ ├── CreditRisk.cpp │ ├── IntRateCalculator.cpp │ ├── EulersMethod.h │ ├── ResourceAlloc.h │ ├── NewtonMethod.h │ ├── Option.h │ ├── TimeSeries.h │ ├── CreditRisk.h │ ├── MIPSolver.h │ ├── Thread.h │ ├── CorrelationCalculator.h │ ├── RungeKuttaODEMethod.h │ ├── QtPlotter.h │ ├── RandonWalk.h │ ├── Stock.h │ ├── BondCalculator.h │ ├── FileManager.h │ ├── MACalculator.h │ ├── RExtension.h │ ├── LinearInterpolation.h │ ├── SimpsonsIntegration.h │ ├── MidpointIntegration.h │ ├── VolatilityCalculator.h │ ├── IntRateCalculator.h │ ├── CompoundIntRateCalculator.h │ ├── LuaOption.h │ ├── Mutex.h │ ├── TrapezoidIntegration.h │ ├── FactorialTemplate.h │ ├── PolymonialInterpolation.h │ ├── CashFlowCalculator.h │ ├── NumVector.h │ ├── MonteCarloIntegration.h │ ├── Date.h │ ├── ParallelOptionsProbabilities.h │ ├── RiskCalculator.h │ ├── BlackScholesForwardMethod.h │ ├── DistributionData.h │ ├── Option.cpp │ ├── TwoDimensionalLPSolver.h │ ├── VectorOperations.h │ ├── Recommendation.h │ ├── FinancialStatement.h │ ├── CalmarRatio.cpp │ ├── CalmarRatio.h │ ├── ModifiedCAP.h │ ├── TimeSeriesTransformations.h │ ├── MatrixOperations.h │ ├── Matrix.h │ ├── RecommendationsProcessor.h │ ├── GnuplotPlotter.h │ ├── CompoundIntRateCalculator.cpp │ ├── OptionsProbabilities.h │ ├── LuaMain.cpp │ ├── BondCalculator.cpp │ ├── TransactionHandler.h │ ├── Stock.cpp │ ├── Recommendation.cpp │ ├── LPSolver.h │ ├── InvestmentInstrument.h │ ├── CorrelationCalculator.cpp │ ├── CashFlowCalculator.cpp │ ├── LuaOption.cpp │ ├── RandonWalk.cpp │ ├── IntRateEngine.h │ ├── FinancialStatement.cpp │ ├── FundamentalsCalc.h │ ├── TimeSeries.cpp │ ├── RiskCalculator.cpp │ ├── Matrix_Py.cpp │ ├── TransactionHandler.cpp │ ├── EulersMethod.cpp │ ├── RungeKuttaODEMethod.cpp │ ├── RExtension.cpp │ ├── MIPSolver.cpp │ ├── InvestmentInstrument.cpp │ ├── BisectionMethod.cpp │ ├── SecantMethod.cpp │ ├── RecommendationsProcessor.cpp │ ├── TwoDimensionalLPSolver.cpp │ ├── NumVector.cpp │ ├── Thread.cpp │ ├── MidpointIntegration.cpp │ ├── ResourceAlloc.cpp │ ├── NewtonMethod.cpp │ ├── SimpsonsIntegration.cpp │ ├── TrapezoidIntegration.cpp │ ├── VolatilityCalculator.cpp │ ├── TimeSeriesTransformations.cpp │ ├── LuaWrap.h │ ├── Mutex.cpp │ ├── VectorOperations.cpp │ ├── LinearInterpolation.cpp │ ├── MACalculator.cpp │ ├── PolymonialInterpolation.cpp │ ├── FinancialSamples.1 │ ├── FileManager.cpp │ ├── Date.cpp │ ├── GnuplotPlotter.cpp │ ├── FundamentalsCalc.cpp │ ├── DistributionData.cpp │ ├── BlackScholesForwardMethod.cpp │ ├── ParallelRandomWalk.cpp │ ├── Matrix.cpp │ ├── QtPlotter.cpp │ ├── MonteCarloIntegration.cpp │ └── Stock_Py.cpp ├── FinancialSamples.xcodeproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcuserdata │ │ │ └── carlosoliveira.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ └── carlosoliveira.xcuserdatad │ │ └── xcschemes │ │ ├── xcschememanagement.plist │ │ └── FinancialSamples.xcscheme ├── .gitignore └── MaximaCode │ ├── src │ ├── OptionProbabilityExportedFunctions.cpp │ └── OptionsProbabilities.h │ └── optionProbabilities.l ├── README.md └── contributing.md /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-cpp-financial-programming/HEAD/LICENSE.txt -------------------------------------------------------------------------------- /9781430267157.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-cpp-financial-programming/HEAD/9781430267157.jpg -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/jamroot: -------------------------------------------------------------------------------- 1 | 2 | # Declare test targets 3 | run-test hello : hello_ext hello.py ; 4 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/luatest: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-cpp-financial-programming/HEAD/FinancialCppSamples/FinancialSamples/luatest -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/stock-setup.py: -------------------------------------------------------------------------------- 1 | # to build this: 2 | # python stock-setup.py build_ext -i 3 | from distutils.core import setup, Extension 4 | 5 | setup(name="stock", version="1.0", 6 | ext_modules=[Extension("stock", ["Stock.cpp", "Stock_Py.cpp"])]) 7 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/LuaWrap.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // LuaWrapper.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "LuaWrap.h" 10 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MathFunction.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // MathFunction.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "MathFunction.h" 10 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples.xcodeproj/project.xcworkspace/xcuserdata/carlosoliveira.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/practical-cpp-financial-programming/HEAD/FinancialCppSamples/FinancialSamples.xcodeproj/project.xcworkspace/xcuserdata/carlosoliveira.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/IntRateEngine.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // IntRateEngine.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "IntRateEngine.h" 10 | 11 | 12 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CommonStock.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // CommonStock.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "CommonStock.h" 10 | 11 | #include 12 | -------------------------------------------------------------------------------- /FinancialCppSamples/.gitignore: -------------------------------------------------------------------------------- 1 | /Debug/ 2 | FinancialSamples.xcodeproj/xcuserdata/carlosoliveira.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist 3 | FinancialSamples.xcodeproj/project.xcworkspace/xcshareddata/FinancialSamples.xccheckout 4 | FinancialSamples.xcodeproj/project.xcworkspace/xcuserdata/carlosoliveira.xcuserdatad/WorkspaceSettings.xcsettings 5 | *.o 6 | *.so 7 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/matrix-setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup, Extension 2 | 3 | setup(name="matrix", version="1.0", 4 | ext_modules=[Extension("matrix", ["Matrix.cpp", "matrix_Py.cpp"], 5 | include_dirs=["/opt/local/include/"], 6 | library_dirs=["/opt/local/lib/"], 7 | libraries=["boost_python-mt"])]) 8 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Stock_Py.h: -------------------------------------------------------------------------------- 1 | // 2 | // Stock_Py.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Stock_Py__ 10 | #define __FinancialSamples__Stock_Py__ 11 | 12 | 13 | 14 | #endif /* defined(__FinancialSamples__Stock_Py__) */ 15 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/LuaMain.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaMain.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__LuaMain__ 10 | #define __FinancialSamples__LuaMain__ 11 | 12 | #include 13 | 14 | #endif /* defined(__FinancialSamples__LuaMain__) */ 15 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Cxx1xExamples.h: -------------------------------------------------------------------------------- 1 | // 2 | // Cxx1xExamples.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Cxx1xExamples__ 10 | #define __FinancialSamples__Cxx1xExamples__ 11 | 12 | 13 | #endif /* defined(__FinancialSamples__Cxx1xExamples__) */ 14 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/OpenMpTest.h: -------------------------------------------------------------------------------- 1 | // 2 | // OpenMpTest.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__OpenMpTest__ 10 | #define __FinancialSamples__OpenMpTest__ 11 | 12 | #include 13 | 14 | #endif /* defined(__FinancialSamples__OpenMpTest__) */ 15 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/PlotViewer.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // PlotViewer.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "PlotViewer.h" 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | class MainWindow : public QMainWindow { 16 | public: 17 | MainWindow(); 18 | ~MainWindow(); 19 | }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Practical C++ Financial Programming*](http://www.apress.com/9781430267157) by Carlos Oliveira (Apress, 2015). 4 | 5 | ![Cover image](9781430267157.jpg) 6 | 7 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 8 | 9 | ## Releases 10 | 11 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 12 | 13 | ## Contributions 14 | 15 | See the file Contributing.md for more information on how you can contribute to this repository. 16 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/OpenMpTest.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // OpenMpTest.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "OpenMpTest.h" 10 | 11 | #include 12 | 13 | using std::cout; 14 | using std::endl; 15 | 16 | int main_openmp() 17 | { 18 | 19 | #pragma omp for schedule(dynamic, 5) 20 | for (int i=0; i<50; ++i) 21 | { 22 | cout << " do this " << endl; 23 | } 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/PlotViewer.h: -------------------------------------------------------------------------------- 1 | // 2 | // PlotViewer.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__PlotViewer__ 10 | #define __FinancialSamples__PlotViewer__ 11 | 12 | 13 | class PlotViewer { 14 | public: 15 | PlotViewer(); 16 | PlotViewer(const PlotViewer &p); 17 | ~PlotViewer(); 18 | PlotViewer &operator=(const PlotViewer &p); 19 | }; 20 | 21 | #endif /* defined(__FinancialSamples__PlotViewer__) */ 22 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FactorialTemplate.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // FactorialTemplate.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "FactorialTemplate.h" 10 | 11 | #include 12 | 13 | void showFactorial() 14 | { 15 | std::cout << " Some factorial values: " << std::endl; 16 | std::cout << "fact(5)= " << Factorial<5>::result; 17 | std::cout << "fact(7)= " << Factorial<7>::result; 18 | std::cout << "fact(9)= " << Factorial<9>::result; 19 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples.xcodeproj/xcuserdata/carlosoliveira.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | FinancialSamples.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 735C9C7718749C9A00807DA0 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CommonStock.h: -------------------------------------------------------------------------------- 1 | // 2 | // CommonStock.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__CommonStock__ 10 | #define __FinancialSamples__CommonStock__ 11 | 12 | #include 13 | 14 | class CommonStock { 15 | public: 16 | CommonStock(const std::string ticker); 17 | ~CommonStock(); 18 | CommonStock(const CommonStock &); 19 | CommonStock operator = (const CommonStock &); 20 | 21 | std::string getTicker(); 22 | }; 23 | 24 | #endif /* defined(__FinancialSamples__CommonStock__) */ 25 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MathFunction.h: -------------------------------------------------------------------------------- 1 | // 2 | // MathFunction.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef MATHFUNCTION_H_ 10 | #define MATHFUNCTION_H_ 11 | 12 | template 13 | class MathFunction { 14 | public: 15 | MathFunction() {} 16 | virtual ~MathFunction(){} 17 | virtual Res operator()(Res x) = 0; 18 | virtual Res operator()(Res x, Res y); // version with two variables 19 | }; 20 | 21 | template 22 | Res MathFunction::operator()(Res x, Res y) 23 | { 24 | return 0; 25 | } 26 | 27 | #endif /* MATHFUNCTION_H_ */ 28 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Matrix_Py.h: -------------------------------------------------------------------------------- 1 | // 2 | // Matrix_Py.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Matrix_Py__ 10 | #define __FinancialSamples__Matrix_Py__ 11 | 12 | #include 13 | 14 | #include "Matrix.h" 15 | 16 | class MatrixP : public Matrix { 17 | public: 18 | MatrixP(int a); 19 | MatrixP(int a, int b); 20 | MatrixP(const MatrixP &p); 21 | ~MatrixP(); 22 | void set(int a, int b, double v); 23 | double get(int a, int b); 24 | }; 25 | 26 | #endif /* defined(__FinancialSamples__Matrix_Py__) */ 27 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/ParallelRandomWalk.h: -------------------------------------------------------------------------------- 1 | // 2 | // ParallelRandomWalk.h 3 | 4 | #ifndef __FinancialSamples__ParallelRandomWalk__ 5 | #define __FinancialSamples__ParallelRandomWalk__ 6 | 7 | class ParallelRandomWalk { 8 | public: 9 | ParallelRandomWalk(int size, double strike, double step); 10 | ParallelRandomWalk(const ParallelRandomWalk &p); 11 | ~ParallelRandomWalk(); 12 | ParallelRandomWalk &operator=(const ParallelRandomWalk &p); 13 | 14 | double probFinishAboveStrike(); 15 | 16 | private: 17 | int m_size; // number of steps 18 | double m_step; // size of each step (in percentage) 19 | double m_start; // starting price 20 | }; 21 | 22 | #endif /* defined(__FinancialSamples__ParallelRandomWalk__) */ 23 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/SecantMethod.h: -------------------------------------------------------------------------------- 1 | // 2 | // SecantMethod.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef SECANTMETHOD_H_ 10 | #define SECANTMETHOD_H_ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class SecantMethod { 16 | public: 17 | SecantMethod(MathFunction &f); 18 | SecantMethod(const SecantMethod &p); 19 | SecantMethod &operator=(const SecantMethod &p); 20 | ~SecantMethod(); 21 | 22 | double getRoot(double x1, double x2); 23 | private: 24 | MathFunction &m_f; 25 | double m_error; 26 | }; 27 | 28 | #endif /* SECANTMETHOD_H_ */ 29 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/BisectionMethod.h: -------------------------------------------------------------------------------- 1 | // 2 | // BisectionMethod.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef BISECTIONMETHOD_H_ 10 | #define BISECTIONMETHOD_H_ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class BisectionMethod { 16 | public: 17 | BisectionMethod(MathFunction &f); 18 | BisectionMethod(const BisectionMethod &p); 19 | ~BisectionMethod(); 20 | BisectionMethod &operator=(const BisectionMethod &p); 21 | double getRoot(double x1, double x2); 22 | 23 | private: 24 | MathFunction &m_f; 25 | double m_error; 26 | }; 27 | 28 | #endif /* BISECTIONMETHOD_H_ */ 29 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CreditRisk.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // CreditRisk.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "CreditRisk.h" 10 | 11 | #include 12 | 13 | 14 | CreditRisk::CreditRisk() 15 | { 16 | 17 | } 18 | 19 | CreditRisk::~CreditRisk() 20 | { 21 | 22 | } 23 | 24 | CreditRisk::CreditRisk(const CreditRisk &a) 25 | { 26 | 27 | } 28 | 29 | CreditRisk &CreditRisk::operator =(const CreditRisk &a) 30 | { 31 | return *this; 32 | } 33 | 34 | CreditRisk::RiskType CreditRisk::getRating() 35 | { 36 | RiskType type = RiskType::AAA; 37 | // define the right type here... 38 | return type; 39 | } 40 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/IntRateCalculator.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // IntRateCalculator.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "IntRateCalculator.h" 10 | 11 | 12 | IntRateCalculator::IntRateCalculator(double rate) 13 | : m_rate(rate) 14 | { 15 | 16 | } 17 | 18 | IntRateCalculator::~IntRateCalculator() 19 | { 20 | 21 | } 22 | 23 | IntRateCalculator::IntRateCalculator(const IntRateCalculator &v) 24 | : m_rate(v.m_rate) 25 | { 26 | 27 | } 28 | 29 | IntRateCalculator &IntRateCalculator::operator=(const IntRateCalculator &v) 30 | { 31 | if (&v != this) { 32 | this->m_rate = v.m_rate; 33 | } 34 | return *this; 35 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/EulersMethod.h: -------------------------------------------------------------------------------- 1 | // 2 | // EulersMethod.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__EulersMethod__ 10 | #define __FinancialSamples__EulersMethod__ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class EulersMethod { 16 | public: 17 | EulersMethod(MathFunction &f); 18 | EulersMethod(const EulersMethod &p); 19 | ~EulersMethod(); 20 | EulersMethod &operator=(const EulersMethod &p); 21 | 22 | double solve(int n, double x0, double y0, double c); 23 | private: 24 | MathFunction &m_f; 25 | }; 26 | 27 | #endif /* defined(__FinancialSamples__EulersMethod__) */ 28 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/ResourceAlloc.h: -------------------------------------------------------------------------------- 1 | // 2 | // ResourceAlloc.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__ResourceAlloc__ 10 | #define __FinancialSamples__ResourceAlloc__ 11 | 12 | #include 13 | 14 | class ResourceAlloc { 15 | public: 16 | ResourceAlloc(std::vector &result, double &objVal); 17 | ResourceAlloc(const ResourceAlloc &p); 18 | ~ResourceAlloc(); 19 | ResourceAlloc &operator=(const ResourceAlloc &p); 20 | 21 | void solveProblem(); 22 | private: 23 | std::vector &m_results; 24 | double &m_objVal; 25 | }; 26 | 27 | 28 | #endif /* defined(__FinancialSamples__ResourceAlloc__) */ 29 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/NewtonMethod.h: -------------------------------------------------------------------------------- 1 | // 2 | // NewtonMethod.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef NEWTONMETHOD_H_ 10 | #define NEWTONMETHOD_H_ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class NewtonMethod { 16 | public: 17 | NewtonMethod(MathFunction &f, MathFunction &derivative); 18 | NewtonMethod(const NewtonMethod &p); 19 | virtual ~NewtonMethod(); 20 | NewtonMethod &operator=(const NewtonMethod &p); 21 | 22 | double getRoot(double initialValue); 23 | private: 24 | MathFunction &m_f; 25 | MathFunction &m_derivative; 26 | double m_error; 27 | }; 28 | 29 | 30 | #endif /* NEWTONMETHOD_H_ */ 31 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Option.h: -------------------------------------------------------------------------------- 1 | // 2 | // Option.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Option__ 10 | #define __FinancialSamples__Option__ 11 | 12 | #include 13 | 14 | class Option { 15 | public: 16 | Option(const std::string &ticker, double strike); 17 | Option(const Option &p); 18 | ~Option(); 19 | Option &operator=(const Option &p); 20 | 21 | std::string ticker(); 22 | double strike(); 23 | 24 | void setTicker(const std::string &); 25 | void setStrike(double); 26 | 27 | private: 28 | std::string m_ticker; 29 | double m_strike; 30 | 31 | }; 32 | 33 | #endif /* defined(__FinancialSamples__Option__) */ 34 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/TimeSeries.h: -------------------------------------------------------------------------------- 1 | // 2 | // TimeSeries.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__TimeSeries__ 10 | #define __FinancialSamples__TimeSeries__ 11 | 12 | #include 13 | #include 14 | 15 | class TimeSeries 16 | { 17 | public: 18 | TimeSeries(); 19 | TimeSeries(const TimeSeries &); 20 | TimeSeries &operator=(const TimeSeries &); 21 | ~TimeSeries(); 22 | 23 | void addValue(double val); 24 | double stdDev(); 25 | double mean(); 26 | size_t size(); 27 | double elem(int i); 28 | private: 29 | std::vector m_values; 30 | }; 31 | 32 | #endif /* defined(__FinancialSamples__TimeSeries__) */ 33 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CreditRisk.h: -------------------------------------------------------------------------------- 1 | // 2 | // CreditRisk.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__CreditRisk__ 10 | #define __FinancialSamples__CreditRisk__ 11 | 12 | class CreditRisk { 13 | public: 14 | enum RiskType { 15 | AAA, 16 | AAPlus, 17 | AA, 18 | APlus, 19 | A, 20 | BPlus, 21 | B, 22 | CPlus, 23 | C 24 | }; 25 | 26 | 27 | RiskType getRating(); 28 | 29 | CreditRisk(); 30 | ~CreditRisk(); 31 | CreditRisk(const CreditRisk &); 32 | CreditRisk &operator =(const CreditRisk &); 33 | 34 | }; 35 | 36 | 37 | 38 | #endif /* defined(__FinancialSamples__CreditRisk__) */ 39 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MIPSolver.h: -------------------------------------------------------------------------------- 1 | // 2 | // MIPSolver.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__MIPSolver__ 10 | #define __FinancialSamples__MIPSolver__ 11 | 12 | #include "LPSolver.h" 13 | 14 | class MIPSolver : public LPSolver { 15 | public: 16 | MIPSolver(Matrix &A, const std::vector &b, const std::vector &c); 17 | MIPSolver(const MIPSolver &p); 18 | ~MIPSolver(); 19 | MIPSolver &operator=(const MIPSolver &p); 20 | 21 | void setColInteger(int colNum); 22 | void setColBinary(int colNum); 23 | virtual ResultType solve(std::vector &result, double &objValue); 24 | }; 25 | 26 | #endif /* defined(__FinancialSamples__MIPSolver__) */ 27 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Thread.h: -------------------------------------------------------------------------------- 1 | // 2 | // Thread.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Thread__ 10 | #define __FinancialSamples__Thread__ 11 | 12 | struct ThreadData; 13 | 14 | class Thread { 15 | public: 16 | Thread(); 17 | virtual ~Thread(); 18 | private: 19 | Thread(const Thread &p); // no copy allowed 20 | Thread &operator=(const Thread &p); // no assignment allowed 21 | 22 | public: 23 | virtual void run() = 0; 24 | void start(); 25 | void endThread(); 26 | void setJoinable(bool yes); 27 | void join(); 28 | 29 | private: 30 | ThreadData *m_data; 31 | bool m_joinable; 32 | }; 33 | 34 | 35 | #endif /* defined(__FinancialSamples__Thread__) */ 36 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CorrelationCalculator.h: -------------------------------------------------------------------------------- 1 | // 2 | // CorrelationCalculator.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__CorrelationCalculator__ 10 | #define __FinancialSamples__CorrelationCalculator__ 11 | 12 | class TimeSeries; 13 | 14 | class CorrelationCalculator 15 | { 16 | public: 17 | CorrelationCalculator(TimeSeries &a, TimeSeries &b); 18 | ~CorrelationCalculator(); 19 | CorrelationCalculator(const CorrelationCalculator &); 20 | CorrelationCalculator &operator =(const CorrelationCalculator &); 21 | 22 | double correlation(); 23 | private: 24 | TimeSeries &m_tsA; 25 | TimeSeries &m_tsB; 26 | }; 27 | 28 | #endif /* defined(__FinancialSamples__CorrelationCalculator__) */ 29 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RungeKuttaODEMethod.h: -------------------------------------------------------------------------------- 1 | // 2 | // RungeKuttaODEMethod.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__RungeKuttaODEMethod__ 10 | #define __FinancialSamples__RungeKuttaODEMethod__ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class RungeKuttaODEMethod { 16 | public: 17 | RungeKuttaODEMethod(MathFunction &f); 18 | RungeKuttaODEMethod(const RungeKuttaODEMethod &p); 19 | ~RungeKuttaODEMethod(); 20 | RungeKuttaODEMethod &operator=(const RungeKuttaODEMethod &p); 21 | double solve(int n, double x0, double y0, double c); 22 | private: 23 | MathFunction &m_f; 24 | }; 25 | 26 | #endif /* defined(__FinancialSamples__RungeKuttaODEMethod__) */ 27 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/QtPlotter.h: -------------------------------------------------------------------------------- 1 | // 2 | // QtPlotter.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__QtPlotter__ 10 | #define __FinancialSamples__QtPlotter__ 11 | 12 | #include 13 | #include 14 | 15 | class QtPlotter { 16 | public: 17 | QtPlotter(); 18 | QtPlotter(const QtPlotter &p); 19 | ~QtPlotter(); 20 | QtPlotter &operator=(const QtPlotter &p); 21 | void setData(const std::vector &xdata, const std::vector &ydata); 22 | int plotWindowRun(int argc, char **argv); 23 | int plotWindowRun(); 24 | private: 25 | std::vector m_xdata; 26 | std::vector m_ydata; 27 | }; 28 | 29 | 30 | 31 | 32 | #endif /* defined(__FinancialSamples__QtPlotter__) */ 33 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RandonWalk.h: -------------------------------------------------------------------------------- 1 | // 2 | // RandonWalk.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__RandonWalk__ 10 | #define __FinancialSamples__RandonWalk__ 11 | 12 | #include 13 | 14 | // Simple random walk for price simulation 15 | class RandomWalk { 16 | public: 17 | RandomWalk(int size, double start, double step); 18 | RandomWalk(const RandomWalk &p); 19 | ~RandomWalk(); 20 | RandomWalk &operator=(const RandomWalk &p); 21 | 22 | std::vector getWalk(); 23 | private: 24 | int m_size; // number of steps 25 | double m_step; // size of each step (in percentage) 26 | double m_start; // starting price 27 | }; 28 | 29 | 30 | #endif /* defined(__FinancialSamples__RandonWalk__) */ 31 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Stock.h: -------------------------------------------------------------------------------- 1 | // 2 | // Stock.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Stock__ 10 | #define __FinancialSamples__Stock__ 11 | 12 | #include 13 | 14 | class Stock { 15 | public: 16 | Stock(const std::string &ticker, double price, double div); 17 | Stock(const Stock &p); 18 | ~Stock(); 19 | Stock &operator=(const Stock &p); 20 | 21 | std::string ticker(); 22 | double price(); 23 | void setPrice(double price); 24 | double dividend(); 25 | void setDividend(double div); 26 | double dividendYield(); 27 | 28 | private: 29 | std::string m_ticker; 30 | double m_currentPrice; 31 | double m_dividend; 32 | }; 33 | 34 | #endif /* defined(__FinancialSamples__Stock__) */ 35 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/BondCalculator.h: -------------------------------------------------------------------------------- 1 | // 2 | // BondCalculator.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__BondCalculator__ 10 | #define __FinancialSamples__BondCalculator__ 11 | 12 | #include 13 | 14 | class BondCalculator { 15 | public: 16 | BondCalculator(const std::string institution, int numPeriods, double principal, double couponValue); 17 | BondCalculator(const BondCalculator &v); 18 | BondCalculator &operator =(const BondCalculator &v); 19 | ~BondCalculator(); 20 | 21 | double interestRate(); 22 | 23 | private: 24 | std::string m_institution; 25 | double m_principal; 26 | double m_coupon; 27 | int m_numPeriods; 28 | }; 29 | 30 | #endif /* defined(__FinancialSamples__BondCalculator__) */ 31 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FileManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // FileManager.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__FileManager__ 10 | #define __FinancialSamples__FileManager__ 11 | 12 | #include 13 | #include 14 | 15 | class FileManager { 16 | public: 17 | FileManager(const std::string &basePath); 18 | FileManager(const FileManager &); 19 | ~FileManager(); 20 | FileManager &operator=(const FileManager &); 21 | 22 | void removeFiles(); 23 | std::vector getDirectoryContents(); 24 | void listContents(); 25 | void copyToTempDirectory(const std::string &prefix); 26 | 27 | private: 28 | std::string m_basePath; 29 | }; 30 | 31 | 32 | #endif /* defined(__FinancialSamples__FileManager__) */ 33 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MACalculator.h: -------------------------------------------------------------------------------- 1 | // 2 | // MACalculator.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__MACalculator__ 10 | #define __FinancialSamples__MACalculator__ 11 | 12 | #include 13 | 14 | class MACalculator { 15 | public: 16 | MACalculator(int period); 17 | MACalculator(const MACalculator &); 18 | MACalculator &operator = (const MACalculator &); 19 | ~MACalculator(); 20 | 21 | void addPriceQuote(double close); 22 | std::vector calculateMA(); 23 | std::vector calculateEMA(); 24 | private: 25 | // number of periods used in the calculation 26 | int m_numPeriods; 27 | std::vector m_prices; 28 | }; 29 | 30 | 31 | #endif /* defined(__FinancialSamples__MACalculator__) */ 32 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RExtension.h: -------------------------------------------------------------------------------- 1 | // 2 | // RExtension.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #ifndef __FinancialSamples__RExtension__ 11 | #define __FinancialSamples__RExtension__ 12 | 13 | #include 14 | 15 | class RExtension { 16 | public: 17 | RExtension(double rate); 18 | RExtension(const RExtension &p); 19 | ~RExtension(); 20 | RExtension &operator=(const RExtension &p); 21 | 22 | void addCashPayment(double value, int timePeriod); 23 | double presentValue(); 24 | private: 25 | std::vector m_cashPayments; 26 | std::vector m_timePeriods; 27 | double m_rate; 28 | double presentValue(double futureValue, int timePeriod); 29 | }; 30 | 31 | #endif /* defined(__FinancialSamples__RExtension__) */ 32 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/LinearInterpolation.h: -------------------------------------------------------------------------------- 1 | // 2 | // LinearInterpolation.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__LinearInterpolation__ 10 | #define __FinancialSamples__LinearInterpolation__ 11 | 12 | #include 13 | 14 | class LinearInterpolation { 15 | public: 16 | LinearInterpolation(); 17 | LinearInterpolation(const LinearInterpolation &p); 18 | ~LinearInterpolation(); 19 | LinearInterpolation &operator=(const LinearInterpolation &p); 20 | void setPoints(const std::vector &xpoints, const std::vector &ypoints); 21 | double getValue(double x); 22 | private: 23 | std::vector m_x; 24 | std::vector m_y; 25 | }; 26 | 27 | #endif /* defined(__FinancialSamples__LinearInterpolation__) */ 28 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/SimpsonsIntegration.h: -------------------------------------------------------------------------------- 1 | // 2 | // SimpsonsIntegration.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__SimpsonsIntegration__ 10 | #define __FinancialSamples__SimpsonsIntegration__ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class SimpsonsIntegration { 16 | public: 17 | SimpsonsIntegration(MathFunction &f); 18 | SimpsonsIntegration(const SimpsonsIntegration &p); 19 | ~SimpsonsIntegration(); 20 | SimpsonsIntegration &operator=(const SimpsonsIntegration &p); 21 | 22 | double getIntegral(double a, double b); 23 | void setNumIntervals(int n); 24 | private: 25 | MathFunction &m_f; 26 | int m_numIntervals; 27 | }; 28 | 29 | #endif /* defined(__FinancialSamples__SimpsonsIntegration__) */ 30 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MidpointIntegration.h: -------------------------------------------------------------------------------- 1 | // 2 | // MidpointIntegration.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__MidpointIntegration__ 10 | #define __FinancialSamples__MidpointIntegration__ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class MidpointIntegration { 16 | public: 17 | MidpointIntegration(MathFunction &f); 18 | MidpointIntegration(const MidpointIntegration &p); 19 | ~MidpointIntegration(); 20 | MidpointIntegration &operator=(const MidpointIntegration &p); 21 | 22 | void setNumIntervals(int n); 23 | double getIntegral(double a, double b); 24 | 25 | private: 26 | MathFunction &m_f; 27 | int m_numIntervals; 28 | 29 | }; 30 | #endif /* defined(__FinancialSamples__MidpointIntegration__) */ 31 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/VolatilityCalculator.h: -------------------------------------------------------------------------------- 1 | // 2 | // VolatilityCalculator.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__VolatilityCalculator__ 10 | #define __FinancialSamples__VolatilityCalculator__ 11 | 12 | #include 13 | 14 | class VolatilityCalculator 15 | { 16 | public: 17 | VolatilityCalculator(); 18 | ~VolatilityCalculator(); 19 | VolatilityCalculator(const VolatilityCalculator &); 20 | VolatilityCalculator &operator=(const VolatilityCalculator &); 21 | 22 | void addPrice(double price); 23 | double rangeVolatility(); 24 | double stdDev(); 25 | double mean(); 26 | double avgDailyRange(); 27 | private: 28 | std::vector m_prices; 29 | }; 30 | 31 | #endif /* defined(__FinancialSamples__VolatilityCalculator__) */ 32 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/IntRateCalculator.h: -------------------------------------------------------------------------------- 1 | // 2 | // IntRateCalculator.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__IntRateCalculator__ 10 | #define __FinancialSamples__IntRateCalculator__ 11 | 12 | #include 13 | 14 | class IntRateCalculator { 15 | public: 16 | IntRateCalculator(double rate); 17 | IntRateCalculator(const IntRateCalculator &v); 18 | IntRateCalculator &operator =(const IntRateCalculator &v); 19 | ~IntRateCalculator(); 20 | 21 | double singlePeriod(double value); 22 | private: 23 | double m_rate; 24 | }; 25 | 26 | inline double IntRateCalculator::singlePeriod(double value) 27 | { 28 | double f = value * ( 1 + this->m_rate ); 29 | return f; 30 | } 31 | 32 | #endif /* defined(__FinancialSamples__IntRateCalculator__) */ 33 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CompoundIntRateCalculator.h: -------------------------------------------------------------------------------- 1 | // 2 | // CompoundIntRateCalculator.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__CompoundIntRateCalculator__ 10 | #define __FinancialSamples__CompoundIntRateCalculator__ 11 | 12 | 13 | class CompoundIntRateCalculator { 14 | public: 15 | CompoundIntRateCalculator(double rate); 16 | CompoundIntRateCalculator(const CompoundIntRateCalculator &v); 17 | CompoundIntRateCalculator &operator =(const CompoundIntRateCalculator &v); 18 | ~CompoundIntRateCalculator(); 19 | 20 | double multiplePeriod(double value, int numPeriods); 21 | double continuousCompounding(double value, int numPeriods); 22 | private: 23 | double m_rate; 24 | }; 25 | 26 | #endif /* defined(__FinancialSamples__CompoundIntRateCalculator__) */ 27 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/LuaOption.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaOption.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__LuaOption__ 10 | #define __FinancialSamples__LuaOption__ 11 | 12 | #include "LuaWrap.h" 13 | 14 | class Option; 15 | 16 | #include 17 | 18 | class LuaOption { 19 | public: 20 | LuaOption(lua_State *l); 21 | void setObject(lua_State *l); 22 | 23 | static const char className[]; 24 | static LuaWrapper::RegType methods[]; 25 | 26 | // Lua functions should receive lua_State and return int 27 | int ticker(lua_State *l); 28 | int strike(lua_State *l); 29 | 30 | int setTicker(lua_State *l); 31 | int setStrike(lua_State *l); 32 | private: 33 | Option *m_option; 34 | }; 35 | 36 | #endif /* defined(__FinancialSamples__LuaOption__) */ 37 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Mutex.h: -------------------------------------------------------------------------------- 1 | // 2 | // Mutex.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Mutex__ 10 | #define __FinancialSamples__Mutex__ 11 | 12 | struct MutexData; 13 | 14 | class Mutex { 15 | public: 16 | Mutex(); 17 | ~Mutex(); 18 | 19 | void lock(); 20 | void unlock(); 21 | private: 22 | Mutex(const Mutex &p); // copy not allowed 23 | Mutex &operator=(const Mutex &p); // assignment not allowed 24 | 25 | MutexData *m_data; 26 | }; 27 | 28 | 29 | class MutexAccess { 30 | public: 31 | MutexAccess(Mutex &m); 32 | ~MutexAccess(); 33 | private: 34 | MutexAccess &operator=(const MutexAccess &p); 35 | MutexAccess(const MutexAccess &p); 36 | 37 | Mutex &m_mutex; 38 | }; 39 | 40 | 41 | #endif /* defined(__FinancialSamples__Mutex__) */ 42 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/TrapezoidIntegration.h: -------------------------------------------------------------------------------- 1 | // 2 | // TrapezoidIntegration.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__TrapezoidIntegration__ 10 | #define __FinancialSamples__TrapezoidIntegration__ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class TrapezoidIntegration { 16 | public: 17 | TrapezoidIntegration(MathFunction &f); 18 | TrapezoidIntegration(const TrapezoidIntegration &p); 19 | ~TrapezoidIntegration(); 20 | TrapezoidIntegration &operator=(const TrapezoidIntegration &p); 21 | 22 | void setNumIntervals(int n); 23 | double getIntegral(double a, double b); 24 | 25 | private: 26 | MathFunction &m_f; 27 | int m_numIntervals; 28 | 29 | }; 30 | 31 | #endif /* defined(__FinancialSamples__TrapezoidIntegration__) */ 32 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FactorialTemplate.h: -------------------------------------------------------------------------------- 1 | // 2 | // FactorialTemplate.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__FactorialTemplate__ 10 | #define __FinancialSamples__FactorialTemplate__ 11 | 12 | template 13 | class Factorial { 14 | public: 15 | enum { 16 | result = Factorial::result * N 17 | }; 18 | private: 19 | 20 | }; 21 | 22 | template <> 23 | class Factorial<0> { 24 | public: 25 | enum { 26 | result = 1 27 | }; 28 | }; 29 | 30 | 31 | template 32 | class ChoiceNumber { 33 | public: 34 | enum { 35 | result = Factorial::result / (Factorial

::result * Factorial::result) 36 | }; 37 | }; 38 | 39 | void showFactorial(); 40 | 41 | 42 | 43 | #endif /* defined(__FinancialSamples__FactorialTemplate__) */ 44 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/PolymonialInterpolation.h: -------------------------------------------------------------------------------- 1 | // 2 | // PolymonialInterpolation.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__PolymonialInterpolation__ 10 | #define __FinancialSamples__PolymonialInterpolation__ 11 | 12 | #include 13 | 14 | class PolynomialInterpolation { 15 | public: 16 | PolynomialInterpolation(); 17 | PolynomialInterpolation(const PolynomialInterpolation &p); 18 | ~PolynomialInterpolation(); 19 | PolynomialInterpolation &operator=(const PolynomialInterpolation &); 20 | void setPoints(const std::vector &x, const std::vector &y); 21 | double getPolynomial(double x); 22 | private: 23 | std::vector m_x; 24 | std::vector m_y; 25 | }; 26 | 27 | #endif /* defined(__FinancialSamples__PolymonialInterpolation__) */ 28 | -------------------------------------------------------------------------------- /FinancialCppSamples/MaximaCode/src/OptionProbabilityExportedFunctions.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // OptionProbabilityExportedFunctions.cpp 3 | #include "OptionsProbabilities.h" 4 | 5 | extern "C" double __declspec(dllexport) optionProbFinishAboveStrike(double initialPrice, 6 | double strike, double avgStep, int nDays) { 7 | OptionsProbabilities optP(initialPrice, strike, avgStep, nDays); 8 | return optP.probFinishAboveStrike(); 9 | } 10 | 11 | extern "C" double __declspec(dllexport) optionProbFinishBellowStrike(double initialPrice, 12 | double strike, double avgStep, int nDays) { 13 | OptionsProbabilities optP(initialPrice, strike, avgStep, nDays); 14 | return optP.probFinishBellowStrike(); 15 | } 16 | 17 | extern "C" double __declspec(dllexport) optionProbFinishBetweenPrices(double initialPrice, 18 | double strike, double avgStep, int nDays, double lowPrice, double highPrice) { 19 | OptionsProbabilities optP(initialPrice, strike, avgStep, nDays); 20 | return optP.probFinalPriceBetweenPrices(lowPrice, highPrice); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CashFlowCalculator.h: -------------------------------------------------------------------------------- 1 | // 2 | // CashFlowCalculator.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__CashFlowCalculator__ 10 | #define __FinancialSamples__CashFlowCalculator__ 11 | 12 | #include 13 | 14 | class CashFlowCalculator { 15 | public: 16 | CashFlowCalculator(double rate); 17 | CashFlowCalculator(const CashFlowCalculator &v); 18 | CashFlowCalculator &operator =(const CashFlowCalculator &v); 19 | ~CashFlowCalculator(); 20 | 21 | void addCashPayment(double value, int timePeriod); 22 | double presentValue(); 23 | private: 24 | std::vector m_cashPayments; 25 | std::vector m_timePeriods; 26 | double m_rate; 27 | double presentValue(double futureValue, int timePeriod); 28 | }; 29 | 30 | #endif /* defined(__FinancialSamples__CashFlowCalculator__) */ 31 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/NumVector.h: -------------------------------------------------------------------------------- 1 | // 2 | // NumVector.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__NumVector__ 10 | #define __FinancialSamples__NumVector__ 11 | 12 | #include 13 | #include 14 | 15 | class NumVector { 16 | public: 17 | NumVector(); 18 | ~NumVector(); 19 | NumVector(const NumVector &); 20 | NumVector &operator =(const NumVector &); 21 | 22 | void add(double val); 23 | void removeLast(); 24 | double get(int pos) const; 25 | size_t size() const; 26 | private: 27 | std::vector m_values; 28 | }; 29 | 30 | NumVector operator +(const NumVector &a, const NumVector &b); 31 | NumVector operator -(const NumVector &a, const NumVector &b); 32 | NumVector operator *(const NumVector &a, const NumVector &b); 33 | 34 | #endif /* defined(__FinancialSamples__NumVector__) */ 35 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MonteCarloIntegration.h: -------------------------------------------------------------------------------- 1 | // 2 | // MonteCarloIntegration.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__MONTECARLOINTEGRATION_H_ 10 | #define __FinancialSamples__MONTECARLOINTEGRATION_H_ 11 | 12 | template 13 | class MathFunction; 14 | 15 | class MonteCarloIntegration { 16 | public: 17 | MonteCarloIntegration(MathFunction &f); 18 | MonteCarloIntegration(const MonteCarloIntegration &p); 19 | ~MonteCarloIntegration(); 20 | MonteCarloIntegration &operator=(const MonteCarloIntegration &p); 21 | 22 | void setNumSamples(int n); 23 | double getIntegral(double a, double b); 24 | double integrateRegion(double a, double b, double min, double max); 25 | private: 26 | MathFunction &m_f; 27 | int m_numSamples; 28 | 29 | }; 30 | 31 | 32 | 33 | 34 | #endif /* MONTECARLOINTEGRATION_H_ */ 35 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Date.h: -------------------------------------------------------------------------------- 1 | // 2 | // Date.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Date__ 10 | #define __FinancialSamples__Date__ 11 | 12 | #include 13 | 14 | class Date { 15 | public: 16 | 17 | enum DayOfWeek { 18 | Sun, 19 | Mon, 20 | Tue, 21 | Wed, 22 | Thu, 23 | Fri, 24 | Sat 25 | }; 26 | 27 | Date(int year, int month, int day); 28 | ~Date(); 29 | 30 | bool isLeapYear(); 31 | Date &operator++(); 32 | bool operator<(const Date &d); 33 | DayOfWeek getDayOfWeek(); 34 | int daysInterval(const Date &); 35 | bool isTradingDay(); 36 | std::string toStringDate(Date::DayOfWeek day); 37 | private: 38 | int m_year; 39 | int m_month; 40 | int m_day; 41 | }; 42 | 43 | 44 | #endif /* defined(__FinancialSamples__Date__) */ 45 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/ParallelOptionsProbabilities.h: -------------------------------------------------------------------------------- 1 | // 2 | // ParallelRandomWalk.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__ParallelRandomWalk__ 10 | #define __FinancialSamples__ParallelRandomWalk__ 11 | 12 | class ParallelOptionsProbabilities { 13 | public: 14 | ParallelOptionsProbabilities(int size, double strike, double sigma); 15 | ParallelOptionsProbabilities(const ParallelOptionsProbabilities &p); 16 | ~ParallelOptionsProbabilities(); 17 | ParallelOptionsProbabilities &operator=(const ParallelOptionsProbabilities &p); 18 | 19 | double probFinishAboveStrike(); 20 | 21 | private: 22 | int m_numSteps; // number of steps 23 | double m_step; // size of each step (in percentage) 24 | double m_strikePrice; // starting price 25 | }; 26 | 27 | #endif /* defined(__FinancialSamples__ParallelRandomWalk__) */ 28 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RiskCalculator.h: -------------------------------------------------------------------------------- 1 | // 2 | // RiskCalculator.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__RiskCalculator__ 10 | #define __FinancialSamples__RiskCalculator__ 11 | 12 | #include "CreditRisk.h" 13 | 14 | #include 15 | #include 16 | 17 | // calculates the risk associated to a portfolio 18 | class RiskCalculator { 19 | public: 20 | RiskCalculator(); 21 | ~RiskCalculator(); 22 | RiskCalculator(const RiskCalculator &); 23 | RiskCalculator &operator =(const RiskCalculator &); 24 | 25 | void addCreditRisk(std::shared_ptr risk); 26 | 27 | CreditRisk::RiskType portfolioMaxRisk(); 28 | CreditRisk::RiskType portfolioMinRisk(); 29 | private: 30 | std::vector > m_creditRisks; 31 | }; 32 | 33 | #endif /* defined(__FinancialSamples__RiskCalculator__) */ 34 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/BlackScholesForwardMethod.h: -------------------------------------------------------------------------------- 1 | // 2 | // BlackScholesFowardMethod.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #ifndef __FinancialSamples__BlackScholesFowardMethod__ 11 | #define __FinancialSamples__BlackScholesFowardMethod__ 12 | 13 | #include 14 | 15 | class BlackScholesForwardMethod { 16 | public: 17 | BlackScholesForwardMethod(double expiration, double maxPrice, double strike, double intRate); 18 | BlackScholesForwardMethod(const BlackScholesForwardMethod &p); 19 | ~BlackScholesForwardMethod(); 20 | BlackScholesForwardMethod &operator=(const BlackScholesForwardMethod &p); 21 | 22 | std::vector solve(double volatility, int nx, int timeSteps); 23 | private: 24 | double m_expiration; 25 | double m_maxPrice; 26 | double m_strike; 27 | double m_intRate; 28 | }; 29 | 30 | 31 | #endif /* defined(__FinancialSamples__BlackScholesFowardMethod__) */ 32 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/DistributionData.h: -------------------------------------------------------------------------------- 1 | // 2 | // DistributionData.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #ifndef DISTRIBUTIONDATA_H_ 11 | #define DISTRIBUTIONDATA_H_ 12 | 13 | #include 14 | 15 | class DistributionData { 16 | public: 17 | DistributionData(); 18 | ~DistributionData(); 19 | std::vector gaussianData(int nPoints, double mean, double sigma); 20 | std::vector exponentialData(int nPoints, double rate); 21 | std::vector chiSquaredData(int nPoints, int degreesOfFreedom); 22 | std::vector logNormalData(int nPoints, double mean, double sigma); 23 | 24 | double gaussianQuantile(double x, double mean, double sigma); 25 | double chiSquaredQuantile(double x, int degreesOfFreedom); 26 | double exponentialQuantile(double x, double rate); 27 | double logNormalQuantile(double x, double mean, double sigma); 28 | }; 29 | 30 | #endif /* DISTRIBUTIONDATA_H_ */ 31 | -------------------------------------------------------------------------------- /FinancialCppSamples/MaximaCode/src/OptionsProbabilities.h: -------------------------------------------------------------------------------- 1 | // 2 | // OptionsProbabilities.h 3 | 4 | #ifndef __FinancialSamples__OptionsProbabilities__ 5 | #define __FinancialSamples__OptionsProbabilities__ 6 | 7 | #include 8 | 9 | class OptionsProbabilities { 10 | public: 11 | OptionsProbabilities(double initialPrice, double strike, double avgStep, int nDays); 12 | OptionsProbabilities(const OptionsProbabilities &p); 13 | ~OptionsProbabilities(); 14 | OptionsProbabilities &operator=(const OptionsProbabilities &p); 15 | 16 | void setNumIterations(int n); 17 | 18 | double probFinishAboveStrike(); 19 | double probFinishBellowStrike(); 20 | double probFinalPriceBetweenPrices(double lowPrice, double highPrice); 21 | std::vector getWalk(); 22 | private: 23 | double m_initialPrice; 24 | double m_strike; 25 | double m_avgStep; 26 | int m_numDays; 27 | int m_numIterations; 28 | 29 | double gaussianValue(double mean, double sigma); 30 | double getLastPriceOfWalk(); 31 | }; 32 | 33 | #endif /* defined(__FinancialSamples__OptionsProbabilities__) */ 34 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Option.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Option.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "Option.h" 10 | 11 | 12 | Option::Option(const std::string &ticker, double strike) 13 | : m_ticker(ticker), 14 | m_strike(strike) 15 | { 16 | } 17 | 18 | Option::Option(const Option &p) 19 | : m_ticker(p.m_ticker), 20 | m_strike(p.m_strike) 21 | { 22 | } 23 | 24 | Option::~Option() 25 | { 26 | } 27 | 28 | Option &Option::operator=(const Option &p) 29 | { 30 | if (this != &p) 31 | { 32 | m_ticker = p.m_ticker; 33 | m_strike = p.m_strike; 34 | } 35 | return *this; 36 | } 37 | 38 | std::string Option::ticker() 39 | { 40 | return m_ticker; 41 | } 42 | 43 | double Option::strike() 44 | { 45 | return m_strike; 46 | } 47 | 48 | void Option::setTicker(const std::string &s) 49 | { 50 | m_ticker = s; 51 | } 52 | 53 | void Option::setStrike(double val) 54 | { 55 | m_strike = val; 56 | } 57 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/TwoDimensionalLPSolver.h: -------------------------------------------------------------------------------- 1 | // 2 | // TwoDimensionalLPSolver.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__TwoDimensionalLPSolver__ 10 | #define __FinancialSamples__TwoDimensionalLPSolver__ 11 | 12 | #include 13 | 14 | class TwoDimensionalLPSolver { 15 | public: 16 | typedef std::vector Vector; 17 | 18 | TwoDimensionalLPSolver(const Vector &c, const Vector &A1, const Vector &A2, const Vector &b); 19 | TwoDimensionalLPSolver(const TwoDimensionalLPSolver &p); 20 | ~TwoDimensionalLPSolver(); 21 | TwoDimensionalLPSolver &operator=(const TwoDimensionalLPSolver &p); 22 | 23 | bool solveProblem(Vector &results, double &objVal); 24 | private: 25 | std::vector m_c; 26 | std::vector m_A1; 27 | std::vector m_A2; 28 | std::vector m_b; 29 | }; 30 | 31 | #endif /* defined(__FinancialSamples__TwoDimensionalLPSolver__) */ 32 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/VectorOperations.h: -------------------------------------------------------------------------------- 1 | // 2 | // VectorOperations.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__VectorOperations__ 10 | #define __FinancialSamples__VectorOperations__ 11 | 12 | #include 13 | 14 | // performs operations on std::vector using boost ublas 15 | class VectorOperations { 16 | public: 17 | VectorOperations(const std::vector &v); 18 | VectorOperations(const VectorOperations &p); 19 | ~VectorOperations(); 20 | VectorOperations &operator=(const VectorOperations &p); 21 | std::vector scalarMult(double scalar); 22 | std::vector addVector(const std::vector &v); 23 | std::vector subtractVector(const std::vector &v); 24 | double dotProd(const std::vector &v); 25 | double norm(); 26 | private: 27 | std::vector m_data; 28 | }; 29 | 30 | #endif /* defined(__FinancialSamples__VectorOperations__) */ 31 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Recommendation.h: -------------------------------------------------------------------------------- 1 | // 2 | // Recommendation.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Recommendation__ 10 | #define __FinancialSamples__Recommendation__ 11 | 12 | #include 13 | 14 | enum RecommendationType { 15 | BUY, 16 | SELL, 17 | HOLD, 18 | NO_RECOMMENDATION 19 | }; 20 | 21 | class Recommendation { 22 | public: 23 | Recommendation(); 24 | Recommendation(const std::string &ticker, RecommendationType rec, double target); 25 | ~Recommendation(); 26 | Recommendation(const Recommendation &r); 27 | Recommendation &operator =(const Recommendation &r); 28 | 29 | double getTarget() const; 30 | RecommendationType getRecommendation() const; 31 | std::string getTicker() const; 32 | 33 | private: 34 | std::string m_ticker; 35 | RecommendationType m_recType; 36 | double m_target; 37 | }; 38 | 39 | #endif /* defined(__FinancialSamples__Recommendation__) */ 40 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FinancialStatement.h: -------------------------------------------------------------------------------- 1 | // 2 | // FinancialStatement.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__FinancialStatement__ 10 | #define __FinancialSamples__FinancialStatement__ 11 | 12 | #include 13 | #include 14 | #include 15 | 16 | class FinancialStatement { 17 | public: 18 | FinancialStatement(); 19 | ~FinancialStatement(); 20 | FinancialStatement(const FinancialStatement&); 21 | FinancialStatement &operator=(FinancialStatement &); 22 | 23 | double getReturn(); 24 | void addTransaction(const std::string &security, double val); 25 | 26 | private: 27 | double m_return; 28 | std::vector > m_transactions; 29 | }; 30 | 31 | std::auto_ptr getSampleStatement(); 32 | 33 | void transferFinancialStatement(std::auto_ptr statement); 34 | 35 | #endif /* defined(__FinancialSamples__FinancialStatement__) */ 36 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CalmarRatio.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // CalmarRatio.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #include "CalmarRatio.h" 11 | 12 | #include 13 | 14 | 15 | 16 | boost::ratio<1, 2> one_half; 17 | boost::ratio<1, 3> one_third; 18 | 19 | 20 | 21 | void createCalmarRatio() 22 | { 23 | CalmarRatio ratio(0.15, 11); 24 | } 25 | 26 | 27 | void printRatios() 28 | { 29 | std::cout << "one_third numerator: " << one_third.num 30 | << " denominator: " << one_third.den; 31 | } 32 | 33 | //void printCalmarRatios() 34 | int main_calmar() 35 | { 36 | CalmarRatio ratio(0.110, 3.12); 37 | std::cout << "return: " << ratio.getReturn() 38 | << " drawdown: " << ratio.getDrawDown() << std::endl; 39 | 40 | CalmarRatio bpsRatio(480, 2.15); 41 | std::cout << "return: " << bpsRatio.getReturn() 42 | << " drawdown: " << bpsRatio.getDrawDown() << std::endl; 43 | return 0; 44 | } 45 | 46 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CalmarRatio.h: -------------------------------------------------------------------------------- 1 | // 2 | // CalmarRatio.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #ifndef CALMARRATIO_H_ 11 | #define CALMARRATIO_H_ 12 | 13 | #include 14 | 15 | typedef boost::ratio<1, 1>::type CalmarRatioType; 16 | typedef boost::ratio<1, 100>::type CalmarRatioBPS; 17 | typedef boost::ratio<1, 1>::type CalmarRatioPerc; 18 | 19 | template 20 | class CalmarRatio { 21 | public: 22 | CalmarRatio(double calmar, double ret) : m_calmar(calmar), m_return(ret) {} 23 | virtual ~CalmarRatio() {} 24 | 25 | double getReturn() 26 | { 27 | return m_return; 28 | } 29 | 30 | double getDrawDown() 31 | { 32 | return m_return / m_calmar * m_ratio.den; 33 | } 34 | private: 35 | Ratio m_ratio; 36 | double m_calmar; 37 | double m_return; 38 | }; 39 | 40 | template <> 41 | double CalmarRatio::getDrawDown() 42 | { 43 | return m_return / m_calmar * m_ratio.den * 100; 44 | } 45 | 46 | #endif /* CALMARRATIO_H_ */ 47 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/ModifiedCAP.h: -------------------------------------------------------------------------------- 1 | // 2 | // ModifiedCAP.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__ModifiedCAP__ 10 | #define __FinancialSamples__ModifiedCAP__ 11 | 12 | #include "Matrix.h" 13 | 14 | // a modified (linearized) model for Capital Asset Pricing 15 | class ModifiedCAP { 16 | public: 17 | ModifiedCAP(int N, int T, double R, Matrix &retMatrix, const std::vector &ret); 18 | ModifiedCAP(const ModifiedCAP &p); 19 | ~ModifiedCAP(); 20 | ModifiedCAP &operator=(const ModifiedCAP &p); 21 | 22 | void solveModel(std::vector &results, double &objVal); 23 | void solveExtendedModel(std::vector &results, double &objVal); 24 | private: 25 | int m_N; // number of investment 26 | int m_T; // number of periods 27 | double m_R; // desired return 28 | Matrix m_retMatrix; 29 | std::vector m_assetRet; // single returns 30 | }; 31 | 32 | #endif /* defined(__FinancialSamples__ModifiedCAP__) */ 33 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/TimeSeriesTransformations.h: -------------------------------------------------------------------------------- 1 | // 2 | // TimeSeriesTransformations.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__TimeSeriesAnalysis__ 10 | #define __FinancialSamples__TimeSeriesAnalysis__ 11 | 12 | #include 13 | 14 | class TimeSeriesTransformations { 15 | public: 16 | TimeSeriesTransformations(); 17 | TimeSeriesTransformations(const TimeSeriesTransformations &); 18 | ~TimeSeriesTransformations(); 19 | TimeSeriesTransformations &operator=(const TimeSeriesTransformations &); 20 | void reducePrices(double val); 21 | void increasePrices(double val); 22 | void removePricesLessThan(double val); 23 | void removePricesGreaterThan(double val); 24 | double getFirstPriceLessThan(double val); 25 | void addValue(double val); 26 | void addValues(const std::vector &val); 27 | private: 28 | std::vector m_prices; 29 | }; 30 | 31 | #endif /* defined(__FinancialSamples__TimeSeriesAnalysis__) */ 32 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MatrixOperations.h: -------------------------------------------------------------------------------- 1 | // 2 | // MatrixOperations.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__MatrixOperations__ 10 | #define __FinancialSamples__MatrixOperations__ 11 | 12 | #include 13 | 14 | #include "Matrix.h" 15 | 16 | class MatrixOperations { 17 | public: 18 | MatrixOperations(); 19 | ~MatrixOperations(); 20 | MatrixOperations(const MatrixOperations &p); 21 | MatrixOperations &operator=(const MatrixOperations &p); 22 | 23 | void addRow(const std::vector &row); 24 | Matrix multiply(Matrix &m); 25 | Matrix transpose(); 26 | Matrix elementwiseMultiply(Matrix &m); 27 | Matrix scalarMultiply(double scalar); 28 | std::vector preMultiply(const std::vector &v); 29 | std::vector postMultiply(const std::vector &v); 30 | 31 | 32 | private: 33 | std::vector > m_rows; 34 | }; 35 | 36 | 37 | #endif /* defined(__FinancialSamples__MatrixOperations__) */ 38 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Matrix.h: -------------------------------------------------------------------------------- 1 | // 2 | // Matrix.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Matrix__ 10 | #define __FinancialSamples__Matrix__ 11 | 12 | #include 13 | 14 | class Matrix { 15 | public: 16 | typedef std::vector Row; 17 | 18 | Matrix(int size); 19 | Matrix(int size1, int size2); 20 | Matrix(const Matrix &s); 21 | ~Matrix(); 22 | Matrix &operator=(const Matrix &s); 23 | 24 | void transpose(); 25 | double trace(); 26 | void add(const Matrix &s); 27 | void subtract(const Matrix &s); 28 | void multiply(const Matrix &s); 29 | 30 | Row & operator[](int pos); 31 | int numRows() const; 32 | private: 33 | std::vector m_rows; 34 | }; 35 | 36 | // free operators 37 | // 38 | Matrix operator+(const Matrix &s1, const Matrix &s2); 39 | Matrix operator-(const Matrix &s1, const Matrix &s2); 40 | Matrix operator*(const Matrix &s1, const Matrix &s2); 41 | 42 | #endif /* defined(__FinancialSamples__Matrix__) */ 43 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RecommendationsProcessor.h: -------------------------------------------------------------------------------- 1 | // 2 | // RecommendationsProcessor.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__RecommendationsProcessor__ 10 | #define __FinancialSamples__RecommendationsProcessor__ 11 | 12 | 13 | #include 14 | #include 15 | 16 | #include "Recommendation.h" 17 | 18 | 19 | class RecommendationsProcessor { 20 | public: 21 | RecommendationsProcessor(); 22 | ~RecommendationsProcessor(); 23 | RecommendationsProcessor(const RecommendationsProcessor &); 24 | RecommendationsProcessor &operator =(const RecommendationsProcessor &); 25 | 26 | void addRecommendation(const std::string &ticker, RecommendationType rec, double targetPrice); 27 | double averageTargetPrice(const std::string &ticker); 28 | RecommendationType averageRecommendation(const std::string &ticker); 29 | private: 30 | std::map > m_recommendations; 31 | }; 32 | 33 | 34 | 35 | #endif /* defined(__FinancialSamples__RecommendationsProcessor__) */ 36 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/GnuplotPlotter.h: -------------------------------------------------------------------------------- 1 | // 2 | // GnuplotPlotter.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__GnuplotPlotter__ 10 | #define __FinancialSamples__GnuplotPlotter__ 11 | 12 | #include 13 | #include 14 | 15 | class GnuplotPlotter { 16 | public: 17 | GnuplotPlotter(const std::string &fileName); 18 | GnuplotPlotter(const GnuplotPlotter &p); 19 | ~GnuplotPlotter(); 20 | GnuplotPlotter &operator=(const GnuplotPlotter &p); 21 | void generateCmds(const std::string &cmdFileName); 22 | void setHeaders(const std::string &xheader, const std::string &yheader); 23 | void setData(const std::vector &xdata, const std::vector &ydata); 24 | void setData(const std::vector &xdata, const std::vector &ydata); 25 | void csvWrite(); 26 | private: 27 | std::string m_fileName; 28 | std::string m_xheader; 29 | std::string m_yheader; 30 | std::vector m_xdata; 31 | std::vector m_ydata; 32 | bool m_isDate; 33 | }; 34 | 35 | #endif /* defined(__FinancialSamples__GnuplotPlotter__) */ 36 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CompoundIntRateCalculator.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // CompoundIntRateCalculator.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "CompoundIntRateCalculator.h" 10 | 11 | #include 12 | 13 | CompoundIntRateCalculator::CompoundIntRateCalculator(double rate) 14 | : m_rate(rate) 15 | { 16 | 17 | } 18 | 19 | CompoundIntRateCalculator::~CompoundIntRateCalculator() 20 | { 21 | 22 | } 23 | 24 | CompoundIntRateCalculator::CompoundIntRateCalculator(const CompoundIntRateCalculator &v) 25 | : m_rate(v.m_rate) 26 | { 27 | 28 | } 29 | 30 | CompoundIntRateCalculator &CompoundIntRateCalculator::operator =(const CompoundIntRateCalculator &v) 31 | { 32 | if (this != &v) 33 | { 34 | this->m_rate = v.m_rate; 35 | } 36 | return *this; 37 | } 38 | 39 | double CompoundIntRateCalculator::multiplePeriod(double value, int numPeriods) 40 | { 41 | double f = value * pow(1 + m_rate, numPeriods); 42 | return f; 43 | } 44 | 45 | double CompoundIntRateCalculator::continuousCompounding(double value, int numPeriods) 46 | { 47 | double f = value * exp(m_rate * numPeriods); 48 | return f; 49 | } 50 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/OptionsProbabilities.h: -------------------------------------------------------------------------------- 1 | // 2 | // OptionsProbabilities.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__OptionsProbabilities__ 10 | #define __FinancialSamples__OptionsProbabilities__ 11 | 12 | #include 13 | 14 | class OptionsProbabilities { 15 | public: 16 | OptionsProbabilities(double initialPrice, double strike, double avgStep, int nDays); 17 | OptionsProbabilities(const OptionsProbabilities &p); 18 | ~OptionsProbabilities(); 19 | OptionsProbabilities &operator=(const OptionsProbabilities &p); 20 | 21 | void setNumIterations(int n); 22 | 23 | double probFinishAboveStrike(); 24 | double probFinishBelowStrike(); 25 | double probFinalPriceBetweenPrices(double lowPrice, double highPrice); 26 | std::vector getWalk(); 27 | private: 28 | double m_initialPrice; 29 | double m_strike; 30 | double m_avgStep; 31 | int m_numDays; 32 | int m_numIterations; 33 | 34 | double gaussianValue(double mean, double sigma); 35 | double getLastPriceOfWalk(); 36 | }; 37 | 38 | #endif /* defined(__FinancialSamples__OptionsProbabilities__) */ 39 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/LuaMain.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // LuaMain.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "LuaMain.h" 10 | 11 | #include 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #include "LuaWrap.h" 19 | #include "LuaOption.h" 20 | 21 | using std::cout; 22 | using std::cerr; 23 | using std::endl; 24 | 25 | 26 | int main_lua() { 27 | char buff[256]; 28 | 29 | lua_State *L = luaL_newstate(); 30 | int error; 31 | 32 | // load some of the (C) libraries included with Lua 33 | luaopen_base(L); 34 | luaopen_table(L); 35 | luaopen_io(L); 36 | luaopen_string(L); 37 | luaopen_math(L); 38 | 39 | // load LuaOption object 40 | LuaWrapper::Register(L); 41 | 42 | while (fgets(buff, sizeof(buff), stdin) != NULL) { 43 | error = luaL_loadbuffer(L, buff, strlen(buff), "line") || 44 | lua_pcall(L, 0, 0, 0); 45 | if (error) { 46 | cerr << lua_tostring(L, -1) << endl; 47 | lua_pop(L, 1); // remove error from Lua stack 48 | } 49 | } 50 | 51 | lua_close(L); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/BondCalculator.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // BondCalculator.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "BondCalculator.h" 10 | 11 | BondCalculator::BondCalculator(const std::string institution, 12 | int numPeriods, double principal, double couponValue) 13 | : m_institution(institution), 14 | m_principal(principal), 15 | m_coupon(couponValue), 16 | m_numPeriods(numPeriods) 17 | { 18 | 19 | } 20 | 21 | BondCalculator::BondCalculator(const BondCalculator &v) 22 | : m_institution(v.m_institution), 23 | m_principal(v.m_principal), 24 | m_coupon(v.m_coupon), 25 | m_numPeriods(v.m_numPeriods) 26 | { 27 | 28 | } 29 | 30 | BondCalculator::~BondCalculator() 31 | { 32 | 33 | } 34 | 35 | BondCalculator &BondCalculator::operator =(const BondCalculator &v) 36 | { 37 | if (this != &v) 38 | { 39 | this->m_institution = v.m_institution; 40 | this->m_principal = v.m_principal; 41 | this->m_numPeriods = v.m_numPeriods; 42 | this->m_coupon = v.m_coupon; 43 | } 44 | return *this; 45 | } 46 | 47 | double BondCalculator::interestRate() 48 | { 49 | return m_coupon / m_principal; 50 | } 51 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/TransactionHandler.h: -------------------------------------------------------------------------------- 1 | // 2 | // TransactionHandler.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__TransactionHandler__ 10 | #define __FinancialSamples__TransactionHandler__ 11 | 12 | #include 13 | #include 14 | 15 | enum TransactionType { 16 | TRANSACTION_SELL, 17 | TRANSACTION_BUY, 18 | TRANSACTION_SHORT, 19 | }; 20 | 21 | class FileError :public std::runtime_error { 22 | public: 23 | FileError(const std::string &s); 24 | }; 25 | 26 | class TransactionTypeError :public std::runtime_error { 27 | public: 28 | TransactionTypeError(const std::string &s); 29 | }; 30 | 31 | class TransactionHandler { 32 | public: 33 | static const std::string SELL_OP; 34 | static const std::string BUY_OP; 35 | static const std::string SHORT_OP; 36 | 37 | TransactionHandler(const std::string &fileName); 38 | TransactionHandler(const TransactionHandler &); 39 | ~TransactionHandler(); 40 | TransactionHandler &operator=(const TransactionHandler&); 41 | 42 | void handleTransactions(); 43 | private: 44 | std::string m_fileName; 45 | }; 46 | 47 | #endif /* defined(__FinancialSamples__TransactionHandler__) */ 48 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Stock.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Stock.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "Stock.h" 10 | 11 | Stock::Stock(const std::string &ticker, double price, double div) 12 | : m_ticker(ticker), 13 | m_currentPrice(price), 14 | m_dividend(div) 15 | { 16 | } 17 | 18 | Stock::Stock(const Stock &p) 19 | : m_ticker(p.m_ticker), 20 | m_currentPrice(p.m_currentPrice), 21 | m_dividend(p.m_dividend) 22 | { 23 | } 24 | 25 | Stock::~Stock() 26 | { 27 | } 28 | 29 | Stock &Stock::operator=(const Stock &p) 30 | { 31 | if (this != &p) 32 | { 33 | m_ticker = p.m_ticker; 34 | m_currentPrice = p.m_currentPrice; 35 | m_dividend = p.m_dividend; 36 | } 37 | return *this; 38 | } 39 | 40 | double Stock::price() 41 | { 42 | return m_currentPrice; 43 | } 44 | 45 | void Stock::setPrice(double price) 46 | { 47 | m_currentPrice = price; 48 | } 49 | 50 | double Stock::dividend() 51 | { 52 | return m_dividend; 53 | } 54 | 55 | void Stock::setDividend(double div) 56 | { 57 | m_dividend = div; 58 | } 59 | 60 | double Stock::dividendYield() 61 | { 62 | return m_dividend / m_currentPrice; 63 | } 64 | 65 | std::string Stock::ticker() 66 | { 67 | return m_ticker; 68 | } 69 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Recommendation.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Recommendation.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "Recommendation.h" 10 | 11 | 12 | 13 | Recommendation::Recommendation() 14 | : m_recType(HOLD), 15 | m_target(0) 16 | { 17 | 18 | } 19 | 20 | Recommendation::Recommendation(const std::string &ticker, RecommendationType rec, double target) 21 | : m_ticker(ticker), 22 | m_recType(rec), 23 | m_target(target) 24 | { 25 | 26 | } 27 | 28 | Recommendation::~Recommendation() 29 | { 30 | 31 | } 32 | 33 | Recommendation::Recommendation(const Recommendation &r) 34 | : m_ticker(r.m_ticker), 35 | m_recType(r.m_recType), 36 | m_target(r.m_target) 37 | { 38 | 39 | } 40 | 41 | Recommendation &Recommendation::operator =(const Recommendation &r) 42 | { 43 | if (this != &r) 44 | { 45 | m_ticker = r.m_ticker; 46 | m_recType = r.m_recType; 47 | m_target = r.m_target; 48 | } 49 | return *this; 50 | } 51 | 52 | double Recommendation::getTarget() const 53 | { 54 | return m_target; 55 | } 56 | 57 | RecommendationType Recommendation::getRecommendation() const 58 | { 59 | return m_recType; 60 | } 61 | 62 | std::string Recommendation::getTicker() const 63 | { 64 | return m_ticker; 65 | } 66 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/LPSolver.h: -------------------------------------------------------------------------------- 1 | // 2 | // LPSolver.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__Glpk__ 10 | #define __FinancialSamples__Glpk__ 11 | 12 | #include 13 | #include 14 | 15 | #include "Matrix.h" 16 | 17 | struct glp_prob; 18 | 19 | class LPSolver { 20 | public: 21 | LPSolver(Matrix &A, const std::vector &b, const std::vector &c); 22 | LPSolver(const LPSolver &p); 23 | ~LPSolver(); 24 | LPSolver &operator=(const LPSolver &p); 25 | 26 | enum ResultType { 27 | INFEASIBLE, 28 | FEASIBLE, 29 | ERROR 30 | }; 31 | 32 | virtual ResultType solve(std::vector &result, double &objValue); 33 | void setName(const std::string &s); 34 | bool isValid(); 35 | void setMaximization(); 36 | void setMinimization(); 37 | private: 38 | size_t m_M; 39 | size_t m_N; 40 | std::vector m_c; 41 | std::vector m_b; 42 | Matrix m_A; 43 | glp_prob *m_lp; 44 | 45 | void initProblem(size_t M, size_t N); 46 | void setRowBounds(); 47 | void setColumnCoefs(); 48 | protected: 49 | glp_prob *getLP(); 50 | int getNumCols(); 51 | int getNumRows(); 52 | }; 53 | 54 | 55 | #endif /* defined(__FinancialSamples__Glpk__) */ 56 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/InvestmentInstrument.h: -------------------------------------------------------------------------------- 1 | // 2 | // InvestmentInstrument.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__InvestmentInstrument__ 10 | #define __FinancialSamples__InvestmentInstrument__ 11 | 12 | #include 13 | 14 | class BondInstrument { 15 | public: 16 | BondInstrument() {} 17 | BondInstrument(double principal, double monthlyPayment); 18 | ~BondInstrument(); 19 | BondInstrument(const BondInstrument &a); 20 | BondInstrument &operator =(const BondInstrument &a); 21 | 22 | double getMonthlyPayment(); 23 | double getPrincipal(); 24 | 25 | // other methods here... 26 | private: 27 | double 28 | m_monthlyPay, 29 | m_principal; 30 | }; 31 | 32 | class MortgageInstrument { 33 | public: 34 | MortgageInstrument() {} 35 | MortgageInstrument(double monthlyPay, double propertyValue, double downpayment); 36 | ~MortgageInstrument(); 37 | MortgageInstrument(const MortgageInstrument &a); 38 | MortgageInstrument &operator =(const MortgageInstrument &a); 39 | 40 | double getMonthlyPayment(); 41 | double getPrincipal(); 42 | 43 | // other methods here... 44 | private: 45 | double 46 | m_monthlyPay, 47 | m_propertyValue, 48 | m_downPayment; 49 | }; 50 | 51 | #endif /* defined(__FinancialSamples__InvestmentInstrument__) */ 52 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/CorrelationCalculator.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // CorrelationCalculator.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "CorrelationCalculator.h" 10 | 11 | #include "TimeSeries.h" 12 | #include 13 | 14 | CorrelationCalculator::CorrelationCalculator(TimeSeries &a, TimeSeries &b) 15 | : m_tsA(a), 16 | m_tsB(b) 17 | { 18 | } 19 | 20 | CorrelationCalculator::~CorrelationCalculator() 21 | { 22 | 23 | } 24 | 25 | CorrelationCalculator::CorrelationCalculator(const CorrelationCalculator &c) 26 | : m_tsA(c.m_tsA), 27 | m_tsB(c.m_tsB) 28 | { 29 | 30 | } 31 | 32 | CorrelationCalculator &CorrelationCalculator::operator=(const CorrelationCalculator &c) 33 | { 34 | if (this != &c) 35 | { 36 | m_tsA = c.m_tsA; 37 | m_tsB = c.m_tsB; 38 | } 39 | return *this; 40 | } 41 | 42 | double CorrelationCalculator::correlation() 43 | { 44 | double sum = 0; 45 | double meanA = m_tsA.mean(); 46 | double meanB = m_tsB.mean(); 47 | 48 | if (m_tsA.size() != m_tsB.size()) { 49 | std::cout << "error: number of observations is different" << std::endl; 50 | return -1; 51 | } 52 | 53 | for (int i=0; i 12 | #include 13 | 14 | CashFlowCalculator::CashFlowCalculator(double rate) 15 | : m_rate(rate) 16 | { 17 | 18 | } 19 | 20 | CashFlowCalculator::CashFlowCalculator(const CashFlowCalculator &v) 21 | : m_rate(v.m_rate) 22 | { 23 | 24 | } 25 | 26 | CashFlowCalculator::~CashFlowCalculator() 27 | { 28 | 29 | } 30 | 31 | CashFlowCalculator &CashFlowCalculator::operator =(const CashFlowCalculator &v) 32 | { 33 | if (this != &v) 34 | { 35 | this->m_cashPayments = v.m_cashPayments; 36 | this->m_timePeriods = v.m_timePeriods; 37 | this->m_rate = v.m_rate; 38 | } 39 | return *this; 40 | } 41 | 42 | 43 | void CashFlowCalculator::addCashPayment(double value, int timePeriod) 44 | { 45 | m_cashPayments.push_back(value); 46 | m_timePeriods.push_back(timePeriod); 47 | } 48 | 49 | double CashFlowCalculator::presentValue(double futureValue, int timePeriod) 50 | { 51 | double pValue = futureValue / pow(1+m_rate, timePeriod); 52 | std::cout << " value " << pValue << std::endl; 53 | return pValue; 54 | } 55 | 56 | double CashFlowCalculator::presentValue() 57 | { 58 | double total = 0; 59 | for (unsigned i=0; i 13 | 14 | #include 15 | 16 | const char LuaOption::className[] = "Option"; 17 | 18 | LuaOption::LuaOption(lua_State *L) 19 | { 20 | printf(" called constructor ");fflush(stdout); 21 | // m_option = (Option*)lua_touserdata(L, 1); 22 | m_option = new Option("", 10); 23 | printf(" called constructor 2 %p", m_option);fflush(stdout); 24 | } 25 | 26 | void LuaOption::setObject(lua_State *L) 27 | { 28 | m_option = (Option*)lua_touserdata(L, 1); 29 | } 30 | 31 | int LuaOption::ticker(lua_State *L) 32 | { 33 | lua_pushstring(L, m_option->ticker().c_str()); 34 | return 1; 35 | } 36 | 37 | int LuaOption::strike(lua_State *L) 38 | { 39 | lua_pushnumber(L, m_option->strike()); 40 | return 1; 41 | } 42 | 43 | int LuaOption::setTicker(lua_State *L) 44 | { 45 | printf("on set ticker"); 46 | m_option->setTicker((const char*)luaL_checkstring(L, 1)); 47 | return 0; 48 | } 49 | 50 | int LuaOption::setStrike(lua_State *L) 51 | { 52 | m_option->setStrike((double)luaL_checknumber(L, 1)); 53 | return 0; 54 | } 55 | 56 | #define method(class, name) {#name, &class::name} 57 | LuaWrapper::RegType LuaOption::methods[] = { 58 | method(LuaOption, ticker), 59 | method(LuaOption, strike), 60 | method(LuaOption, setTicker), 61 | method(LuaOption, setStrike), 62 | {0,0} 63 | }; 64 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RandonWalk.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // RandonWalk.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "RandonWalk.h" 10 | 11 | #include 12 | #include 13 | 14 | using std::vector; 15 | using std::cout; 16 | using std::endl; 17 | 18 | RandomWalk::RandomWalk(int size, double start, double step) 19 | : m_size(size), 20 | m_step(step), 21 | m_start(start) 22 | { 23 | } 24 | 25 | RandomWalk::RandomWalk(const RandomWalk &p) 26 | : m_size(p.m_size), 27 | m_step(p.m_step), 28 | m_start(p.m_start) 29 | { 30 | } 31 | 32 | RandomWalk::~RandomWalk() 33 | { 34 | } 35 | 36 | RandomWalk &RandomWalk::operator=(const RandomWalk &p) 37 | { 38 | if (this != &p) 39 | { 40 | m_size = p.m_size; 41 | m_step = p.m_step; 42 | m_start = p.m_start; 43 | } 44 | return *this; 45 | } 46 | 47 | std::vector RandomWalk::getWalk() 48 | { 49 | vector walk; 50 | double prev = m_start; 51 | 52 | for (int i=0; i walk = rw.getWalk(); 68 | for (int i=0; i 13 | 14 | template 15 | class IntRateEngine { 16 | public: 17 | IntRateEngine(); 18 | ~IntRateEngine(); 19 | IntRateEngine(const IntRateEngine &a); 20 | IntRateEngine &operator =(const IntRateEngine &a); 21 | 22 | void setInstrument(T &inv); 23 | double getAnnualIntRate(); 24 | private: 25 | T m_instrument; 26 | }; 27 | 28 | template 29 | IntRateEngine::IntRateEngine() 30 | { 31 | 32 | } 33 | 34 | template 35 | IntRateEngine::~IntRateEngine() 36 | { 37 | 38 | } 39 | 40 | template 41 | IntRateEngine::IntRateEngine(const IntRateEngine &a) 42 | : m_instrument(a.m_instrument) 43 | { 44 | 45 | } 46 | 47 | template 48 | IntRateEngine &IntRateEngine::operator =(const IntRateEngine &a) 49 | { 50 | if (this != &a) 51 | { 52 | m_instrument = a.m_instrument; 53 | } 54 | return *this; 55 | } 56 | 57 | template 58 | void IntRateEngine::setInstrument(T &inv) 59 | { 60 | m_instrument = inv; 61 | } 62 | 63 | template 64 | double IntRateEngine::getAnnualIntRate() 65 | { 66 | double payment = m_instrument.getMonthlyPayment(); 67 | double principal = m_instrument.getPrincipal(); 68 | return (12 *payment) / principal; 69 | } 70 | 71 | 72 | #endif /* defined(__FinancialSamples__IntRateEngine__) */ 73 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FinancialStatement.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // FinancialStatement.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "FinancialStatement.h" 10 | 11 | #include 12 | 13 | FinancialStatement::FinancialStatement() 14 | : m_return(0) 15 | { 16 | 17 | } 18 | 19 | FinancialStatement::~FinancialStatement() 20 | { 21 | 22 | } 23 | 24 | FinancialStatement::FinancialStatement(const FinancialStatement &v) 25 | : m_return(v.m_return), 26 | m_transactions(v.m_transactions) 27 | { 28 | 29 | } 30 | 31 | FinancialStatement &FinancialStatement::operator=(FinancialStatement &v) 32 | { 33 | if (this != &v) 34 | { 35 | m_return = v.m_return; 36 | m_transactions = v.m_transactions; 37 | } 38 | return *this; 39 | } 40 | 41 | double FinancialStatement::getReturn() 42 | { 43 | return m_return; 44 | } 45 | 46 | void FinancialStatement::addTransaction(const std::string &security, double val) 47 | { 48 | m_transactions.push_back(std::make_pair(security, val)); 49 | } 50 | 51 | // returns a sample statement that includes a few common stocks 52 | std::auto_ptr getSampleStatement() 53 | { 54 | std::auto_ptr fs(new FinancialStatement); 55 | fs->addTransaction("IBM", 102.2); 56 | fs->addTransaction("AAPL", 523.0); 57 | return fs; 58 | } 59 | 60 | void transferFinancialStatement(std::auto_ptr statement) 61 | { 62 | // perform transfer here 63 | // ... 64 | // statement is still valid 65 | std::cout << statement->getReturn() << std::endl; 66 | // statement is released here 67 | } 68 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FundamentalsCalc.h: -------------------------------------------------------------------------------- 1 | // 2 | // FundamentalsCalc.h 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #ifndef __FinancialSamples__FundamentalsCalc__ 10 | #define __FinancialSamples__FundamentalsCalc__ 11 | 12 | #include 13 | 14 | class FundamentalsCalculator { 15 | public: 16 | FundamentalsCalculator(const std::string &ticker, double price, double dividend); 17 | ~FundamentalsCalculator(); 18 | FundamentalsCalculator(const FundamentalsCalculator &); 19 | FundamentalsCalculator &operator=(const FundamentalsCalculator&); 20 | 21 | void setNumOfShares(int n); 22 | void setEarnings(double val); 23 | void setExpectedEarnings(double val); 24 | void setBookValue(double val); 25 | void setAssets(double val); 26 | void setLiabilitiesAndIntangibles(double val); 27 | void setEpsGrowth(double val); 28 | void setNetIncome(double val); 29 | void setShareHoldersEquity(double val); 30 | 31 | double PE(); 32 | double forwardPE(); 33 | double bookValue(); 34 | double priceToBookRatio(); 35 | double priceEarningsToGrowth(); 36 | double returnOnEquity(); 37 | double getDividend(); 38 | 39 | private: 40 | 41 | std::string m_ticker; 42 | double m_price; 43 | double m_dividend; 44 | double m_earningsEstimate; 45 | int m_numShares; 46 | double m_earnings; 47 | double m_bookValue; 48 | double m_assets; 49 | double m_liabilitiesAndIntangibles; 50 | double m_epsGrowth; 51 | double m_netIncome; 52 | double m_shareholdersEquity; 53 | }; 54 | 55 | #endif /* defined(__FinancialSamples__FundamentalsCalc__) */ 56 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/TimeSeries.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // TimeSeries.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "TimeSeries.h" 10 | #include 11 | #include 12 | 13 | TimeSeries::TimeSeries() 14 | : m_values() 15 | { 16 | 17 | } 18 | 19 | TimeSeries::~TimeSeries() 20 | { 21 | 22 | } 23 | 24 | TimeSeries::TimeSeries(const TimeSeries &ts) 25 | : m_values(ts.m_values) 26 | { 27 | } 28 | 29 | TimeSeries &TimeSeries::operator =(const TimeSeries &ts) 30 | { 31 | if (this != &ts) 32 | { 33 | m_values = ts.m_values; 34 | } 35 | return *this; 36 | } 37 | 38 | void TimeSeries::addValue(double val) 39 | { 40 | m_values.push_back(val); 41 | } 42 | 43 | double TimeSeries::mean() 44 | { 45 | double sum = 0; 46 | for (int i=0; i 12 | 13 | RiskCalculator::RiskCalculator() 14 | { 15 | 16 | } 17 | 18 | RiskCalculator::~RiskCalculator() 19 | { 20 | 21 | } 22 | 23 | RiskCalculator::RiskCalculator(const RiskCalculator &v) 24 | : m_creditRisks(v.m_creditRisks) 25 | { 26 | 27 | } 28 | 29 | RiskCalculator &RiskCalculator::operator =(const RiskCalculator &v) 30 | { 31 | if (this != &v) 32 | { 33 | m_creditRisks = v.m_creditRisks; 34 | } 35 | return *this; 36 | } 37 | 38 | void RiskCalculator::addCreditRisk(std::shared_ptr risk) 39 | { 40 | m_creditRisks.push_back(risk); 41 | } 42 | 43 | CreditRisk::RiskType RiskCalculator::portfolioMaxRisk() 44 | { 45 | auto risk = CreditRisk::RiskType::AAA; 46 | for (std::vector >::iterator p = m_creditRisks.begin(); 47 | p != m_creditRisks.end(); ++p) 48 | { 49 | 50 | } 51 | for (auto p = m_creditRisks.begin(); p != m_creditRisks.end(); ++p) 52 | { 53 | if ((*p)->getRating() < risk) 54 | { 55 | risk = (*p)->getRating(); 56 | } 57 | } 58 | return risk; 59 | } 60 | 61 | CreditRisk::RiskType RiskCalculator::portfolioMinRisk() 62 | { 63 | CreditRisk::RiskType risk = CreditRisk::RiskType::C; 64 | for (unsigned i=0; igetRating() > risk) 67 | { 68 | risk = m_creditRisks[i]->getRating(); 69 | } 70 | } 71 | return risk; 72 | } 73 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Matrix_Py.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Matrix_Py.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "Matrix_Py.h" 10 | 11 | #if 0 12 | // include this header file for access to boost::python templates and macros 13 | #include 14 | 15 | // add the using clause to reduce namespace clutter 16 | using namespace boost::python; 17 | 18 | 19 | MatrixP::MatrixP(int a) 20 | : Matrix(a) 21 | { 22 | 23 | } 24 | 25 | MatrixP::MatrixP(int a, int b) 26 | : Matrix(a, b) 27 | { 28 | 29 | } 30 | 31 | MatrixP::MatrixP(const MatrixP &p) 32 | : Matrix(p) 33 | { 34 | 35 | } 36 | 37 | MatrixP::~MatrixP() 38 | { 39 | } 40 | 41 | void MatrixP::set(int a, int b, double v) 42 | { 43 | (*this)[a][b] = v; 44 | } 45 | 46 | double MatrixP::get(int a, int b) 47 | { 48 | return (*this)[a][b]; 49 | } 50 | 51 | 52 | // this macro generates all the boilerplate required by the Python API 53 | BOOST_PYTHON_MODULE(matrix) 54 | { 55 | 56 | // defines a new class to be exported 57 | class_("Matrix", 58 | init()) // the init form defines a constructor 59 | 60 | // another constructor with two int parameters 61 | .def(init()) 62 | 63 | // here are some standard functions (name first, member function second) 64 | .def("add", &MatrixP::add) 65 | .def("subtract", &MatrixP::subtract) 66 | .def("multiply", &MatrixP::multiply) 67 | .def("numRows", &MatrixP::numRows) 68 | .def("trace", &MatrixP::trace) 69 | .def("transpose", &MatrixP::transpose) 70 | .def("set", &MatrixP::set) 71 | .def("get", &MatrixP::get) 72 | ; 73 | } 74 | 75 | #endif -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/TransactionHandler.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // TransactionHandler.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "TransactionHandler.h" 10 | 11 | #include 12 | 13 | FileError::FileError(const std::string &s) 14 | : std::runtime_error(s) 15 | { 16 | } 17 | 18 | 19 | TransactionTypeError::TransactionTypeError(const std::string &s) 20 | : std::runtime_error(s) 21 | { 22 | 23 | } 24 | 25 | const std::string TransactionHandler::SELL_OP = "SELL"; 26 | const std::string TransactionHandler::BUY_OP = "BUY"; 27 | const std::string TransactionHandler::SHORT_OP = "SHORT"; 28 | 29 | TransactionHandler::TransactionHandler(const std::string &fileName) 30 | : m_fileName(fileName) 31 | { 32 | 33 | } 34 | 35 | TransactionHandler::TransactionHandler(const TransactionHandler &a) 36 | : m_fileName(a.m_fileName) 37 | { 38 | 39 | } 40 | 41 | TransactionHandler::~TransactionHandler() 42 | { 43 | } 44 | 45 | TransactionHandler &TransactionHandler::operator=(const TransactionHandler&a) 46 | { 47 | if (this != &a) 48 | { 49 | m_fileName = a.m_fileName; 50 | } 51 | return *this; 52 | } 53 | 54 | void TransactionHandler::handleTransactions() 55 | { 56 | std::ifstream file; 57 | file.open(m_fileName, std::ifstream::in); 58 | if (file.fail()) 59 | { 60 | throw new FileError(std::string("error opening file ") + m_fileName); 61 | } 62 | 63 | std::string op; 64 | file >> op; 65 | while (file.good() && !file.eof()) 66 | { 67 | if (op != SELL_OP && op != BUY_OP && op != SHORT_OP) 68 | { 69 | throw new TransactionTypeError(std::string("unknown transaction ") + op); 70 | } 71 | 72 | // process remaining transaction data... 73 | } 74 | } 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/EulersMethod.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // EulersMethod.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "EulersMethod.h" 10 | 11 | #include "MathFunction.h" 12 | 13 | #include 14 | 15 | using std::cout; 16 | using std::endl; 17 | 18 | 19 | EulersMethod::EulersMethod(MathFunction &f) 20 | : m_f(f) 21 | { 22 | } 23 | 24 | EulersMethod::EulersMethod(const EulersMethod &p) 25 | : m_f(p.m_f) 26 | { 27 | } 28 | 29 | EulersMethod::~EulersMethod() 30 | { 31 | } 32 | 33 | EulersMethod &EulersMethod::operator=(const EulersMethod &p) 34 | { 35 | if (this != &p) 36 | { 37 | m_f = p.m_f; 38 | } 39 | return *this; 40 | } 41 | 42 | double EulersMethod::solve(int n, double x0, double y0, double c) 43 | { 44 | // problem : y' = f(x,y) ; y(x0) = y0 45 | 46 | auto x = x0; 47 | auto y = y0; 48 | auto h = (c - x0)/n; 49 | 50 | cout << " h is " << h << endl; 51 | 52 | for (int i=0; i { 73 | public: 74 | double operator()(double x) { return x; } // not used 75 | double operator()(double x, double y); 76 | }; 77 | 78 | double EulerMethSampleFunc::operator()(double x, double y) 79 | { 80 | return 3 * x + 2 * y + 1; 81 | } 82 | 83 | int main_euler() 84 | { 85 | EulerMethSampleFunc f; 86 | EulersMethod m(f); 87 | double res = m.solve (100, 0, 0.25, 2); 88 | cout << " result is " << res << endl; 89 | return 0; 90 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RungeKuttaODEMethod.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // RungeKuttaODEMethod.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "RungeKuttaODEMethod.h" 10 | 11 | #include "MathFunction.h" 12 | 13 | #include 14 | 15 | using std::cout; 16 | using std::endl; 17 | 18 | RungeKuttaODEMethod::RungeKuttaODEMethod(MathFunction &f) 19 | : m_f(f) 20 | { 21 | } 22 | 23 | RungeKuttaODEMethod::RungeKuttaODEMethod(const RungeKuttaODEMethod &p) 24 | : m_f(p.m_f) 25 | { 26 | } 27 | 28 | RungeKuttaODEMethod::~RungeKuttaODEMethod() 29 | { 30 | } 31 | 32 | RungeKuttaODEMethod &RungeKuttaODEMethod::operator=(const RungeKuttaODEMethod &p) 33 | { 34 | if (this != &p) 35 | { 36 | m_f = p.m_f; 37 | } 38 | return *this; 39 | } 40 | 41 | double RungeKuttaODEMethod::solve(int n, double x0, double y0, double c) 42 | { 43 | auto x = x0; 44 | auto y = y0; 45 | auto h = (c - x0)/n; 46 | 47 | for (int i=0; i { 64 | public: 65 | double operator()(double x) { return x; } // not used 66 | double operator()(double x, double y); 67 | }; 68 | 69 | double RKMethSampleFunc::operator()(double x, double y) 70 | { 71 | return 3 * x + 2 * y + 1; 72 | } 73 | 74 | int main_rkm() 75 | { 76 | RKMethSampleFunc f; 77 | RungeKuttaODEMethod m(f); 78 | double res = m.solve (100, 0, 0.25, 2); 79 | cout << " result is " << res << endl; 80 | return 0; 81 | } 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RExtension.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // RExtension.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #include "RExtension.h" 11 | 12 | 13 | #include 14 | #include 15 | 16 | using std::cout; 17 | using std::endl; 18 | 19 | extern "C" { 20 | void presentValue(int *, double *, int *, double *, double *); 21 | } 22 | 23 | 24 | void presentValue(int *numPayments, double *intRate, 25 | int *timePeriods, double *payments, double *result) 26 | { 27 | int n = *numPayments; 28 | RExtension re(*intRate); 29 | for (int i=0; im_cashPayments = v.m_cashPayments; 59 | this->m_timePeriods = v.m_timePeriods; 60 | this->m_rate = v.m_rate; 61 | } 62 | return *this; 63 | } 64 | 65 | 66 | void RExtension::addCashPayment(double value, int timePeriod) 67 | { 68 | m_cashPayments.push_back(value); 69 | m_timePeriods.push_back(timePeriod); 70 | } 71 | 72 | double RExtension::presentValue(double futureValue, int timePeriod) 73 | { 74 | double pValue = futureValue / pow(1+m_rate, timePeriod); 75 | cout << " value " << pValue << endl; 76 | return pValue; 77 | } 78 | 79 | double RExtension::presentValue() 80 | { 81 | double total = 0; 82 | for (unsigned i=0; i 14 | #include 15 | 16 | using std::vector; 17 | using std::cout; 18 | using std::endl; 19 | 20 | MIPSolver::MIPSolver(Matrix &A, const std::vector &b, const std::vector &c) 21 | : LPSolver(A, b, c) 22 | { 23 | } 24 | 25 | MIPSolver::MIPSolver(const MIPSolver &p) 26 | : LPSolver(p) 27 | { 28 | } 29 | 30 | MIPSolver::~MIPSolver() 31 | { 32 | } 33 | 34 | MIPSolver &MIPSolver::operator=(const MIPSolver &p) 35 | { 36 | return *this; 37 | } 38 | 39 | void MIPSolver::setColInteger(int colNum) 40 | { 41 | glp_set_col_kind(getLP(), colNum+1, GLP_IV); 42 | } 43 | 44 | void MIPSolver::setColBinary(int colNum) 45 | { 46 | glp_set_col_kind(getLP(), colNum+1, GLP_BV); 47 | } 48 | 49 | LPSolver::ResultType MIPSolver::solve(vector &result, double &objValue) 50 | { 51 | glp_simplex(getLP(), NULL); 52 | int res = glp_intopt(getLP(), NULL); 53 | if (res != 0) 54 | { 55 | cout << "res = " << res << " \n"; 56 | } 57 | 58 | result.resize(getNumCols(), 0); 59 | objValue = glp_mip_obj_val(getLP()); 60 | 61 | for (int i=0; i b = { 2, 3 }; 72 | vector c = { 1, 1 }; 73 | A[0][0] = 1; 74 | A[0][1] = 2; 75 | A[1][0] = 3; 76 | A[1][1] = 4; 77 | MIPSolver solver(A, b, c); 78 | 79 | solver.setMaximization(); 80 | solver.setColInteger(0); 81 | 82 | vector result; 83 | double objVal; 84 | solver.solve(result, objVal); 85 | cout << "optimum: " << objVal << endl; 86 | cout << " x0: " << result[0] << " x1: " << result[1] << endl; 87 | return 0; 88 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/InvestmentInstrument.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // InvestmentInstrument.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "InvestmentInstrument.h" 10 | 11 | 12 | BondInstrument::BondInstrument(double principal, double monthlyPayment) 13 | : m_principal(principal), 14 | m_monthlyPay(monthlyPayment) 15 | { 16 | 17 | } 18 | 19 | BondInstrument::~BondInstrument() 20 | { 21 | 22 | } 23 | 24 | BondInstrument::BondInstrument(const BondInstrument &a) 25 | : m_monthlyPay(a.m_monthlyPay), 26 | m_principal(a.m_principal) 27 | { 28 | 29 | } 30 | 31 | BondInstrument &BondInstrument::operator =(const BondInstrument &a) 32 | { 33 | if (this != &a) 34 | { 35 | m_principal = a.m_principal; 36 | m_monthlyPay = a.m_monthlyPay; 37 | } 38 | return *this; 39 | } 40 | 41 | double BondInstrument::getMonthlyPayment() 42 | { 43 | return m_monthlyPay; 44 | } 45 | 46 | double BondInstrument::getPrincipal() 47 | { 48 | return m_principal; 49 | } 50 | 51 | 52 | ///////////// 53 | 54 | MortgageInstrument::MortgageInstrument(double monthlyPay, double propertyValue, double downpayment) 55 | : m_monthlyPay(monthlyPay), 56 | m_propertyValue(propertyValue), 57 | m_downPayment(downpayment) 58 | { 59 | 60 | } 61 | 62 | MortgageInstrument::~MortgageInstrument() 63 | { 64 | 65 | } 66 | 67 | MortgageInstrument::MortgageInstrument(const MortgageInstrument &a) 68 | : m_downPayment(a.m_downPayment), 69 | m_propertyValue(a.m_propertyValue), 70 | m_monthlyPay(a.m_monthlyPay) 71 | { 72 | 73 | } 74 | 75 | MortgageInstrument &MortgageInstrument::operator =(const MortgageInstrument &a) 76 | { 77 | if (this != &a) 78 | { 79 | m_downPayment = a.m_downPayment; 80 | m_propertyValue = a.m_propertyValue; 81 | m_monthlyPay = a.m_monthlyPay; 82 | } 83 | return *this; 84 | } 85 | 86 | double MortgageInstrument::getMonthlyPayment() 87 | { 88 | return m_monthlyPay; 89 | } 90 | 91 | double MortgageInstrument::getPrincipal() 92 | { 93 | return m_propertyValue - m_downPayment; 94 | } 95 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/BisectionMethod.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // BisectionMethod.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "BisectionMethod.h" 10 | 11 | #include "MathFunction.h" 12 | #include 13 | #include 14 | 15 | using std::cout; 16 | using std::endl; 17 | 18 | namespace { 19 | const double DEFAULT_ERROR = 0.001; 20 | } 21 | 22 | BisectionMethod::BisectionMethod(MathFunction &f) 23 | : m_f(f), 24 | m_error(DEFAULT_ERROR) 25 | { 26 | } 27 | 28 | BisectionMethod::BisectionMethod(const BisectionMethod &p) 29 | : m_f(p.m_f), 30 | m_error(p.m_error) 31 | { 32 | } 33 | 34 | 35 | BisectionMethod::~BisectionMethod() 36 | { 37 | } 38 | 39 | BisectionMethod &BisectionMethod::operator =(const BisectionMethod &p) 40 | { 41 | if (this != &p) 42 | { 43 | m_f = p.m_f; 44 | m_error = p.m_error; 45 | } 46 | return *this; 47 | } 48 | 49 | double BisectionMethod::getRoot(double x1, double x2) 50 | { 51 | double root = 0; 52 | while (std::abs(x1 - x2) > m_error) 53 | { 54 | double x3 = (x1 + x2) / 2; 55 | root = x3; 56 | cout << "root is " << x3 << endl; // this line just for demonstration 57 | if (m_f(x1) * m_f(x3) < 0) 58 | { 59 | x2 = x3; 60 | } 61 | else 62 | { 63 | x1 = x3; 64 | } 65 | if (m_f(x1) * m_f(x2) > 0) 66 | { 67 | cout << " function does not converge " << endl; 68 | break; 69 | } 70 | } 71 | return root; 72 | } 73 | 74 | // ---- this is the implementation for an example function 75 | 76 | namespace { 77 | 78 | class F1 : public MathFunction { 79 | public: 80 | virtual ~F1(); 81 | virtual double operator()(double value); 82 | }; 83 | 84 | F1::~F1() 85 | { 86 | } 87 | 88 | double F1::operator ()(double x) 89 | { 90 | return (x-1)*(x-1)*(x-1); 91 | } 92 | 93 | } 94 | 95 | int main_bisec() 96 | { 97 | F1 f; 98 | BisectionMethod bm(f); 99 | cout << " the root of the function is " << bm.getRoot(-100, 100) << endl; 100 | return 0; 101 | } 102 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/SecantMethod.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // SecantMethod.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #include "SecantMethod.h" 11 | 12 | #include "MathFunction.h" 13 | #include 14 | #include 15 | 16 | using std::cout; 17 | using std::endl; 18 | 19 | namespace { 20 | const double DEFAULT_ERROR = 0.001; 21 | } 22 | 23 | SecantMethod::SecantMethod(MathFunction &f) 24 | : m_f(f), 25 | m_error(DEFAULT_ERROR) 26 | { 27 | } 28 | 29 | SecantMethod::SecantMethod(const SecantMethod &p) 30 | : m_f(p.m_f), 31 | m_error(p.m_error) 32 | { 33 | } 34 | 35 | SecantMethod::~SecantMethod() 36 | { 37 | } 38 | 39 | SecantMethod &SecantMethod::operator=(const SecantMethod &p) 40 | { 41 | if (this != &p) 42 | { 43 | m_f = p.m_f; 44 | m_error = p.m_error; 45 | } 46 | return *this; 47 | } 48 | 49 | double SecantMethod::getRoot(double a, double b) 50 | { 51 | double root = 0; 52 | double fa = m_f(a); 53 | double fb = m_f(b); 54 | double c = 0, fc = 0; 55 | do 56 | { 57 | c = b - fb*(b-a)/(fb-fa); 58 | root = c; 59 | fc = m_f(c); 60 | 61 | cout << "-> " << c << " " << fc << " " << endl; // this line just for demonstration 62 | 63 | a = b; 64 | fa = fb; 65 | b = c; 66 | fb = fc; 67 | } 68 | while (std::abs(a - b) > m_error); 69 | return root; 70 | } 71 | 72 | // ---- this is the implementation for an example function 73 | 74 | namespace { 75 | 76 | class F2 : public MathFunction { 77 | public: 78 | virtual ~F2(); 79 | virtual double operator()(double value); 80 | }; 81 | 82 | F2::~F2() 83 | { 84 | } 85 | 86 | double F2::operator ()(double x) 87 | { 88 | return (x-1)*(x-1)*(x-1); 89 | // return x*x*x + 4*x*x - 10; 90 | } 91 | 92 | } 93 | 94 | int main_sec() 95 | { 96 | F2 f; 97 | SecantMethod sm(f); 98 | double root = sm.getRoot(-10, 10); 99 | cout << " the root of the function is " << root << endl; 100 | return 0; 101 | } 102 | 103 | -------------------------------------------------------------------------------- /FinancialCppSamples/MaximaCode/optionProbabilities.l: -------------------------------------------------------------------------------- 1 | (lisp:clines " 2 | static double (*optionProbFinishAboveStrike_)(double,double,double,int) = NULL; 3 | static double (*optionProbFinishBellowStrike_)(double,double,double,int) = NULL; 4 | static double (*optionProbFinishBetweenPrices_)(double,double,double,int,double,double) = NULL; 5 | __declspec (dllimport) void *__stdcall LoadLibraryA(const char *); 6 | void *__stdcall GetProcAddress(void *,const char *); 7 | __declspec (dllimport) unsigned int __stdcall GetLastError(void); 8 | 9 | static int libraryLoaded = 0; 10 | static const char *libName = \"optprob.dll\"; 11 | 12 | static int loadLibrary() { 13 | void *lib = LoadLibraryA(libName); 14 | if (!lib) return 0; 15 | optionProbFinishAboveStrike_ = GetProcAddress(lib, \"optionProbFinishAboveStrike\"); 16 | optionProbFinishBellowStrike_ = GetProcAddress(lib, \"optionProbFinishBellowStrike\"); 17 | optionProbFinishBetweenPrices_ = GetProcAddress(lib, \"optionProbFinishBetweenPrices\"); 18 | libraryLoaded = 1; 19 | return 1; 20 | } 21 | 22 | double l_optionProbFinishAboveStrike(double a,double b,double c,int d) { 23 | if (!libraryLoaded && !loadLibrary()) return -1; /* error code */ 24 | if (!optionProbFinishAboveStrike_) return -2; 25 | return optionProbFinishAboveStrike_(a, b, c, d); 26 | 27 | } 28 | double l_optionProbFinishBellowStrike(double a,double b,double c,int d) { 29 | if (!libraryLoaded && !loadLibrary()) return -1; /* error code */ 30 | return optionProbFinishAboveStrike_(a, b, c, d); 31 | } 32 | double l_optionProbFinishBetweenPrices(double a,double b,double c,int d,double e,double f) { 33 | if (!libraryLoaded && !loadLibrary()) return -1; /* error code */ 34 | return optionProbFinishBetweenPrices_(a, b, c, d, e, f); 35 | } 36 | ") 37 | 38 | (lisp:defentry $optionProbFinishAboveStrike (lisp:double lisp:double lisp:double lisp:int) 39 | (lisp:double "l_optionProbFinishAboveStrike")) 40 | 41 | (lisp:defentry $optionProbFinishBellowStrike (lisp:double lisp:double lisp:double lisp:int) 42 | (lisp:double "l_optionProbFinishBellowStrike")) 43 | 44 | (lisp:defentry $optionProbFinishBetweenPrices(lisp:double lisp:double lisp:double lisp:int lisp:double lisp:double) 45 | (lisp:double "l_optionProbFinishBetweenPrices")) 46 | 47 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/RecommendationsProcessor.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // RecommendationsProcessor.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "RecommendationsProcessor.h" 10 | #include 11 | 12 | RecommendationsProcessor::RecommendationsProcessor() 13 | { 14 | 15 | } 16 | 17 | RecommendationsProcessor::~RecommendationsProcessor() 18 | { 19 | 20 | } 21 | 22 | RecommendationsProcessor::RecommendationsProcessor(const RecommendationsProcessor &r) 23 | : m_recommendations(r.m_recommendations) 24 | { 25 | 26 | } 27 | 28 | RecommendationsProcessor &RecommendationsProcessor::operator =(const RecommendationsProcessor &r) 29 | { 30 | if (this != &r) 31 | { 32 | m_recommendations = r.m_recommendations; 33 | } 34 | return *this; 35 | } 36 | 37 | void RecommendationsProcessor::addRecommendation(const std::string &ticker, 38 | RecommendationType rec, double targetPrice) 39 | { 40 | Recommendation r(ticker, rec, targetPrice); 41 | m_recommendations[ticker].push_back(r); 42 | } 43 | 44 | double RecommendationsProcessor::averageTargetPrice(const std::string &ticker) 45 | { 46 | if (m_recommendations.find(ticker) == m_recommendations.end()) 47 | return 0; 48 | auto vrec = m_recommendations[ticker]; 49 | std::vector prices; 50 | for (auto i=0; i recommendations; 66 | for (auto i=0; i 15 | 16 | using std::vector; 17 | using std::cout; 18 | using std::endl; 19 | 20 | TwoDimensionalLPSolver::TwoDimensionalLPSolver(const Vector &c, const Vector &A1, 21 | const Vector &A2, const Vector &b) 22 | : m_c(c), 23 | m_A1(A1), 24 | m_A2(A2), 25 | m_b(b) 26 | { 27 | } 28 | 29 | TwoDimensionalLPSolver::TwoDimensionalLPSolver(const TwoDimensionalLPSolver &p) 30 | : m_c(p.m_c), 31 | m_A1(p.m_A1), 32 | m_A2(p.m_A2), 33 | m_b(p.m_b) 34 | { 35 | } 36 | 37 | TwoDimensionalLPSolver::~TwoDimensionalLPSolver() 38 | { 39 | } 40 | 41 | TwoDimensionalLPSolver &TwoDimensionalLPSolver::operator=(const TwoDimensionalLPSolver &p) 42 | { 43 | if (this != &p) 44 | { 45 | m_c = p.m_c; 46 | m_A1 = p.m_A1; 47 | m_A2 = p.m_A2; 48 | m_b = p.m_b; 49 | } 50 | return *this; 51 | } 52 | 53 | bool TwoDimensionalLPSolver::solveProblem(Vector &res, double &objVal) 54 | { 55 | int size = m_b.size(); 56 | Matrix A(size, 2); 57 | for (int j=0; j A1 = { -2.1, 3.1, 7.9}; 70 | vector A2 = { 1, 1, 1 }; 71 | vector c = { 5.3, 7.1 }; 72 | vector b = { 3.4, 4.3, 6 }; 73 | TwoDimensionalLPSolver solver(c, A1, A2, b); 74 | 75 | vector results; 76 | double objVal; 77 | solver.solveProblem(results, objVal); 78 | cout << "objVal : " << objVal << endl; 79 | for (int i=0; i 12 | #include 13 | 14 | NumVector::NumVector() 15 | { 16 | 17 | } 18 | 19 | NumVector::~NumVector() 20 | { 21 | 22 | } 23 | 24 | NumVector::NumVector(const NumVector &v) 25 | : m_values(v.m_values) 26 | { 27 | 28 | } 29 | 30 | NumVector &NumVector::operator=(const NumVector &v) 31 | { 32 | if (this != &v) 33 | { 34 | m_values = v.m_values; 35 | } 36 | return *this; 37 | } 38 | 39 | size_t NumVector::size() const 40 | { 41 | return m_values.size(); 42 | } 43 | 44 | double NumVector::get(int pos) const 45 | { 46 | return m_values[pos]; 47 | } 48 | 49 | void NumVector::add(double val) 50 | { 51 | m_values.push_back(val); 52 | } 53 | 54 | void NumVector::removeLast() 55 | { 56 | m_values.pop_back(); 57 | } 58 | 59 | NumVector operator +(const NumVector &a, const NumVector &b) 60 | { 61 | if (a.size() != b.size()) 62 | { 63 | throw new std::runtime_error("vectors must have the same size"); 64 | } 65 | NumVector result; 66 | for (int i=0; i 12 | #include 13 | 14 | using std::cout; 15 | using std::endl; 16 | 17 | 18 | struct ThreadData { 19 | pthread_t m_thread; 20 | pthread_attr_t m_attr; 21 | }; 22 | 23 | namespace { 24 | 25 | void *thread_function(void *data) 26 | { 27 | Thread *t = reinterpret_cast(data); 28 | t->run(); 29 | return nullptr; 30 | } 31 | } 32 | 33 | Thread::Thread() 34 | : m_data(new ThreadData), 35 | m_joinable(false) 36 | { 37 | pthread_attr_init(&m_data->m_attr); 38 | } 39 | 40 | Thread::~Thread() 41 | { 42 | if (m_data) 43 | { 44 | delete m_data; 45 | } 46 | } 47 | 48 | 49 | void Thread::start() 50 | { 51 | pthread_create(&m_data->m_thread, &m_data->m_attr, thread_function, this); 52 | } 53 | 54 | void Thread::endThread() 55 | { 56 | pthread_exit(nullptr); 57 | } 58 | 59 | void Thread::setJoinable(bool yes) 60 | { 61 | pthread_attr_setdetachstate(&m_data->m_attr, 62 | yes ? PTHREAD_CREATE_JOINABLE : PTHREAD_CREATE_DETACHED); 63 | m_joinable = yes; 64 | } 65 | 66 | void Thread::run() 67 | { 68 | cout << " no concreate implementation provided " << endl; 69 | } 70 | 71 | void Thread::join() 72 | { 73 | if (!m_joinable) 74 | { 75 | cout << " thread cannot be joined " << endl; 76 | } 77 | else 78 | { 79 | void *result; 80 | pthread_join(m_data->m_thread, &result); 81 | } 82 | } 83 | 84 | 85 | // --- sample implementation 86 | 87 | class TestThread : public Thread { 88 | public: 89 | virtual void run(); 90 | }; 91 | 92 | void TestThread::run() 93 | { 94 | cout << " this is a test implementation " << endl; 95 | endThread(); 96 | } 97 | 98 | int main_thread() 99 | { 100 | Thread *myThread = new TestThread; 101 | myThread->setJoinable(true); 102 | myThread->start(); 103 | myThread->join(); 104 | return 0; 105 | } 106 | 107 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MidpointIntegration.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // MidpointIntegration.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "MidpointIntegration.h" 10 | 11 | #include "MathFunction.h" 12 | 13 | #include 14 | 15 | using std::cout; 16 | using std::endl; 17 | 18 | namespace { 19 | const int DEFAULT_NUM_INTERVALS = 100; 20 | } 21 | 22 | MidpointIntegration::MidpointIntegration(MathFunction &f) 23 | : m_f(f), 24 | m_numIntervals(DEFAULT_NUM_INTERVALS) 25 | { 26 | } 27 | 28 | MidpointIntegration::MidpointIntegration(const MidpointIntegration &p) 29 | : m_f(p.m_f), 30 | m_numIntervals(p.m_numIntervals) 31 | { 32 | } 33 | 34 | MidpointIntegration::~MidpointIntegration() 35 | { 36 | } 37 | 38 | MidpointIntegration &MidpointIntegration::operator=(const MidpointIntegration &p) 39 | { 40 | if (this != &p) 41 | { 42 | m_f = p.m_f; 43 | m_numIntervals = p.m_numIntervals; 44 | } 45 | return *this; 46 | } 47 | 48 | void MidpointIntegration::setNumIntervals(int n) 49 | { 50 | m_numIntervals = n; 51 | } 52 | 53 | double MidpointIntegration::getIntegral(double a, double b) 54 | { 55 | double S = 0; 56 | double intSize = (b - a)/m_numIntervals; 57 | double x = a; 58 | 59 | for (int i=0; i 73 | { 74 | public: 75 | ~F1(); 76 | double operator()(double x); 77 | }; 78 | 79 | 80 | F1::~F1() 81 | { 82 | } 83 | 84 | double F1::operator()(double x) 85 | { 86 | return x*x+1; 87 | } 88 | 89 | } 90 | 91 | int main_mpi() 92 | { 93 | F1 f; 94 | MidpointIntegration mpi(f); 95 | double integral = mpi.getIntegral(1, 5); 96 | cout << " the integral of the function is " << integral << endl; 97 | 98 | mpi.setNumIntervals(200); 99 | integral = mpi.getIntegral(1, 5); 100 | cout << " the integral of the function with 200 intervals is " << integral << endl; 101 | return 0; 102 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/ResourceAlloc.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // ResourceAlloc.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "ResourceAlloc.h" 10 | 11 | #include "MIPSolver.h" 12 | #include "Matrix.h" 13 | 14 | #include 15 | 16 | using std::vector; 17 | using std::cout; 18 | using std::endl; 19 | 20 | ResourceAlloc::ResourceAlloc(vector &result, double &objVal) 21 | : m_results(result), 22 | m_objVal(objVal) 23 | { 24 | } 25 | 26 | ResourceAlloc::ResourceAlloc(const ResourceAlloc &p) 27 | : m_results(p.m_results), 28 | m_objVal(p.m_objVal) 29 | { 30 | } 31 | 32 | ResourceAlloc::~ResourceAlloc() 33 | { 34 | } 35 | 36 | ResourceAlloc &ResourceAlloc::operator=(const ResourceAlloc &p) 37 | { 38 | if (this != &p) 39 | { 40 | m_results = p.m_results; 41 | m_objVal = p.m_objVal; 42 | } 43 | return *this; 44 | } 45 | 46 | void ResourceAlloc::solveProblem() 47 | { 48 | static const double cost_array[][5] = { 49 | // Years: 50 | // 1 2 3 4 5 51 | {1.81, 2.4, 2.5, 0.97, 1.5}, // proj 1 52 | {1.29, 1.8, 2.3, 0.56, 0.5}, // proj 2 53 | {1.22, 1.2, 0.1, 0.48, 0 }, // proj 3 54 | {1.43, 1.4, 1.2, 1.2, 1.2}, // proj 4 55 | {1.62, 1.9, 2.5, 2.0, 1.8}, // proj 5 56 | }; 57 | 58 | Matrix costs(5,5); // cost matrix 59 | for (int i=0; i<5; ++i) { 60 | for (int j=0; j<5; ++j) { 61 | costs[j][i] = cost_array[i][j]; 62 | } 63 | } 64 | 65 | vector returns = {12.13, 3.95, 7.2, 4.21, 11.39}; // investment returns 66 | vector budgets = {5.1, 6.4, 6.84, 4.5, 3.8}; // annual budgets 67 | MIPSolver solver(costs, budgets, returns); 68 | solver.setMaximization(); 69 | 70 | for (int i=0; i<5; ++i) 71 | { 72 | solver.setColBinary(i); 73 | } 74 | 75 | // --- solve the problem 76 | solver.solve(m_results, m_objVal); 77 | } 78 | 79 | int main_ra() 80 | { 81 | 82 | vector result; 83 | double objVal; 84 | 85 | ResourceAlloc ra(result, objVal); 86 | ra.solveProblem(); 87 | cout << " optimum: " << objVal ; 88 | for (int i=0; i 14 | #include 15 | 16 | using std::endl; 17 | using std::cout; 18 | 19 | namespace { 20 | const double DEFAULT_ERROR = 0.001; 21 | } 22 | 23 | NewtonMethod::NewtonMethod(MathFunction &f, MathFunction &derivative) 24 | : m_f(f), 25 | m_derivative(derivative), 26 | m_error(DEFAULT_ERROR) 27 | { 28 | } 29 | 30 | NewtonMethod::NewtonMethod(const NewtonMethod &p) 31 | : m_f(p.m_f), 32 | m_derivative(p.m_derivative), 33 | m_error(p.m_error) 34 | { 35 | } 36 | 37 | NewtonMethod::~NewtonMethod() 38 | { 39 | } 40 | 41 | NewtonMethod &NewtonMethod::operator=(const NewtonMethod &p) 42 | { 43 | if (this != &p) 44 | { 45 | m_f = p.m_f; 46 | m_derivative = p.m_derivative; 47 | m_error = p.m_error; 48 | } 49 | return *this; 50 | } 51 | 52 | double NewtonMethod::getRoot(double x0) 53 | { 54 | double x1 = x0; 55 | do 56 | { 57 | x0 = x1; 58 | cout << " x0 is " << x0 << endl; // this line just for demonstration 59 | double d = m_derivative(x0); 60 | double y = m_f(x0); 61 | x1 = x0 - y / d; 62 | } 63 | while (std::abs(x0 - x1) > m_error); 64 | return x1; 65 | } 66 | 67 | // ---- this is the implementation for an example function and its derivative 68 | 69 | namespace { 70 | 71 | class F3 : public MathFunction { 72 | public: 73 | virtual ~F3(); 74 | virtual double operator()(double value); 75 | }; 76 | 77 | F3::~F3() 78 | { 79 | } 80 | 81 | double F3::operator ()(double x) 82 | { 83 | return (x-1)*(x-1)*(x-1); 84 | } 85 | 86 | class DF3 : public MathFunction { 87 | public: 88 | virtual ~DF3(); 89 | virtual double operator()(double value); 90 | }; 91 | 92 | // represents the derivative of F3 93 | DF3::~DF3() 94 | { 95 | } 96 | 97 | double DF3::operator ()(double x) 98 | { 99 | return 3*(x-1)*(x-1); 100 | } 101 | 102 | } 103 | 104 | int main_nm() 105 | { 106 | F3 f; 107 | DF3 df; 108 | NewtonMethod nm(f, df); 109 | cout << " the root of the function is " << nm.getRoot(100) << endl; 110 | return 0; 111 | } 112 | 113 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/SimpsonsIntegration.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // SimpsonsIntegration.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "SimpsonsIntegration.h" 10 | 11 | #include "MathFunction.h" 12 | 13 | #include 14 | #include 15 | 16 | using std::cout; 17 | using std::endl; 18 | 19 | namespace { 20 | const int DEFAULT_NUM_INTERVALS = 100; 21 | } 22 | 23 | SimpsonsIntegration::SimpsonsIntegration(MathFunction &f) 24 | : m_f(f), 25 | m_numIntervals(DEFAULT_NUM_INTERVALS) 26 | { 27 | } 28 | 29 | SimpsonsIntegration::SimpsonsIntegration(const SimpsonsIntegration &p) 30 | : m_f(p.m_f), 31 | m_numIntervals(p.m_numIntervals) 32 | { 33 | } 34 | 35 | SimpsonsIntegration::~SimpsonsIntegration() 36 | { 37 | } 38 | 39 | SimpsonsIntegration &SimpsonsIntegration::operator=(const SimpsonsIntegration &p) 40 | { 41 | if (this != &p) 42 | { 43 | m_f = p.m_f; 44 | m_numIntervals = p.m_numIntervals; 45 | } 46 | return *this; 47 | } 48 | 49 | double SimpsonsIntegration::getIntegral(double a, double b) 50 | { 51 | double S = 0; 52 | double intSize = (b - a)/m_numIntervals; 53 | double x = a; 54 | 55 | for (int i=0; i 73 | { 74 | public: 75 | ~F2(); 76 | double operator()(double x); 77 | }; 78 | 79 | 80 | F2::~F2() 81 | { 82 | } 83 | 84 | double F2::operator()(double x) 85 | { 86 | return sin(x); 87 | } 88 | 89 | } 90 | 91 | int main_simp() 92 | { 93 | F2 f; 94 | SimpsonsIntegration si(f); 95 | double integral = si.getIntegral(0.5, 2.5); 96 | cout << " the integral of the function is " << integral << endl; 97 | 98 | si.setNumIntervals(200); 99 | integral = si.getIntegral(0.5, 2.5); 100 | cout << " the integral of the function with 200 intervals is " << integral << endl; 101 | return 0; 102 | } 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/TrapezoidIntegration.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // TrapezoidIntegration.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "TrapezoidIntegration.h" 10 | 11 | #include "MathFunction.h" 12 | 13 | #include 14 | #include 15 | 16 | using std::cout; 17 | using std::endl; 18 | 19 | namespace { 20 | const int DEFAULT_NUM_INTERVALS = 100; 21 | } 22 | 23 | TrapezoidIntegration::TrapezoidIntegration(MathFunction &f) 24 | : m_f(f), 25 | m_numIntervals(DEFAULT_NUM_INTERVALS) 26 | { 27 | } 28 | 29 | TrapezoidIntegration::TrapezoidIntegration(const TrapezoidIntegration &p) 30 | : m_f(p.m_f), 31 | m_numIntervals(p.m_numIntervals) 32 | { 33 | } 34 | 35 | TrapezoidIntegration::~TrapezoidIntegration() 36 | { 37 | } 38 | 39 | TrapezoidIntegration &TrapezoidIntegration::operator=(const TrapezoidIntegration &p) 40 | { 41 | if (this != &p) 42 | { 43 | m_f = p.m_f; 44 | m_numIntervals = p.m_numIntervals; 45 | } 46 | return *this; 47 | } 48 | 49 | void TrapezoidIntegration::setNumIntervals(int n) 50 | { 51 | m_numIntervals = n; 52 | } 53 | 54 | double TrapezoidIntegration::getIntegral(double a, double b) 55 | { 56 | double S = 0; 57 | double intSize = (b - a)/m_numIntervals; 58 | double x = a; 59 | 60 | for (int i=0; i 74 | { 75 | public: 76 | ~F2(); 77 | double operator()(double x); 78 | }; 79 | 80 | 81 | F2::~F2() 82 | { 83 | } 84 | 85 | double F2::operator()(double x) 86 | { 87 | return sin(x); 88 | } 89 | } 90 | 91 | int main_trapez() 92 | { 93 | F2 f; 94 | TrapezoidIntegration ti(f); 95 | double integral = ti.getIntegral(0.5, 2.5); 96 | cout << " the integral of the function is " << integral << endl; 97 | 98 | ti.setNumIntervals(200); 99 | integral = ti.getIntegral(0.5, 2.5); 100 | cout << " the integral of the function with 200 intervals is " << integral << endl; 101 | return 0; 102 | } 103 | 104 | 105 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/VolatilityCalculator.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // VolatilityCalculator.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "VolatilityCalculator.h" 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | VolatilityCalculator::VolatilityCalculator() 16 | { 17 | 18 | } 19 | 20 | 21 | VolatilityCalculator::~VolatilityCalculator() 22 | { 23 | 24 | } 25 | 26 | VolatilityCalculator::VolatilityCalculator(const VolatilityCalculator &v) 27 | : m_prices(v.m_prices) 28 | { 29 | 30 | } 31 | 32 | VolatilityCalculator &VolatilityCalculator::operator =(const VolatilityCalculator &v) 33 | { 34 | if (&v != this) 35 | { 36 | m_prices = v.m_prices; 37 | } 38 | return *this; 39 | } 40 | 41 | void VolatilityCalculator::addPrice(double price) 42 | { 43 | m_prices.push_back(price); 44 | } 45 | 46 | double VolatilityCalculator::rangeVolatility() 47 | { 48 | if (m_prices.size() < 1) 49 | { 50 | return 0; 51 | } 52 | 53 | double min = m_prices[0]; 54 | double max = min; 55 | for (int i=1; i max) 62 | { 63 | max = m_prices[i]; 64 | } 65 | } 66 | return max - min; 67 | } 68 | 69 | double VolatilityCalculator::avgDailyRange() 70 | { 71 | unsigned long n = m_prices.size(); 72 | if (n < 2) 73 | { 74 | return 0; 75 | } 76 | 77 | double previous = m_prices[0]; 78 | double sum = 0; 79 | for (int i=1; i 12 | #include 13 | #include 14 | 15 | 16 | TimeSeriesTransformations::TimeSeriesTransformations() 17 | : m_prices() 18 | { 19 | } 20 | 21 | TimeSeriesTransformations::TimeSeriesTransformations(const TimeSeriesTransformations &s) 22 | : m_prices(s.m_prices) 23 | { 24 | } 25 | 26 | TimeSeriesTransformations::~TimeSeriesTransformations() 27 | { 28 | } 29 | 30 | TimeSeriesTransformations &TimeSeriesTransformations::operator=(const TimeSeriesTransformations &v) 31 | { 32 | if (this != &v) 33 | { 34 | m_prices = v.m_prices; 35 | } 36 | return *this; 37 | } 38 | 39 | void TimeSeriesTransformations::reducePrices(double val) 40 | { 41 | std::vector neg(m_prices.size()); 42 | std::transform(m_prices.begin(), m_prices.end(), neg.begin(), std::bind2nd(std::minus(), val)); 43 | m_prices.swap(neg); 44 | } 45 | 46 | void TimeSeriesTransformations::increasePrices(double val) 47 | { 48 | std::for_each(m_prices.begin(), m_prices.end(), std::bind1st(std::plus(), val)); 49 | } 50 | 51 | void TimeSeriesTransformations::removePricesLessThan(double val) 52 | { 53 | std::remove_if(m_prices.begin(), m_prices.end(), std::bind2nd(std::less(), val)); 54 | } 55 | 56 | void TimeSeriesTransformations::removePricesGreaterThan(double val) 57 | { 58 | std::remove_if(m_prices.begin(), m_prices.end(), std::bind2nd(std::greater(), val)); 59 | } 60 | 61 | double TimeSeriesTransformations::getFirstPriceLessThan(double val) 62 | { 63 | auto res = std::find_if(m_prices.begin(), m_prices.end(), std::bind2nd(std::less(), val)); 64 | if (res != m_prices.end()) 65 | return *res; 66 | return 0; 67 | } 68 | 69 | void TimeSeriesTransformations::addValue(double val) 70 | { 71 | m_prices.push_back(val); 72 | } 73 | 74 | void TimeSeriesTransformations::addValues(const std::vector &val) 75 | { 76 | m_prices.insert(m_prices.end(), val.begin(), val.end()); 77 | } 78 | 79 | int main_tstrans() 80 | { 81 | TimeSeriesTransformations ts; 82 | std::vector vals = {7, 6.4, 2.16, 5, 3, 7}; 83 | ts.addValues(vals); 84 | ts.addValue(6.5); 85 | ts.reducePrices(0.5); 86 | std::cout << " price is " << ts.getFirstPriceLessThan(6.0) << std::endl; 87 | return 0; 88 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/LuaWrap.h: -------------------------------------------------------------------------------- 1 | // 2 | // LuaWrapper.h 3 | // original code from luna wrapper example (from http://lua-users.org/wiki/LunaWrapper) 4 | // 5 | // (c) 2015 Carlos Oliveira 6 | // This code is part of the book "Practical C++ Financial Programming" 7 | // by Carlos Oliveira, Apress, 2015. 8 | // For more information, visit http://coliveira.net 9 | 10 | #ifndef __FinancialSamples__Luna__ 11 | #define __FinancialSamples__Luna__ 12 | 13 | #include 14 | 15 | #include 16 | 17 | template class LuaWrapper { 18 | public: 19 | static void Register(lua_State *L) { 20 | lua_pushcfunction(L, &LuaWrapper::constructor); 21 | lua_setglobal(L, T::className); 22 | 23 | luaL_newmetatable(L, T::className); 24 | lua_pushstring(L, "__gc"); 25 | lua_pushcfunction(L, &LuaWrapper::gc_obj); 26 | lua_settable(L, -3); 27 | } 28 | 29 | static int constructor(lua_State *L) { 30 | printf("constructor called");fflush(stdout); 31 | T* obj = new T(L); 32 | 33 | printf("constructor called6");fflush(stdout); 34 | lua_newtable(L); 35 | lua_pushnumber(L, 0); 36 | printf("constructor called5");fflush(stdout); 37 | T** a = (T**)lua_newuserdata(L, sizeof(T*)); 38 | *a = obj; 39 | printf("constructor called4");fflush(stdout); 40 | luaL_getmetatable(L, T::className); 41 | lua_setmetatable(L, -2); 42 | lua_settable(L, -3); // table[0] = obj; 43 | 44 | printf("constructor called2");fflush(stdout); 45 | 46 | for (int i = 0; T::methods[i].name; i++) { 47 | lua_pushstring(L, T::methods[i].name); 48 | lua_pushnumber(L, i); 49 | lua_pushcclosure(L, &LuaWrapper::thunk, 1); 50 | lua_settable(L, -3); 51 | } 52 | printf("constructor called3");fflush(stdout); 53 | 54 | return 1; 55 | } 56 | 57 | static int thunk(lua_State *L) { 58 | int i = (int)lua_tonumber(L, lua_upvalueindex(1)); 59 | lua_pushnumber(L, 0); 60 | lua_gettable(L, 1); 61 | 62 | T** obj = static_cast(luaL_checkudata(L, -1, T::className)); 63 | lua_remove(L, -1); 64 | return ((*obj)->*(T::methods[i].mfunc))(L); 65 | } 66 | 67 | static int gc_obj(lua_State *L) { 68 | T** obj = static_cast(luaL_checkudata(L, -1, T::className)); 69 | delete (*obj); 70 | return 0; 71 | } 72 | 73 | struct RegType { 74 | const char *name; 75 | int(T::*mfunc)(lua_State*); 76 | }; 77 | }; 78 | 79 | 80 | 81 | #endif /* defined(__FinancialSamples__LuaWrapper__) */ 82 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Mutex.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Mutex.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "Mutex.h" 10 | 11 | #include "Thread.h" 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | using std::vector; 19 | using std::cout; 20 | using std::endl; 21 | 22 | struct MutexData { 23 | pthread_mutex_t m_mutex; 24 | }; 25 | 26 | Mutex::Mutex() 27 | : m_data(new MutexData) 28 | { 29 | pthread_mutex_init(&m_data->m_mutex, NULL); 30 | } 31 | 32 | Mutex::~Mutex() 33 | { 34 | if (m_data) 35 | { 36 | pthread_mutex_destroy(&m_data->m_mutex); 37 | delete m_data; 38 | } 39 | } 40 | 41 | void Mutex::lock() 42 | { 43 | pthread_mutex_lock(&(m_data->m_mutex)); 44 | // cout << " &&&& locked \n"; 45 | } 46 | 47 | void Mutex::unlock() 48 | { 49 | // cout << " ^^^^ unlocked \n"; 50 | pthread_mutex_unlock(&(m_data->m_mutex)); 51 | } 52 | 53 | 54 | /// ---- 55 | 56 | MutexAccess::MutexAccess(Mutex &m) 57 | : m_mutex(m) 58 | { 59 | m_mutex.lock(); 60 | } 61 | 62 | MutexAccess::~MutexAccess() 63 | { 64 | m_mutex.unlock(); 65 | } 66 | 67 | 68 | /// ---- 69 | 70 | class MutexTestThread : public Thread { 71 | public: 72 | MutexTestThread(double &result, double incVal); 73 | ~MutexTestThread(); 74 | 75 | void run(); 76 | private: 77 | double &m_result; 78 | double m_incValue; 79 | 80 | static Mutex m_globalMutex; 81 | }; 82 | 83 | Mutex MutexTestThread::m_globalMutex; 84 | 85 | MutexTestThread::MutexTestThread(double &result, double incVal) 86 | : m_result(result), 87 | m_incValue(incVal) 88 | { 89 | } 90 | 91 | MutexTestThread::~MutexTestThread() 92 | { 93 | } 94 | 95 | void MutexTestThread::run() 96 | { 97 | MutexAccess maccess(m_globalMutex); // mutex is locked here 98 | cout << " accessing data " << endl; cout.flush(); 99 | if (m_result > m_incValue) 100 | { 101 | m_result -= m_incValue; 102 | } 103 | else 104 | { 105 | m_incValue += m_incValue; 106 | } 107 | 108 | // mutex is automatically unlocked 109 | } 110 | 111 | int main_mutex() 112 | { 113 | int nThreads = 10; 114 | 115 | vector threads(nThreads); 116 | double price = rand() % 25; 117 | 118 | for (int i=0; isetJoinable(true); 122 | threads[i]->start(); 123 | } 124 | for (int i=0; ijoin(); 127 | } 128 | 129 | cout << " final price is " << price << endl; 130 | return 0; 131 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/VectorOperations.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // VectorOperations.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "VectorOperations.h" 10 | 11 | #include 12 | 13 | 14 | VectorOperations::VectorOperations(const std::vector &p) 15 | : m_data(p) 16 | { 17 | } 18 | 19 | VectorOperations::VectorOperations(const VectorOperations &p) 20 | : m_data(p.m_data) 21 | { 22 | 23 | } 24 | 25 | VectorOperations::~VectorOperations() 26 | { 27 | } 28 | 29 | VectorOperations &VectorOperations::operator=(const VectorOperations &p) 30 | { 31 | if (this != &p) 32 | { 33 | m_data = p.m_data; 34 | } 35 | return *this; 36 | } 37 | 38 | std::vector VectorOperations::scalarMult(double scalar) 39 | { 40 | using namespace boost::numeric::ublas; 41 | vector vx; 42 | 43 | std::copy(m_data.begin(), m_data.end(), vx.end()); 44 | 45 | 46 | vector res = vx * scalar; 47 | 48 | std::vector v; 49 | std::copy(res.begin(), res.end(), v.end()); 50 | 51 | return v; 52 | } 53 | 54 | std::vector VectorOperations::addVector(const std::vector &vec) 55 | { 56 | using namespace boost::numeric::ublas; 57 | 58 | vector v1; 59 | std::copy(m_data.begin(), m_data.end(), v1.end()); 60 | 61 | vector v2; 62 | std::copy(vec.begin(), vec.end(), v2.end()); 63 | 64 | vector v3 = v1 + v2; 65 | 66 | std::vector v; 67 | std::copy(v3.begin(), v3.end(), v.end()); 68 | return v; 69 | } 70 | 71 | std::vector VectorOperations::subtractVector(const std::vector &vec) 72 | { 73 | using namespace boost::numeric::ublas; 74 | 75 | vector v1; 76 | std::copy(m_data.begin(), m_data.end(), v1.end()); 77 | 78 | vector v2; 79 | std::copy(vec.begin(), vec.end(), v2.end()); 80 | 81 | vector v3 = v1 - v2; 82 | 83 | std::vector v; 84 | std::copy(v3.begin(), v3.end(), v.end()); 85 | return v; 86 | } 87 | 88 | double VectorOperations::dotProd(const std::vector &v) 89 | { 90 | 91 | using namespace boost::numeric::ublas; 92 | 93 | vector v1; 94 | std::copy(m_data.begin(), m_data.end(), v1.end()); 95 | 96 | vector v2; 97 | std::copy(v.begin(), v.end(), v2.end()); 98 | 99 | double res = inner_prod(v1, v2); 100 | return res; 101 | } 102 | 103 | 104 | double VectorOperations::norm() 105 | { 106 | using namespace boost::numeric::ublas; 107 | 108 | vector v1; 109 | std::copy(m_data.begin(), m_data.end(), v1.end()); 110 | 111 | double res = norm_2(v1); 112 | return res; 113 | } 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/LinearInterpolation.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // LinearInterpolation.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "LinearInterpolation.h" 10 | 11 | #include 12 | #include 13 | 14 | using std::vector; 15 | using std::cout; 16 | using std::cin; 17 | using std::endl; 18 | 19 | LinearInterpolation::LinearInterpolation() 20 | : m_x(), 21 | m_y() 22 | { 23 | } 24 | 25 | LinearInterpolation::LinearInterpolation(const LinearInterpolation &p) 26 | : m_x(p.m_x), 27 | m_y(p.m_y) 28 | { 29 | } 30 | 31 | LinearInterpolation::~LinearInterpolation() 32 | { 33 | } 34 | 35 | LinearInterpolation &LinearInterpolation::operator=(const LinearInterpolation &p) 36 | { 37 | if (this != &p) 38 | { 39 | m_x = p.m_x; 40 | m_y = p.m_y; 41 | } 42 | return *this; 43 | } 44 | 45 | void LinearInterpolation::setPoints(const std::vector &xpoints, 46 | const std::vector &ypoints) 47 | { 48 | m_x = xpoints; 49 | m_y = ypoints; 50 | 51 | // update points to become sorted on x axis. 52 | std::sort(m_x.begin(), m_x.end()); 53 | for (int i=0; i m_x[m_x.size()-1]) 72 | { 73 | cout << " the value " << x << "is outside the domain " 74 | << m_x[0] << "," << m_x[m_x.size()-1] << endl; 75 | return 0; // outside of domain 76 | } 77 | 78 | for (int i=0; i= x) 86 | { 87 | x1 = m_x[i]; 88 | y1 = m_y[i]; 89 | break; 90 | } 91 | } 92 | 93 | return y0 * (x-x1)/(x0-x1) + y1 * (x-x0)/(x1-x0); 94 | } 95 | 96 | int main_linear_interp() 97 | { 98 | double xi = 0; 99 | double yi = 0; 100 | vector xvals; 101 | vector yvals; 102 | while (cin >> xi) 103 | { 104 | if (xi == -1) 105 | { 106 | break; 107 | } 108 | xvals.push_back(xi); 109 | cin >> yi; 110 | yvals.push_back(yi); 111 | } 112 | double x = 0; 113 | cin >> x; 114 | LinearInterpolation li; 115 | li.setPoints(xvals, yvals); 116 | double y = li.getValue(x); 117 | cout << "interpolation result for value " << x << " is " << y << endl; 118 | return 0; 119 | } 120 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MACalculator.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // MACalculator.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "MACalculator.h" 10 | 11 | #include 12 | 13 | 14 | MACalculator::MACalculator(int numPeriods) 15 | : m_numPeriods(numPeriods) 16 | { 17 | 18 | } 19 | 20 | MACalculator::~MACalculator() 21 | { 22 | 23 | } 24 | 25 | MACalculator::MACalculator(const MACalculator &ma) 26 | : m_numPeriods(ma.m_numPeriods) 27 | { 28 | 29 | } 30 | 31 | MACalculator &MACalculator::operator = (const MACalculator &ma) 32 | { 33 | if (this != &ma) 34 | { 35 | m_numPeriods = ma.m_numPeriods; 36 | m_prices = ma.m_prices; 37 | } 38 | return *this; 39 | } 40 | 41 | std::vector MACalculator::calculateMA() 42 | { 43 | std::vector ma; 44 | double sum = 0; 45 | for (int i=0; i= m_numPeriods) 49 | { 50 | ma.push_back(sum / m_numPeriods); 51 | sum -= m_prices[i-m_numPeriods]; 52 | } 53 | } 54 | return ma; 55 | } 56 | 57 | std::vector MACalculator::calculateEMA() 58 | { 59 | std::vector ema; 60 | double multiplier = 2.0 / (m_numPeriods + 1); 61 | 62 | // calculate the MA to determine the first element corresponding 63 | // to the given number of periods 64 | std::vector ma = calculateMA(); 65 | ema.push_back(ma.front()); 66 | 67 | // for each remaining element, compute the weighted average 68 | for (int i=m_numPeriods+1; i 83 | 84 | // the main function receives parameters passed to the program 85 | int main_macalc(int argc, const char * argv[]) 86 | { 87 | if (argc != 2) 88 | { 89 | std::cout << "usage: progName " << std::endl; 90 | return 1; 91 | } 92 | 93 | int num_periods = atoi(argv[1]); 94 | 95 | 96 | double price; 97 | MACalculator calculator(num_periods); 98 | for (;;) { 99 | std::cin >> price; 100 | if (price == -1) 101 | break; 102 | calculator.addPriceQuote(price); 103 | } 104 | 105 | std::vector ma = calculator.calculateMA(); 106 | 107 | for (int i=0; i 12 | #include 13 | 14 | using std::vector; 15 | using std::cin; 16 | using std::cout; 17 | using std::endl; 18 | 19 | PolynomialInterpolation::PolynomialInterpolation() 20 | : m_x(), 21 | m_y() 22 | { 23 | } 24 | 25 | PolynomialInterpolation::PolynomialInterpolation(const PolynomialInterpolation &p) 26 | : m_y(p.m_y), 27 | m_x(p.m_x) 28 | { 29 | } 30 | 31 | PolynomialInterpolation::~PolynomialInterpolation() 32 | { 33 | } 34 | 35 | PolynomialInterpolation &PolynomialInterpolation::operator=(const PolynomialInterpolation &p) 36 | { 37 | if (this != &p) 38 | { 39 | m_x = p.m_x; 40 | m_y = p.m_y; 41 | } 42 | return *this; 43 | } 44 | 45 | void PolynomialInterpolation::setPoints(const std::vector &x, const std::vector &y) 46 | { 47 | m_x = x; 48 | m_y = y; 49 | 50 | // update points to become sorted on x axis. 51 | std::sort(m_x.begin(), m_x.end()); 52 | for (int i=0; i xvals; 104 | vector yvals; 105 | while (cin >> xi) 106 | { 107 | if (xi == -1) 108 | { 109 | break; 110 | } 111 | xvals.push_back(xi); 112 | cin >> yi; 113 | yvals.push_back(yi); 114 | } 115 | double x = 0; 116 | cin >> x; 117 | PolynomialInterpolation pi; 118 | pi.setPoints(xvals, yvals); 119 | double y = pi.getPolynomial(x); 120 | cout << "interpolation result for value " << x << " is " << y << endl; 121 | // for (double v=10; v < 50; v += 0.1) 122 | // { 123 | // cout << v << ", "; 124 | // } 125 | // cout << endl; 126 | // for (double v=10; v < 50; v += 0.1) 127 | // { 128 | // cout << pi.getValue(v) << ", "; 129 | // } 130 | return 0; 131 | } 132 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FinancialSamples.1: -------------------------------------------------------------------------------- 1 | .\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples. 2 | .\"See Also: 3 | .\"man mdoc.samples for a complete listing of options 4 | .\"man mdoc for the short list of editing options 5 | .\"/usr/share/misc/mdoc.template 6 | .Dd 1/1/14 \" DATE 7 | .Dt FinancialSamples 1 \" Program name and manual section number 8 | .Os Darwin 9 | .Sh NAME \" Section Header - required - don't modify 10 | .Nm FinancialSamples, 11 | .\" The following lines are read in generating the apropos(man -k) database. Use only key 12 | .\" words here as the database is built based on the words here and in the .ND line. 13 | .Nm Other_name_for_same_program(), 14 | .Nm Yet another name for the same program. 15 | .\" Use .Nm macro to designate other names for the documented program. 16 | .Nd This line parsed for whatis database. 17 | .Sh SYNOPSIS \" Section Header - required - don't modify 18 | .Nm 19 | .Op Fl abcd \" [-abcd] 20 | .Op Fl a Ar path \" [-a path] 21 | .Op Ar file \" [file] 22 | .Op Ar \" [file ...] 23 | .Ar arg0 \" Underlined argument - use .Ar anywhere to underline 24 | arg2 ... \" Arguments 25 | .Sh DESCRIPTION \" Section Header - required - don't modify 26 | Use the .Nm macro to refer to your program throughout the man page like such: 27 | .Nm 28 | Underlining is accomplished with the .Ar macro like this: 29 | .Ar underlined text . 30 | .Pp \" Inserts a space 31 | A list of items with descriptions: 32 | .Bl -tag -width -indent \" Begins a tagged list 33 | .It item a \" Each item preceded by .It macro 34 | Description of item a 35 | .It item b 36 | Description of item b 37 | .El \" Ends the list 38 | .Pp 39 | A list of flags and their descriptions: 40 | .Bl -tag -width -indent \" Differs from above in tag removed 41 | .It Fl a \"-a flag as a list item 42 | Description of -a flag 43 | .It Fl b 44 | Description of -b flag 45 | .El \" Ends the list 46 | .Pp 47 | .\" .Sh ENVIRONMENT \" May not be needed 48 | .\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1 49 | .\" .It Ev ENV_VAR_1 50 | .\" Description of ENV_VAR_1 51 | .\" .It Ev ENV_VAR_2 52 | .\" Description of ENV_VAR_2 53 | .\" .El 54 | .Sh FILES \" File used or created by the topic of the man page 55 | .Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact 56 | .It Pa /usr/share/file_name 57 | FILE_1 description 58 | .It Pa /Users/joeuser/Library/really_long_file_name 59 | FILE_2 description 60 | .El \" Ends the list 61 | .\" .Sh DIAGNOSTICS \" May not be needed 62 | .\" .Bl -diag 63 | .\" .It Diagnostic Tag 64 | .\" Diagnostic informtion here. 65 | .\" .It Diagnostic Tag 66 | .\" Diagnostic informtion here. 67 | .\" .El 68 | .Sh SEE ALSO 69 | .\" List links in ascending order by section, alphabetically within a section. 70 | .\" Please do not reference files that do not exist without filing a bug report 71 | .Xr a 1 , 72 | .Xr b 1 , 73 | .Xr c 1 , 74 | .Xr a 2 , 75 | .Xr b 2 , 76 | .Xr a 3 , 77 | .Xr b 3 78 | .\" .Sh BUGS \" Document known, unremedied bugs 79 | .\" .Sh HISTORY \" Document history if command behaves in a unique manner -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FileManager.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // FileManager.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "FileManager.h" 10 | 11 | #define BOOST_NO_CXX11_SCOPED_ENUMS 12 | 13 | #include 14 | 15 | using namespace boost::filesystem; 16 | 17 | FileManager::FileManager(const std::string &basePath) 18 | : m_basePath(basePath) 19 | { 20 | } 21 | 22 | FileManager::FileManager(const FileManager &v) 23 | : m_basePath(v.m_basePath) 24 | { 25 | 26 | } 27 | 28 | FileManager::~FileManager() 29 | { 30 | 31 | } 32 | 33 | FileManager &FileManager::operator=(const FileManager &v) 34 | { 35 | if (this != &v) 36 | { 37 | m_basePath = v.m_basePath; 38 | } 39 | return *this; 40 | } 41 | 42 | void FileManager::removeFiles() 43 | { 44 | std::vector files = getDirectoryContents(); 45 | for (unsigned i=0; i files = getDirectoryContents(); 63 | for (unsigned i=0; i FileManager::getDirectoryContents() 74 | { 75 | std::vector results; 76 | path aPath(m_basePath); 77 | if (!is_directory(aPath)) 78 | { 79 | std::cout << " incorrect path was used " << std::endl; 80 | } 81 | else 82 | { 83 | auto iterator = directory_iterator(aPath); 84 | 85 | std::vector contents; 86 | copy(directory_iterator(aPath), directory_iterator(), back_inserter(contents)); 87 | 88 | for (unsigned i=0; ilistContents(); 107 | 108 | std::vector contents = getDirectoryContents(); 109 | for (auto it = directory_iterator(aPath); it != directory_iterator(); ++it) 110 | { 111 | if (is_regular_file(it->path())) 112 | { 113 | copy_file(it->path(), tmpPath); 114 | } 115 | } 116 | } 117 | 118 | int main_filem() 119 | { 120 | // create a FileManager object for the /tmp directory 121 | // 122 | FileManager fm("/tmp/"); 123 | std::vector contents = fm.getDirectoryContents(); 124 | std::cout << "entries: " << std::endl; 125 | for (std::string entry : contents) 126 | { 127 | std::cout << entry << std::endl; 128 | } 129 | return 0; 130 | } 131 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Date.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Date.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "Date.h" 10 | 11 | #include 12 | #include 13 | 14 | #include 15 | 16 | using namespace boost::gregorian; 17 | 18 | Date::Date(int year, int month, int day) 19 | : m_year(year), 20 | m_month(month), 21 | m_day(day) 22 | { 23 | } 24 | 25 | Date::~Date() 26 | { 27 | } 28 | 29 | bool Date::isLeapYear() 30 | { 31 | if (m_year % 4 != 0) return false; 32 | if (m_year % 100 != 0) return true; 33 | if (m_year % 400 != 0) return false; 34 | return true; 35 | } 36 | 37 | Date &Date::operator++() 38 | { 39 | std::vector m31 = { 1, 3, 5, 7, 8, 10, 12 }; 40 | 41 | if (m_day == 31) 42 | { 43 | m_day = 1; 44 | m_month++; 45 | } 46 | else if (m_day == 30 && std::find(m31.begin(), m31.end(), m_month) == m31.end()) 47 | { 48 | m_day = 1; 49 | m_month++; 50 | } 51 | else if (m_day == 29 && m_month == 2) 52 | { 53 | m_day = 1; 54 | m_month++; 55 | } 56 | else if (m_day == 28 && m_month == 2 && !isLeapYear()) 57 | { 58 | m_day = 1; 59 | m_month++; 60 | } 61 | else 62 | { 63 | m_day++; 64 | } 65 | 66 | if (m_month > 12) 67 | { 68 | m_month = 1; 69 | m_year++; 70 | } 71 | return *this; 72 | } 73 | 74 | int Date::daysInterval(const Date &d) 75 | { 76 | date bdate1(m_year, m_month, m_day); 77 | date bdate2(d.m_year, d.m_month, d.m_day); 78 | 79 | boost::gregorian::date_duration duration = bdate1 - bdate2; 80 | return (int) duration.days(); 81 | } 82 | 83 | bool Date::operator<(const Date &d) 84 | { 85 | if (m_year < d.m_year) return true; 86 | if (m_year == d.m_year && m_month < d.m_month) return true; 87 | if (m_year == d.m_year && m_month == d.m_month && m_day < d.m_day) return true; 88 | return false; 89 | } 90 | 91 | Date::DayOfWeek Date::getDayOfWeek() 92 | { 93 | int day = 1; 94 | Date d(1900, 1, 1); 95 | for (;d < *this; ++d) 96 | { 97 | if (day == 7) day = 1; 98 | else day++; 99 | } 100 | return (DayOfWeek) day; 101 | } 102 | 103 | bool Date::isTradingDay() 104 | { 105 | DayOfWeek dayOfWeek = getDayOfWeek(); 106 | if (dayOfWeek == Sun || dayOfWeek == Sat) 107 | { 108 | return false; 109 | } 110 | return true; 111 | } 112 | 113 | std::string Date::toStringDate(Date::DayOfWeek day) 114 | { 115 | switch(day) 116 | { 117 | case DayOfWeek::Sun: return "Sunday"; 118 | case DayOfWeek::Mon: return "Monday"; 119 | case DayOfWeek::Tue: return "Tuesday"; 120 | case DayOfWeek::Wed: return "Wednesday"; 121 | case DayOfWeek::Thu: return "Thursday"; 122 | case DayOfWeek::Fri: return "Friday"; 123 | case DayOfWeek::Sat: return "Saturday"; 124 | } 125 | throw std::runtime_error("unknown day of week"); 126 | } 127 | 128 | 129 | int main_date() 130 | { 131 | Date myDate(2015, 1, 3); 132 | auto dayOfWeek = myDate.getDayOfWeek(); 133 | std::cout << " day of week is " 134 | << myDate.toStringDate(dayOfWeek) << std::endl; 135 | Date secondDate(2014, 12, 5); 136 | ++secondDate; // test increment operator 137 | ++secondDate; 138 | 139 | int interval = myDate.daysInterval(secondDate); 140 | std::cout << " interval is " << interval << " days" << std::endl; 141 | return 0; 142 | } 143 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/GnuplotPlotter.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // GnuplotPlotter.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "GnuplotPlotter.h" 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | using std::ofstream; 17 | using std::vector; 18 | using std::cout; 19 | using std::endl; 20 | 21 | GnuplotPlotter::GnuplotPlotter(const std::string &fileName) 22 | : m_fileName(fileName), 23 | m_isDate(false) 24 | { 25 | } 26 | 27 | GnuplotPlotter::GnuplotPlotter(const GnuplotPlotter &p) 28 | : m_fileName(p.m_fileName), 29 | m_xheader(p.m_xheader), 30 | m_yheader(p.m_yheader), 31 | m_xdata(p.m_xdata), 32 | m_ydata(p.m_ydata), 33 | m_isDate(p.m_isDate) 34 | { 35 | } 36 | 37 | GnuplotPlotter::~GnuplotPlotter() 38 | { 39 | } 40 | 41 | GnuplotPlotter &GnuplotPlotter::operator=(const GnuplotPlotter &p) 42 | { 43 | if (&p != this) 44 | { 45 | m_fileName = p.m_fileName; 46 | m_xheader = p.m_xheader; 47 | m_yheader = p.m_yheader; 48 | m_xdata = p.m_xdata; 49 | m_ydata = p.m_ydata; 50 | m_isDate = p.m_isDate; 51 | } 52 | return *this; 53 | } 54 | 55 | void GnuplotPlotter::setData(const std::vector &xdata, const std::vector &ydata) 56 | { 57 | m_xdata = xdata; 58 | m_ydata = ydata; 59 | m_isDate = true; // assume that x-axis is a date 60 | } 61 | 62 | void GnuplotPlotter::setData(const std::vector &xdata, const std::vector &ydata) 63 | { 64 | for (unsigned i = 0; i < xdata.size(); ++i) 65 | { 66 | std::stringstream ss; 67 | ss << xdata[i]; 68 | m_xdata.push_back(ss.str()); 69 | } 70 | m_ydata = ydata; 71 | m_isDate = false; // x-axis cannot be a date. 72 | } 73 | 74 | void GnuplotPlotter::setHeaders(const std::string &xheader, const std::string &yheader) 75 | { 76 | m_xheader = xheader; 77 | m_yheader = yheader; 78 | } 79 | 80 | void GnuplotPlotter::generateCmds(const std::string &cmdFileName) 81 | { 82 | ofstream file; 83 | 84 | file.open(cmdFileName.c_str()); 85 | if (file.fail()) 86 | { 87 | cout << "failed to open file " << m_fileName << endl; 88 | return; 89 | } 90 | 91 | if (m_isDate) 92 | { 93 | file << "set xdata time" << endl; 94 | file << "set timefmt \"%Y-%m-%d\" " << endl; 95 | } 96 | file << "set datafile separator \",\" " << endl; 97 | file << "plot '" << m_fileName << "' u 1:2 title columnhead w lines " << endl; 98 | } 99 | 100 | void GnuplotPlotter::csvWrite() 101 | { 102 | ofstream file; 103 | 104 | file.open(m_fileName.c_str()); 105 | if (file.fail()) 106 | { 107 | cout << "failed to open file " << m_fileName << endl; 108 | return; 109 | } 110 | 111 | if (m_xdata.size() != m_ydata.size()) 112 | { 113 | cout << "data has incorrect size " << endl; 114 | return; 115 | } 116 | 117 | file << m_xheader << "," << m_yheader << endl; 118 | 119 | for (unsigned i = 0; i < m_xdata.size(); ++i) 120 | { 121 | file << m_xdata[i] << "," << m_ydata[i] << endl; 122 | } 123 | } 124 | 125 | int main_gp() 126 | { 127 | GnuplotPlotter plotter("test.csv"); 128 | plotter.setHeaders("x", "sin(x)"); 129 | 130 | vector xdata; 131 | vector ydata; 132 | for (int i=0; i<100; ++i) 133 | { 134 | double x = i*10/100.0; 135 | xdata.push_back(x); 136 | ydata.push_back(sin(x)); 137 | } 138 | 139 | plotter.setData(xdata, ydata); 140 | plotter.csvWrite(); 141 | plotter.generateCmds("testcmds.gp"); 142 | return 0; 143 | } 144 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples.xcodeproj/xcuserdata/carlosoliveira.xcuserdatad/xcschemes/FinancialSamples.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 51 | 52 | 58 | 59 | 60 | 61 | 64 | 65 | 66 | 67 | 68 | 69 | 75 | 76 | 82 | 83 | 84 | 85 | 87 | 88 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/FundamentalsCalc.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // FundamentalsCalc.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "FundamentalsCalc.h" 10 | 11 | #include 12 | 13 | 14 | FundamentalsCalculator::FundamentalsCalculator(const std::string &ticker, 15 | double price, double dividend) : 16 | m_ticker(ticker), 17 | m_price(price), 18 | m_dividend(dividend), 19 | m_earningsEstimate(0), 20 | m_numShares(0), 21 | m_bookValue(0), 22 | m_assets(0), 23 | m_liabilitiesAndIntangibles(0), 24 | m_epsGrowth(0), 25 | m_netIncome(0), 26 | m_shareholdersEquity(0) 27 | { 28 | 29 | } 30 | 31 | FundamentalsCalculator::FundamentalsCalculator(const FundamentalsCalculator &v) : 32 | m_ticker(v.m_ticker), 33 | m_price(v.m_price), 34 | m_dividend(v.m_dividend), 35 | m_earningsEstimate(v.m_earningsEstimate), 36 | m_numShares(v.m_numShares), 37 | m_bookValue(v.m_bookValue), 38 | m_assets(v.m_assets), 39 | m_liabilitiesAndIntangibles(v.m_liabilitiesAndIntangibles), 40 | m_epsGrowth(v.m_epsGrowth), 41 | m_netIncome(v.m_netIncome), 42 | m_shareholdersEquity(v.m_shareholdersEquity) 43 | { 44 | 45 | } 46 | 47 | FundamentalsCalculator::~FundamentalsCalculator() 48 | { 49 | 50 | } 51 | 52 | FundamentalsCalculator &FundamentalsCalculator::operator=(const FundamentalsCalculator &v) 53 | { 54 | if (this != &v) 55 | { 56 | m_ticker = v.m_ticker; 57 | m_price = v.m_price; 58 | m_dividend = v.m_dividend; 59 | m_earningsEstimate = v.m_earningsEstimate; 60 | m_numShares = v.m_numShares; 61 | m_bookValue = v.m_bookValue; 62 | m_assets = v.m_assets; 63 | m_liabilitiesAndIntangibles = v.m_liabilitiesAndIntangibles; 64 | m_epsGrowth = v.m_epsGrowth; 65 | m_netIncome = v.m_netIncome; 66 | m_shareholdersEquity = v.m_shareholdersEquity; 67 | } 68 | return *this; 69 | } 70 | 71 | double FundamentalsCalculator::PE() 72 | { 73 | return (m_price * m_numShares)/ m_earnings; 74 | } 75 | 76 | double FundamentalsCalculator::forwardPE() 77 | { 78 | return (m_price * m_numShares)/ m_earningsEstimate; 79 | } 80 | 81 | double FundamentalsCalculator::returnOnEquity() 82 | { 83 | return m_netIncome / m_shareholdersEquity; 84 | } 85 | 86 | double FundamentalsCalculator::getDividend() 87 | { 88 | return m_dividend; 89 | } 90 | 91 | double FundamentalsCalculator::bookValue() 92 | { 93 | return m_bookValue; 94 | } 95 | 96 | double FundamentalsCalculator::priceToBookRatio() 97 | { 98 | return (m_price * m_numShares) / (m_assets - m_liabilitiesAndIntangibles); 99 | } 100 | 101 | double FundamentalsCalculator::priceEarningsToGrowth() 102 | { 103 | return PE()/ m_epsGrowth; 104 | } 105 | 106 | void FundamentalsCalculator::setNumOfShares(int n) 107 | { 108 | m_numShares = n; 109 | } 110 | 111 | void FundamentalsCalculator::setEarnings(double val) 112 | { 113 | m_earnings = val; 114 | } 115 | 116 | void FundamentalsCalculator::setExpectedEarnings(double val) 117 | { 118 | m_earningsEstimate = val; 119 | } 120 | 121 | void FundamentalsCalculator::setBookValue(double val) 122 | { 123 | m_bookValue = val; 124 | } 125 | 126 | void FundamentalsCalculator::setEpsGrowth(double val) 127 | { 128 | m_epsGrowth = val; 129 | } 130 | 131 | void FundamentalsCalculator::setNetIncome(double val) 132 | { 133 | m_netIncome = val; 134 | } 135 | 136 | void FundamentalsCalculator::setShareHoldersEquity(double val) 137 | { 138 | m_shareholdersEquity = val; 139 | } 140 | 141 | void FundamentalsCalculator::setLiabilitiesAndIntangibles(double val) 142 | { 143 | m_liabilitiesAndIntangibles = val; 144 | } 145 | 146 | void FundamentalsCalculator::setAssets(double val) 147 | { 148 | m_assets = val; 149 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/DistributionData.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // DistributionData.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #include "DistributionData.h" 11 | 12 | #include 13 | 14 | #include 15 | 16 | using boost::math::quantile; 17 | 18 | #include 19 | #include 20 | 21 | static boost::rand48 random_generator; 22 | 23 | using std::cout; 24 | using std::endl; 25 | using std::string; 26 | 27 | 28 | DistributionData::DistributionData() 29 | { 30 | } 31 | 32 | DistributionData::~DistributionData() 33 | { 34 | } 35 | 36 | std::vector DistributionData::gaussianData(int nPoints, double mean, double sigma) 37 | { 38 | std::vector data; 39 | 40 | boost::random::normal_distribution<> distrib(mean, sigma); 41 | 42 | for (int i=0; i DistributionData::exponentialData(int nPoints, double rate) 52 | { 53 | std::vector data; 54 | 55 | boost::random::exponential_distribution<> distrib(rate); 56 | 57 | for (int i=0; i DistributionData::logNormalData(int nPoints, double mean, double sigma) 67 | { 68 | std::vector data; 69 | 70 | boost::random::lognormal_distribution<> distrib(mean, sigma); 71 | 72 | for (int i=0; i DistributionData::chiSquaredData(int nPoints, int degreesOfFreedom) 83 | { 84 | std::vector data; 85 | 86 | boost::random::chi_squared_distribution<> distrib(degreesOfFreedom); 87 | 88 | for (int i=0; i dist(mean, sigma); 100 | 101 | return quantile(dist, x); 102 | } 103 | 104 | 105 | double DistributionData::chiSquaredQuantile(double x, int degreesOfFreedom) 106 | { 107 | boost::math::chi_squared_distribution<> dist(degreesOfFreedom); 108 | 109 | return quantile(dist, x); 110 | } 111 | 112 | double DistributionData::exponentialQuantile(double x, double rate) 113 | { 114 | boost::math::exponential_distribution<> dist(rate); 115 | 116 | return quantile(dist, x); 117 | } 118 | 119 | double DistributionData::logNormalQuantile(double x, double mean, double sigma) 120 | { 121 | boost::math::lognormal_distribution<> dist(mean, sigma); 122 | 123 | return quantile(dist, x); 124 | } 125 | 126 | namespace { 127 | template 128 | void printData(const string &label, const T &data) 129 | { 130 | cout << " " << label << ": "; 131 | for (auto i : data) 132 | { 133 | cout << i << " "; 134 | } 135 | cout << endl; 136 | } 137 | } 138 | 139 | int main_distdata() 140 | { 141 | DistributionData dData; 142 | auto gdata = dData.gaussianData(10, 5, 2); 143 | printData("gaussian data", gdata); 144 | 145 | auto edata = dData.exponentialData(10, 4); 146 | printData("exponential data", edata); 147 | 148 | auto kdata = dData.chiSquaredData(10, 5); 149 | printData("chi squared data", kdata); 150 | 151 | auto ldata = dData.logNormalData(10, 8, 2); 152 | printData("log normal data", ldata); 153 | return 0; 154 | } 155 | 156 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/BlackScholesForwardMethod.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // BlackScholesForwardMethod.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | 10 | #include "BlackScholesForwardMethod.h" 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | using std::vector; 19 | using std::cout; 20 | using std::endl; 21 | using std::setw; 22 | 23 | BlackScholesForwardMethod::BlackScholesForwardMethod(double expiration, double maxPrice, 24 | double strike, double intRate) 25 | : m_expiration(expiration), 26 | m_maxPrice(maxPrice), 27 | m_strike(strike), 28 | m_intRate(intRate) 29 | { 30 | } 31 | 32 | BlackScholesForwardMethod::BlackScholesForwardMethod(const BlackScholesForwardMethod &p) 33 | : m_expiration(p.m_expiration), 34 | m_maxPrice(p.m_maxPrice), 35 | m_strike(p.m_strike), 36 | m_intRate(p.m_intRate) 37 | { 38 | } 39 | 40 | BlackScholesForwardMethod::~BlackScholesForwardMethod() 41 | { 42 | } 43 | 44 | BlackScholesForwardMethod &BlackScholesForwardMethod::operator=(const BlackScholesForwardMethod &p) 45 | { 46 | if (this != &p) 47 | { 48 | m_expiration = p.m_expiration; 49 | m_maxPrice = p.m_maxPrice; 50 | m_strike = p.m_strike; 51 | m_intRate = p.m_intRate; 52 | } 53 | return *this; 54 | } 55 | 56 | vector BlackScholesForwardMethod::solve(double volatility, int nx, int timeSteps) 57 | { 58 | double dt = m_expiration /(double)timeSteps; 59 | double dx = m_maxPrice /(double)nx; 60 | 61 | vector a(nx-1); 62 | vector b(nx-1); 63 | vector c(nx-1); 64 | 65 | int i; 66 | for (i = 0; i < nx - 1; i++) 67 | { 68 | b[i] = 1.0 - m_intRate * dt - dt * pow(volatility * (i+1), 2); 69 | } 70 | 71 | for (i = 0; i < nx - 2; i++) 72 | { 73 | c[i] = 0.5 * dt * pow(volatility * (i+1), 2) + 0.5 * dt * m_intRate * (i+1); 74 | } 75 | 76 | for (i = 1; i < nx - 1; i++) 77 | { 78 | a[i] = 0.5 * dt * pow(volatility * (i+1), 2) - 0.5 * dt * m_intRate * (i+1); 79 | } 80 | 81 | vector u((nx-1)*(timeSteps+1)); 82 | 83 | double u0 = 0.0; 84 | for (i = 0; i < nx - 1; i++) 85 | { 86 | u0 += dx; 87 | u[i+0*(nx-1)] = std::max(u0 - m_strike, 0.0); 88 | } 89 | 90 | for (int j = 0; j < timeSteps; j++) 91 | { 92 | double t = (double)(j) * m_expiration /(double)timeSteps; 93 | 94 | double p = 0.5 * dt * (nx - 1) * (volatility*volatility * (nx-1) + m_intRate) 95 | * (m_maxPrice-m_strike * exp(-m_intRate*t ) ); 96 | 97 | for (i = 0; i < nx - 1; i++) 98 | { 99 | u[i+(j+1)*(nx-1)] = b[i] * u[i+j*(nx-1)]; 100 | } 101 | for (i = 0; i < nx - 2; i++) 102 | { 103 | u[i+(j+1)*(nx-1)] += c[i] * u[i+1+j*(nx-1)]; 104 | } 105 | for (i = 1; i < nx - 1; i++) 106 | { 107 | u[i+(j+1)*(nx-1)] += a[i] * u[i-1+j*(nx-1)]; 108 | } 109 | u[nx-2+(j+1)*(nx-1)] += p; 110 | } 111 | 112 | return u; 113 | } 114 | 115 | int main_bsmeth() 116 | { 117 | auto strike = 5.0; 118 | auto intRate = 0.03; 119 | auto sigma = 0.50; 120 | auto t1 = 1.0; 121 | auto numSteps = 11; 122 | auto numDays = 29; 123 | auto maxPrice = 10.0; 124 | 125 | 126 | BlackScholesForwardMethod bsfm(t1, maxPrice, strike, intRate); 127 | vector u = bsfm.solve(sigma, numSteps, numDays); 128 | 129 | double minPrice = .0; 130 | for (int i=0; i < numSteps-1; i++) 131 | { 132 | double s = ((numSteps-i-2) * minPrice+(i+1)*maxPrice)/ (double)(numSteps-1); 133 | cout << " " << s << " " << u[i+numDays*(numSteps-1)] << endl; 134 | } 135 | return 0; 136 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/ParallelRandomWalk.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // ParallelRandomWalk.cpp 3 | 4 | #include "ParallelRandomWalk.h" 5 | 6 | #include "Thread.h" 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | 13 | #include 14 | #include 15 | 16 | using std::vector; 17 | using std::cout; 18 | using std::endl; 19 | 20 | static boost::rand48 random_generator; 21 | 22 | using std::vector; 23 | 24 | /// --- 25 | 26 | 27 | class RandomWalkThread : public Thread { 28 | public: 29 | RandomWalkThread(int num_steps, double sigma, double startPrice); 30 | ~RandomWalkThread(); 31 | virtual void run(); 32 | 33 | double gaussianValue(double mean, double sigma); 34 | double getLastPriceOfWalk(); 35 | 36 | double result(); 37 | private: 38 | int m_numberOfSteps; // number of steps 39 | double m_sigma; // size of each step (in percentage) 40 | double m_startingPrice; // starting price 41 | 42 | double m_result; 43 | }; 44 | 45 | 46 | RandomWalkThread::RandomWalkThread(int numSteps, double sigma, double startingPrice) 47 | : m_numberOfSteps(numSteps), 48 | m_sigma(sigma), 49 | m_startingPrice(startingPrice) 50 | { 51 | } 52 | 53 | RandomWalkThread::~RandomWalkThread() 54 | { 55 | } 56 | 57 | double RandomWalkThread::gaussianValue(double mean, double sigma) 58 | { 59 | boost::random::normal_distribution<> distrib(mean, sigma); 60 | return distrib(random_generator); 61 | } 62 | 63 | double RandomWalkThread::result() 64 | { 65 | return m_result; 66 | } 67 | 68 | double RandomWalkThread::getLastPriceOfWalk() 69 | { 70 | double prev = m_startingPrice; 71 | 72 | for (int i=0; i= m_startingPrice) 94 | { 95 | nAbove++; 96 | } 97 | } 98 | 99 | m_result = nAbove/(double)m_numberOfSteps; 100 | } 101 | 102 | // --- 103 | 104 | 105 | ParallelRandomWalk::ParallelRandomWalk(int size, double start, double step) 106 | : m_size(size), 107 | m_start(start), 108 | m_step(step) 109 | { 110 | } 111 | 112 | ParallelRandomWalk::ParallelRandomWalk(const ParallelRandomWalk &p) 113 | : m_size(p.m_size), 114 | m_start(p.m_start), 115 | m_step(p.m_step) 116 | { 117 | } 118 | 119 | ParallelRandomWalk::~ParallelRandomWalk() 120 | { 121 | } 122 | 123 | ParallelRandomWalk &ParallelRandomWalk::operator=(const ParallelRandomWalk &p) 124 | { 125 | if (this != &p) 126 | { 127 | m_size = p.m_size; 128 | m_start = p.m_start; 129 | m_step = p.m_step; 130 | } 131 | return *this; 132 | } 133 | 134 | double ParallelRandomWalk::probFinishAboveStrike() 135 | { 136 | const int numThreads = 20; 137 | 138 | vector threads(numThreads); 139 | for (int i=0; isetJoinable(true); 143 | threads[i]->start(); 144 | } 145 | 146 | for (int i=0; ijoin(); 149 | } 150 | 151 | double nAbove = 0; 152 | for (int i=0; iresult(); 155 | } 156 | 157 | return nAbove/(double)(numThreads); 158 | } 159 | 160 | 161 | int main() 162 | { 163 | ParallelRandomWalk rw(100, 50.0, 52.0); 164 | double r = rw.probFinishAboveStrike(); 165 | cout << " result is " << r << endl; 166 | return 0; 167 | } -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Matrix.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Matrix.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "Matrix.h" 10 | 11 | #include 12 | 13 | Matrix::Matrix(int size) 14 | { 15 | for (int i=0; i row(size, 0); 18 | m_rows.push_back(row); 19 | } 20 | } 21 | 22 | Matrix::Matrix(int size, int size2) 23 | { 24 | for (int i=0; i row(size2, 0); 27 | m_rows.push_back(row); 28 | } 29 | } 30 | 31 | Matrix::Matrix(const Matrix &s) 32 | : m_rows(s.m_rows) 33 | { 34 | } 35 | 36 | Matrix::~Matrix() 37 | { 38 | } 39 | 40 | Matrix &Matrix::operator=(const Matrix &s) 41 | { 42 | if (this != &s) 43 | { 44 | m_rows = s.m_rows; 45 | } 46 | return *this; 47 | } 48 | 49 | Matrix::Row &Matrix::operator[](int pos) 50 | { 51 | return m_rows[pos]; 52 | } 53 | 54 | void Matrix::transpose() 55 | { 56 | std::vector rows; 57 | for (unsigned i=0;i row; 60 | for (unsigned j=0; j rows; 122 | for (unsigned i=0; i row; 125 | for (unsigned j=0; j 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | 18 | #include 19 | 20 | 21 | using std::vector; 22 | 23 | class PlotWindow : public QMainWindow { 24 | public: 25 | PlotWindow(); 26 | ~PlotWindow(); 27 | void paintEvent(QPaintEvent *event); 28 | void setData(const vector &xdata, const vector &ydata); 29 | private: 30 | vector m_xdata; 31 | vector m_ydata; 32 | }; 33 | 34 | PlotWindow::PlotWindow() 35 | { 36 | } 37 | 38 | PlotWindow::~PlotWindow() 39 | { 40 | } 41 | 42 | void PlotWindow::setData(const vector &xdata, const vector &ydata) 43 | { 44 | m_xdata = xdata; 45 | m_ydata = ydata; 46 | } 47 | 48 | void PlotWindow::paintEvent(QPaintEvent *event) 49 | { 50 | QMainWindow::paintEvent(event); 51 | QPainter painter(this); 52 | 53 | // define margins 54 | double marginX = 10; 55 | double marginY = 10; 56 | double lengthX = 500; 57 | double lengthY = 400; 58 | 59 | 60 | // define axis 61 | int maxX = lengthX, maxY = lengthY; 62 | painter.drawLine(marginX,marginY, marginX, lengthY+marginY); 63 | painter.drawLine(marginX,lengthY + marginY, lengthX, lengthY + marginY); 64 | 65 | // find units 66 | int largeX = 0, largeY = 0; 67 | double largeXd = 0, largeYd = 0; 68 | for (unsigned i=1; i &xdata, const std::vector &ydata) 124 | { 125 | m_xdata = xdata; 126 | m_ydata = ydata; 127 | } 128 | 129 | int QtPlotter::plotWindowRun() 130 | { 131 | char *arg = (char *)"plotter"; 132 | int argc = 1; 133 | return plotWindowRun(argc, &arg); 134 | } 135 | 136 | int QtPlotter::plotWindowRun(int argc, char **argv) 137 | { 138 | QApplication app(argc, argv); 139 | 140 | app.setApplicationName("Qt Plotter"); 141 | PlotWindow window; 142 | 143 | window.resize(600, 600); 144 | window.show(); 145 | return app.exec(); 146 | } 147 | 148 | int main_qt() 149 | { 150 | QtPlotter plotter; 151 | 152 | vector xdata; 153 | vector ydata; 154 | for (int i=0; i<100; ++i) 155 | { 156 | double x = i*10/100.0; 157 | xdata.push_back(x); 158 | ydata.push_back(sin(x)+1); 159 | } 160 | 161 | 162 | plotter.setData(xdata, ydata); 163 | 164 | return plotter.plotWindowRun(); 165 | } 166 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/MonteCarloIntegration.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // MonteCarloIntegration.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "MonteCarloIntegration.h" 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #include "MathFunction.h" 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | static boost::rand48 random_generator; 23 | 24 | using std::cout; 25 | using std::endl; 26 | 27 | namespace { 28 | const int DEFAULT_NUM_SAMPLES = 1000; 29 | } 30 | 31 | MonteCarloIntegration::MonteCarloIntegration(MathFunction& f) 32 | : m_f(f), 33 | m_numSamples(DEFAULT_NUM_SAMPLES) 34 | { 35 | } 36 | 37 | MonteCarloIntegration::MonteCarloIntegration(const MonteCarloIntegration& p) 38 | : m_f(p.m_f), 39 | m_numSamples(p.m_numSamples) 40 | { 41 | } 42 | 43 | MonteCarloIntegration::~MonteCarloIntegration() 44 | { 45 | } 46 | 47 | MonteCarloIntegration& MonteCarloIntegration::operator =(const MonteCarloIntegration& p) 48 | { 49 | if (this != &p) 50 | { 51 | m_f = p.m_f; 52 | m_numSamples = p.m_numSamples; 53 | } 54 | return *this; 55 | } 56 | 57 | void MonteCarloIntegration::setNumSamples(int n) 58 | { 59 | m_numSamples = n; 60 | } 61 | 62 | double MonteCarloIntegration::integrateRegion(double a, double b, double min, double max) 63 | { 64 | boost::random::uniform_real_distribution<> xDistrib(a, b); 65 | boost::random::uniform_real_distribution<> yDistrib(min, max); 66 | 67 | int pointsIn = 0; 68 | int pointsOut = 0; 69 | bool positive = max > 0; 70 | 71 | for (int i = 0; i < m_numSamples; ++i) 72 | { 73 | double x = xDistrib(random_generator); 74 | double y = m_f(x); 75 | 76 | double ry = yDistrib(random_generator); 77 | if (positive && min <= ry && ry <= y) 78 | { 79 | pointsIn++; 80 | } 81 | else if (!positive && y <= ry && ry <= max) 82 | { 83 | pointsIn++; 84 | } 85 | else 86 | { 87 | pointsOut++; 88 | } 89 | } 90 | 91 | double percentageArea = 0; 92 | if (pointsIn+pointsOut > 0) 93 | { 94 | percentageArea = pointsIn / double(pointsIn + pointsOut); 95 | } 96 | 97 | if (percentageArea > 0) 98 | { 99 | return (b-a) * (max-min) * percentageArea; 100 | } 101 | 102 | return 0; 103 | } 104 | 105 | double MonteCarloIntegration::getIntegral(double a, double b) 106 | { 107 | boost::random::uniform_real_distribution<> distrib(a, b); 108 | 109 | double max = 0; 110 | double min = 0; 111 | 112 | for (int i = 0; i < m_numSamples; ++i) 113 | { 114 | double x = distrib(random_generator); 115 | double y = m_f(x); 116 | 117 | if (y > max) 118 | { 119 | max = y; 120 | } 121 | if (y < min) 122 | { 123 | min = y; 124 | } 125 | } 126 | double positiveIntg = max > 0 ? integrateRegion(a, b, 0, max) : 0; 127 | double negativeIntg = min < 0 ? integrateRegion(a, b, min, 0) : 0; 128 | return positiveIntg - negativeIntg; 129 | } 130 | 131 | // Example function 132 | 133 | namespace { 134 | 135 | class FSin : public MathFunction 136 | { 137 | public: 138 | ~FSin(); 139 | double operator()(double x); 140 | }; 141 | 142 | 143 | FSin::~FSin() 144 | { 145 | } 146 | 147 | double FSin::operator()(double x) 148 | { 149 | return sin(x); 150 | } 151 | 152 | } 153 | 154 | 155 | int main() 156 | { 157 | cout << "starting" << endl; 158 | FSin f; 159 | MonteCarloIntegration mci(f); 160 | double integral = mci.getIntegral(0.5, 4.9); 161 | cout << " the integral of the function is " << integral << endl; 162 | 163 | mci.setNumSamples(200000); 164 | integral = mci.getIntegral(0.5, 4.9); 165 | cout << " the integral of the function with 20000 intervals is " << integral << endl; 166 | return 0; 167 | } 168 | 169 | -------------------------------------------------------------------------------- /FinancialCppSamples/FinancialSamples/Stock_Py.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Stock_Py.cpp 3 | // 4 | // (c) 2015 Carlos Oliveira 5 | // This code is part of the book "Practical C++ Financial Programming" 6 | // by Carlos Oliveira, Apress, 2015. 7 | // For more information, visit http://coliveira.net 8 | 9 | #include "Stock_Py.h" 10 | #include "Stock.h" 11 | 12 | #if 0 13 | #include 14 | #include 15 | 16 | #include 17 | 18 | namespace { 19 | 20 | void stock_destructor(PyObject *capsule) 21 | { 22 | printf("calling destructor\n"); 23 | Stock *stock = reinterpret_cast(PyCapsule_GetPointer(capsule, NULL)); 24 | delete stock; 25 | } 26 | 27 | PyObject *stock_create(PyObject *self, PyObject *args) 28 | { 29 | char *ticker; 30 | double price; 31 | double dividend; 32 | if (!PyArg_ParseTuple(args, "sdd", &ticker, &price, ÷nd)) 33 | return NULL; 34 | 35 | printf("ticker: %s, price: %lf, dividend: %lf\n", ticker, price, dividend); 36 | 37 | Stock *stock = new Stock(ticker, price, dividend); 38 | 39 | PyObject* stockObj = PyCapsule_New(stock, NULL, stock_destructor); 40 | return stockObj; 41 | } 42 | 43 | Stock *getStock(PyObject *obj) 44 | { 45 | if (!PyCapsule_CheckExact(obj)) 46 | printf("error: not a stock object\n"); 47 | fflush(stdout); 48 | return reinterpret_cast(PyCapsule_GetPointer(obj, NULL)); 49 | } 50 | 51 | PyObject *returnNone() 52 | { 53 | Py_INCREF(Py_None); 54 | return Py_None; 55 | } 56 | 57 | PyObject *stock_ticker(PyObject *self, PyObject *args) 58 | { 59 | PyObject *obj; 60 | if (!PyArg_ParseTuple(args, "O!", &PyCapsule_Type, &obj)) 61 | return NULL; 62 | 63 | Stock *stock = getStock(obj); 64 | return Py_BuildValue("s", stock->ticker().c_str()); 65 | } 66 | 67 | PyObject *stock_price(PyObject *self, PyObject *args) 68 | { 69 | PyObject *obj; 70 | if (!PyArg_ParseTuple(args, "O!", &PyCapsule_Type, &obj)) 71 | return NULL; 72 | 73 | Stock *stock = getStock(obj); 74 | return Py_BuildValue("d", stock->price()); 75 | } 76 | 77 | PyObject *stock_setPrice(PyObject *self, PyObject *args) 78 | { 79 | double price; 80 | PyObject *obj; 81 | if (!PyArg_ParseTuple(args, "O!d", &PyCapsule_Type, &obj, &price)) 82 | return NULL; 83 | 84 | Stock *stock = getStock(obj); 85 | if (!stock) 86 | return NULL; 87 | stock->setPrice(price); 88 | return returnNone(); 89 | } 90 | 91 | PyObject *stock_dividend(PyObject *self, PyObject *args) 92 | { 93 | PyObject *obj; 94 | if (!PyArg_ParseTuple(args, "O!", &PyCapsule_Type, &obj)) 95 | return NULL; 96 | 97 | Stock *stock = getStock(obj); 98 | if (!stock) 99 | return NULL; 100 | return Py_BuildValue("d", stock->dividend()); 101 | } 102 | 103 | PyObject *stock_setDividend(PyObject *self, PyObject *args) 104 | { 105 | double dividend; 106 | PyObject *obj; 107 | if (!PyArg_ParseTuple(args, "O!d", &PyCapsule_Type, &obj, ÷nd)) 108 | return NULL; 109 | 110 | Stock *stock = getStock(obj); 111 | 112 | stock->setDividend(dividend); 113 | return returnNone(); 114 | } 115 | 116 | PyObject *stock_dividendYield(PyObject *self, PyObject *args) 117 | { 118 | PyObject *obj; 119 | if (!PyArg_ParseTuple(args, "O!", &PyCapsule_Type, &obj)) 120 | return NULL; 121 | Stock *stock = getStock(obj); 122 | return Py_BuildValue("d", stock->dividendYield()); 123 | } 124 | 125 | PyMethodDef stockMethods[] = { 126 | {"new", stock_create, METH_VARARGS, "Create a new stock object."}, 127 | {"ticker", stock_ticker, METH_VARARGS, "get ticker for a stock object."}, 128 | {"price", stock_price, METH_VARARGS, "get price for stock."}, 129 | {"setPrice", stock_setPrice, METH_VARARGS, "set price for a stock object."}, 130 | {"dividend", stock_dividend, METH_VARARGS, "get dividend for stock."}, 131 | {"setDividend", stock_setDividend, METH_VARARGS, "set dividend for a stock object."}, 132 | {"dividendYield", stock_dividendYield, METH_VARARGS, "get dividend yield for stock."}, 133 | {NULL, NULL, 0, NULL} 134 | }; 135 | 136 | } 137 | 138 | PyMODINIT_FUNC initstock() 139 | { 140 | Py_InitModule("stock", stockMethods); 141 | 142 | } 143 | 144 | #endif --------------------------------------------------------------------------------