Enhancing Hands-on Learning using Mathematica: A case of Investment Analysis

Ramesh Adhikari
 Humboldt State University

Presentaton Outline

1. The Case for Use of Wolfram Lanaguage
2. Accessing Financial Data and Basic Data Visualization
3. Capital Budgeting and Business Valuation
4. Performance Analysis of Stocks Returns
5. Factor Models 
6. Stock Portfolio Performance Measures 
7. Interactive Graphics and Technical Analysis of Stock Prices 
8. Bonds and Derivatives  
9. Linear Programming and Applications 
10. Mean-Variance Optimization under Uncertainty
11. Mean-CVaR Optimization  
12. Simulation and Bootstrapping
13. Introductory Time Series Analysis and Forecasting 
14. AI and Machine Learning 
15. Conclusions

1. The Case for Use of Wolfram Language

Notebook’s interactive nature and its ability to hold text, codes, results and graphics makes it self-contained document and easy to understand.

Evarything is reproducible and interactive for analysis.

High-level built-in knowledge. Can bridge the gap that exists between mathematical background and its application.

Can handle not only symbolic and numerical calculations but also graphics and linguistics. These features make a good tool for investment analysis.

Compatibility with other programming language.

Generous licensing policy. Also cheaper.

NotebookEvaluate["C:\\Users\\rkadh\\Desktop\\Paper 7\\Codes\\myfunctions.nb",InsertResults->True]

2. Accessing Financial Data and Basic   Data Visualization

Company or CompanyData or Financial functions can be used to access company specific financial data. Similarly, FinancialData can be used to get data about stocks and other financial instruments.

plotCompanydata["AAPL",{2000,1,1},{2019,1,1},{"ROA","ROE","RevenueGrowth"}]

plotCompaniesdata[{"AAPL","FB","WMT","BAC"},{2000,1,1},{2019,1,1},"RevenueGrowth"]

Data from Quandl and Federal Reserve

FedDataPlot["USSLIND",{1990,01,30},{2019,03,30},"Leading Index"]

getCompanydata["AAPL",{2000,1,1},{2019,1,1},{"ROA","ROE","RevenueGrowth"}]

3. Capital Budgeting and Business Valuation

You need an equipment that can be purchased by borrowing at 8% APR or leased as a true tax lease. The cost of the equipment is 100000 with five years of expected life and depreciated using straight line depreciation to its residual value of 5000. It can be leased with its residual value of 5000 and lessor requires 10% return. If the current tax rate is 21%, should you lease or purchase?

leaseVsbuy[0.08,5,.1,1,100000,5000,0.21]

Three Stage Growth Business Valuation Model

Consider a company in the early stage of its life cycle assuming that the company experienced 10 percent growth in the past year. The company is expected to grow by 8% more each year for the next 7  years and its growth will start to decline by 5% each year after 7th year for 5 years. After 12 years, the company is expected to grow at the rate of the overall economy which is 2.5% per year. If the past year’s CFC was $100 million and the weighted average cost of capital is 9.5%, what should be the value of the firm?

ThreeStageDCFModel[100,0.1,0.08,7,-0.05,7,0.025,0.095]

4. Performance Analysis of Stocks Returns

Individual Stocks

performanceChartOneSymbol["SPY",{2018,10,10},{2019,6,7},"Day"]

performanceStatsOneSymbol["WMT",{2010,10,10},{2019,6,6},"Month"]

Multiple Stocks

norp=normalizedPrices[{"FB","COST","WMT"},{2000,5,1},{2019,5,30},"Week"];
DateListPlot[norp,PlotTheme->"Detailed",PlotLabel->"Normalized Weekly Prices Returns Over Time",PlotRange-> All,PlotLegends->{"FB","COST","WMT"}]
cret=cumlativeReturns[{"FB","COST","WMT"},{2010,06,10},{2019,6,30},"Week"];
DateListPlot[cret,PlotTheme->"Detailed",PlotLabel->"Cumulative Returns Over Time",PlotRange-> All,PlotLegends->{"FB","COST","WMT"}]

performanceStatsTable[{"WMT", "AAPL", "MSFT", "NFLX"}, {2010, 1, 1}, {2019, 3, 30}, "Month"]

5. Factor Models

Factor models are widely accepted and utilized in finance for predicting market returns. Mathematica has the ability to download all factors data from Kenneth French data library and use it in the regression. Build in functions for regression diagnostics make estimaton of factor models more relavent.

dataFiveFM=dataforFiveFactorModel["AAPL",{2008,10,1},{2019,3,30}]; 
fivefmodel=LinearModelFit[dataFiveFM,{MRRF,SMB,HML,RMW,CMA},{MRRF,SMB,HML,RMW,CMA}];
fivefmodel["ParameterTable"]
Grid[Transpose[{#,fivefmodel[#]}&[{"AdjustedRSquared","AIC","BIC","RSquared","DurbinWatsonD"}]],Alignment->Left]

({{"", "Estimate", "Standard Error", "t\[Hyphen]Statistic", "P\[Hyphen]Value"}, {1, -0.19710854963433844`, 0.02765642613468032`, -7.127043410253586`, 1.621093496197853`*^-10}, {MRRF, 1.001846003352563`, 0.007727629908873208`, 129.6446666269821`, 3.146586151830411`*^-113}, {SMB, -0.1489181817788126`, 0.013171139277532743`, -11.306400960533189`, 1.3869976062404612`*^-19}, {HML, -0.0023152509478426325`, 0.016017997855081685`, -0.14454059544702227`, 0.8853645101836898`}, {RMW, 0.039117475652684294`, 0.020008173742889636`, 1.9550747687097425`, 0.053365803377933285`}, {CMA, 0.0007045771654771187`, 0.023835504390894855`, 0.029559985554418`, 0.9764768929444819`}})

({{"AdjustedRSquared", 0.994583135725759`}, {"AIC", 29.151267595948894`}, {"BIC", 47.795341254733366`}, {"RSquared", 0.9948410816435799`}, {"DurbinWatsonD", 2.3922626714405895`}})

6. Stock Portfolio Performance Measures

All kinds of performance measures can be computed.

computePortfolioPerformanceTable[{"OTCFX","NAESX","ANWPX"},"SPY",0.0016,
{1995,01,01},{2019,03,30},"Month"]

7. Interactive Graphics and Technical Analysis of Stock Prices

Pattern Recogination.

peakBottomAnalysis["QQQ","Close",{{2014,10,31},{2019,10,28}}]

8. Bonds and Derivatives

FinancialBond function that can be used to used to find bond value, yield, duration, convexity and other related to bond measures.

FinancialDerivative can compute the values and partial derivatives for many common types of financial derivative contracts. We can also use Manipulate and FinancialDerivative functions to analyze the determinants of call/put options.

manipulateCall[50,50,0.02,0.5,1,0.05]

Binomial Trees Formulas for pricing equity options with no dividends

Mathematica does not have explicit function to compute the price of call and put using Binomial function. However, I have created the two functions that can be used to price the European Call and Put options.

binomialcallprice[50,45,0.4,0.1,5,500]
binomialputprice[50,45,0.4,0.1,5,500]

computeOptionParameters["BA",320,{2019,12,28},0.0187,"European"]

9. Linear Programming and Applications

minimize 102.36 (Subscript[x, 1]) +110.83  (Subscript[x, 2]) +96.94(Subscript[x, 3])+114.65(Subscript[x, 4])+96.63(Subscript[x, 5])
subject to
2.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 100
2.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 200
2.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 100
2.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 200
102.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 800
105  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 1200
103(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 400
104(Subscript[x, 4])+103.5(Subscript[x, 5])≥ 1000
0≤(Subscript[x, 1]), ...(Subscript[x, 5])

We can solve the problem using FindMinimum function as follows.

FindMinimum[{102.36 (Subscript[x, 1]) +110.83  (Subscript[x, 2]) +96.94(Subscript[x, 3])+114.65(Subscript[x, 4])+96.63(Subscript[x, 5]),
2.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 100 
&& 2.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 200
&& 2.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 100 
&& 2.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 200 
&&102.5 (Subscript[x, 1]) +5  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 800 
&& 105  (Subscript[x, 2]) +3(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 1200 
&& 103(Subscript[x, 3])+4(Subscript[x, 4])+3.5(Subscript[x, 5])≥ 400 
&& 104(Subscript[x, 4])+103.5(Subscript[x, 5])≥ 1000 
&& (Subscript[x, 1])≥ 0&& (Subscript[x, 2])≥ 0
&& (Subscript[x, 3])≥ 0&& (Subscript[x, 4])≥ 0
&& (Subscript[x, 5])≥ 0},{(Subscript[x, 1]), (Subscript[x, 2]), (Subscript[x, 3]), (Subscript[x, 4]), (Subscript[x, 5])},Method->"LinearProgramming"]

c={102.36,110.83,96.94,114.65,96.63};
m={{2.5,5,3,4,3.5},
{2.5,5,3,4,3.5},
{2.5,5,3,4,3.5},
{2.5,5,3,4,3.5},
{102.5,5,3,4,3.5},
{0,105,3,4,3.5},
{0,0,103,4,3.5},
{0,0,0,104,103.5}};
b={{100,1},{200,1},{100,1},{200,1},
{800,1},{1200,1},{400,1},{1000,1}};
bounds={{0,Infinity},{0,Infinity},
{0,Infinity},{0,Infinity},{0,Infinity}};
sol=LinearProgramming[c,m,b,bounds];
{c.sol,sol}

10. Mean-Variance Optimization under Uncertainty

Optimization techniques with data uncertainty.

ret=getReturnsData[{"^GSPC","^NDX"},{1982,01,01},{2019,04,30},"Month"];
sratios=robustTengencyPortfolios[ret,0.02/12,2000,10000];
visualHistogram[sratios]

11. Mean-CVaR Optimization

CVaR optimization does not depend on any distributional assumptions of returns but it works for normal distribution as well.

ret=getReturnsData[{"SPY","DIA","QQQ"},{2000,5,1},{2019,5,30},"Month"];
mCVaROptimization[ret,0.0052,0.95]

12. Simulation and Bootstrapping

RandomVariate is a very powerful function to obtained data from built-in statistical distributions including continuous/discrete distributions, univariate/multivariate distributions, parametric/derived distributions and distributions defined by data.

Performing a bootstrap analysis in Mathematica is very straight forward using RandomChoice or RandomSample functions with or without replacement.

ret=getReturnsData[{"^GSPC", "^NDX"}, {1982, 01, 01}, {2019, 04, 30}, "Week"];
cvars=Table[bootstrapcVaR[ret,50],10000];

{TableForm[basicStats[cvars]],visualHistogram[cvars]}

13. Introductory Time Series Analysis and Forecasting

TimeSeriesModelFit[tsdata] fits automatically selected parametric model to a time series. You can customize the model fit specification by changing its options. Currently supported models are AR, MA, ARMA, ARIMA, SARMA, SARIMA, ARCH and GARCH models. Mathematica also has a variety of built in measures to access the goodness of the model fit. AIC, BIC, AICc or SBC can be used to measure goodness of the fitted model and AFCPlot, PFCPlot or LjungBoxPlot can be used to assess the whiteness of the model residuals.

One of the primary objectives of building a time series model is to be able to forecast the values of that series at future dates. We can use TimeSeriesForecast[tsmodel,k] to have k-step-ahead forecast using the time series model. TimeSeriesForecast supports of the three methods, AR, Covariance and Kalman.

std={1990,01,01}; 
ed=Today;
conn=ServiceConnect["FederalReserveEconomicData"];
tsd=TimeSeriesWindow[conn["SeriesData","ID"->{"POILWTIUSDM"}],{std,ed}];

AutocorrelationTest[tsd,Automatic,"HypothesisTestData"]
["TestDataTable",All]

infoc={"AIC","AICc","BIC","SBC"};
TimeSeriesModelFit[tsd,Method->{Automatic,"SelectionCriterion"->#}]
["CandidateSelectionTable"]&/@infoc

tsm/@{"ACFPlot","PACFPlot","LjungBoxPlot"}

Yield Curve and Recession

14. AI and Machine Learning

Big data and big data analytics are becoming an integral part in all areas of finance as the availability of large amounts of financial data are becoming available through programmatic APIs.

Artificial intelligence in general and machine learning and deep learning in particular is a very technical field and needs higher level of computer programming and mathematical knowledge.

The Wolfram Language in general and Mathematica in particular could be well suited to address the challenges we face.

15. Conclusions

All the codes and functions used here are available for download at   http://www2.humboldt.edu/rkadhikari/about-me-and-my-research

While there are wide range of software available for modelling and analysis of financial data, Mathematica I think is the best in its kind because of its rich set of built in functions especially designed for analysis of financial data, both for exploratory data analysis and fitting statistical models.

Our focus has been to show uses of readily available built in functions and some of the functions we have written. The functions we have provided are just a few examples. Mathematica can do much more that what we have shown in here.
Interested readers can start exploring Mathematica using its extensive documentation.