projects (upcoming) - university of georgiacobweb.cs.uga.edu/~maria/classes/0-4646-summer... · –...
TRANSCRIPT
MachineLearningforTradingSoftwarePlatform
Introduction&Installation
Projects(upcoming)
• AssessPortfolio• AssessLearners&DefeatLearners• MarketSimulator
TowardsSharpeRatioIntuition
• Considersourreturninthecontextofrisk
• Riskisvolatile(standarddeviation)
• Adjustourreturninreturnfortherisk
• Volatility– Measuredbystandarddeviation
SharpeRatio
• Considersourreturninthecontextofrisk
• Riskisvolatile(standarddeviation)
• Adjustourreturninreturnfortherisk
• Volatility– Measuredbystandarddeviation
1
2
3
SharpeRatio
1. HigherReturnsisBetter2. LessVolatility/LessRisk
isBetter3. NotEnoughInformation
– Returns:ABC>XYZ– VolatilityABC>XYZ– ABCishigherreturns,
butmorerisk
1
2
3
SharpeRatio• Adjuststhe
– returnforrisk• Aquantitativewaytoassessaportfolio
– 1.ABCisbetterbecauseithasthesamevolatilitybuthigherreturns
– 2.samereturnsbutXYZhaslowerrisksoXYZisbetter– 3.AquantitysuchastheSharpeRatiomaygiveyouanumbertodeterminewhichisbetter
• Sharperatioalsoconsiders(comparative)– Riskfreerateofreturns
• ExampleBankaccountortreasurenote– Latelyriskfreereturnis0,bankinterestrateis0,orcloseto0– Caveat:WhencomputingSharpeRationeedtobecarefuloftheriskfreereturnsrate:
• Annual,weekly,daily
Intuition:WhichFormulaisBest?
ConsiderParameterstoincludeinformula:• Rp:PortfolioReturn• Rf:RiskFreeRateofReturn• σp :StandardDeviationofPortfolioReturna) Rp–Rf+σp
b) Rf/Rf-σp
c) (Rp–Rf)/σp
GeneralFormoftheSharpeRatio
HeuristicsSharpeRatio
• SharpeRatioAnswers:Istheportfolioreturnduetointelligentinvestmentdecisionsortheresultofexcessiverisktakenbytheinvestor?
• Thegreateraportfolio’sSharperatio:
• Thebetteritsrisk-adjustedperformancehasbeen.
• AnegativeSharperatioindicatesthatarisk-lessasset(riskfree)wouldperformbetterthantheportfolio(return)beinganalyzed.”
ComputingSharpeRatio
• Expectedreturn:Canusemean()ofdailyreturns(accessibleviayahoofinance).
• StD()ofdailyreturns.• StD()oftheReturnoftheRiskFreeRate
– Standarddeviationofaconstantis0(canremove).• Whatistheriskfreerate?
– LIBOR(LondonInterBankOfferRate)– InterestRate:3monthsTreasuryBill(Standard)– 0%!ShortCut.– Ifyouusedailyreturns,thentheriskfreerateneedstobeatthesamesamplingrate:
• Soifyouarereferencinganannualratethenyouwillneedtoconvertittoadailyriskfreerate.
RiskFreeRate
• IfyouhaveannualrateandwantEffectiveDailyRatecompoundeddaily.
• Caveat:Compoundinterestisnotlinearwithtime.
Example:2.5%AnnualReturn-Goingtoeffectivedailyreturn–242tradingdaysinayear.
=POWER(1+0.025,1/242)-1
€
1+ Annualized ReturnNth−1
1+0.025242 −1
• SharpeRatioitselfisanannualmeasure,soifwearesamplingatadifferentratee.g.daily,needanadjustmentfactortoconvertittothecorrectperiod– SRannualized=k*SR
SampleRate K(converttoannual)
Daily
Weekly
Monthly
SR=
ComputingSRSummary
• 2thingstoconsiderwhencomputingSharpeRatio:– 1)ConvertRiskFreeRatetosameperiodasexpectedreturnperiod.
– 2)ConvertSRtoannualSR.(usingadjustmentfactork).
Quiz:WhatistheSharpeRatio?• 60DaysofData• BPS–Basispointsaretenthsofpercentages.• AverageDailyReturn=10bps=0.001• DailyRiskFreeRate=2bps=0.0002• StandardDeviationDailyReturn=10bps=0.001
SR=SQRT(Period)*mean(Rportfolio-RRiskFree)--------------------------------Std(DailyReturn)SR=SQRT(Period)*(10-2)-------10
Quiz:WhatistheSharpeRatio?• 60DaysofData• BPS–Basispointsaretenthsofpercentages.• AverageDailyReturn=10bps=0.001• DailyRiskFreeRate=2bps=0.0002• StandardDeviationDailyReturn=10bps=0.001
SR=SQRT(Period)*mean(Rportfolio-RRiskFree)--------------------------------Std(DailyReturn)SR=SQRT(Period)*(10-2)-------10
ProjectDemo
• Computeport_valandstatistics…
GettheDailyTotalValueofthePortfolio• Step1:PricesDataFrameindexbydates
– pricesisaframe.• Step2:NormalizebyFirstRow
– normed=prices/prices[0]• Step3:Multiplybyallocation(avector)
– allocated=normed*allocs• Step4:Positionvalues=wortheachday
– pos_vals=allocated*start_val• Step5:DailyTotalValueofPortfolio
– port_vals=pos_vals.sum(axis=1)
prices normed allocated pos_vals port_vals
Given:
start_val = $1,000,000start_date = 2011-01-01end_date = 2011-12-31symbols =[‘SPY’,’XOM’, ’GOOG’, ‘GLD’]allocs = [0.4,0.4,0.1,0.1]
prices/prices[0] normed/allocs
allocated
*start_val
pos_vals.sum(axis=1
)
port_vals=get_portfolio_value(prices,allocs,start_val)
ComputeStatistics• AverageDailyReturn
– Intuition:• Today/Yesterday-1• Remove1strowsincenowitisall0s
– ExcelacellG10=E10/E9-1• E10=current’srowadjustedclose• E09=previousday’sadjustedclose
– Pandas:• daily_rets=port_val/port_val.shift(X)-1• #whatisX?
• Cumulativefrombeginningtoend– >=periodthandailyreturn.
• AverageandStandardDeviationoftheDailyReturn.mean(),.std()
• SharpeRatio(Annual)
Given:1) port_vals: portfolio
daily return values 2) rfr: risk free rate3) sample_frequency: Sample
Frequency – Example, daily 252 in a year.
cr,adr,sddr,sr=get_portfolio_stats(port_val,risk_free_rate,sample_frequency)
Optimization
• Whatisanoptimizer?1. Findminimumvaluesoffunctions
• Example:f(x)=x2+x3+…+1
2. Findparametersfromdata• Enables:buildingparameterizedmodelsbasedondata• How:polynomialfittodata
3. Find(refine)allocationofstocksinaportfolio• Whatpercentageshouldbeallocatedtoeachstocktomaximizetheportfolioreturn(partoftheproject).
FindMinimaofaFunction
• Howtouseanoptimizer:1) Provideafunctiontominimize:
• Example:f(x)=x2+0.5
2) Provideaninitialguess:• Example=5(generatedbyarandomizer)
3) Calltheoptimizerwiththeparametersabove
Example:Minimization1) Functionprovided:
– f(x)=(x–1.5)2+0.52) Provideaninitialguess:3.03) CallOptimizerwithparameters
definedabove.– Onemethod:
• Gradientdescendtonarrowinonthesolution.
• Experimentwithothermethods.
• Next:LookatCode(provided):– pdf-code-finance/001-minimizer.py
http://www.wolframalpha.com/min(x-1.5)^2 +0.5)
f(x):Y = (X - 1.5)**2 + 0.5 # parabola atX = 1.5 Y = 0.5min_result=spo.minimize(f,Xguess,method='SLSQP',options={'disp':True})
Exercise:Minimization1) Functionprovided:
– f(x)=(x1)2+(x2)22) Provideaninitialguess:[1,1]3) CallOptimizerwithparameters
definedabove.– Onemethod:
• Gradientdescendtonarrowinonthesolution.
• Experimentwithothermethods.
• CodeSnippets:
http://www.wolframalpha.com/min(X1^2 + X2^2)
x1,x2=paramsZ=x1**2+x2**2Xguess=[1,1]min_result=spo.minimize(f,Xguess,method='SLSQP',options={'disp':True})
optimize1D2.py
Exercise:Minimization1) Functionprovided:
– f(x)=(x1)2+(x2)22) Provideaninitialguess:[1,1]3) CallOptimizerwithparameters
definedabove.– Onemethod:
• Gradientdescendtonarrowinonthesolution.
• Experimentwithothermethods.
• CodeSnippets:
http://www.wolframalpha.com/min(X1^2 + X2^2)
x1,x2=paramsZ=x1**2+x2**2Xguess=[1,1]min_result=spo.minimize(f,Xguess,method='SLSQP',options={'disp':True})
optimize1D2.py
Exercise
#min (X1+0.5)^2 + (X2-0.25)^2+sin(3X1)+sin(5X2)
Whichfunctionsarechallengingtosolve(fortheminimizer)?
• A
• B
• C
• D
Whichfunctionsarechallengingtosolve(fortheminimizer)?
• A–flatareasdon’thaveagradient.
• B-convexproblems
• C–severalglobalminima
• D–discontinuity(andaflatarea).
• Convexfunctionsareguaranteedtofindaminima(onlyone).
• But–otheralgorithmsforspecificissues,youcanexperimentwithdifferentonesonyourown.
ConvexProblems
• Convexfunction• Wikipedia:"...areal-valuedfunctionf(x)definedonanintervaliscalledconvexifthelinesegmentbetweenanytwopointsonthegraphofthefunctionliesabovethegraph..."
Parameterizedmodelsfromdata• Example:f(x)=mx+b
– c1x+c0– c3x3+c2x2+c1x+c0
• Goal1:Findparametersofthelinec0,c1,wherec0isthey-intercept,andc1isslopethatbestfitsthedata
• Goal2:Howdowereframetheproblemsothatitmakessensetotheminimizer?
• Whatshouldwebeminimizing?
humidity
rain
003-parameters-data.py
WhichMetricsaregoodforfittingdata?
• Σ ei• Σ abs(ei)• Σ ei2
WhichMetricsaregoodforfittingdata?
• Σ eiü Σ abs(ei)ü Σ ei2
BothareOKSquareErrorisastandardmethod
Steps:
• Expressafunction‘error()’thatreturnsanerrormeasurebetween:– Agivenline,and– DataPoints.
• deferror(data,line)
003-parameters-data.py
(data− line)2∑
(Ydata−Yline)2∑
RunningtheCode
• Horizontallineistheinitialguess.• Minimizestheerrorbetweenthelineanddata.
BonusExercise
• Howwouldyoudocurvefitting?– Fitdatatoacurve?
HowtoOptimizeaPortfolio?(futureactivity)
• Exercise/Activity:Maximizeperformanceofaportfolio
• Criteria(maximization)?Whichiseasiest?– Cumulativereturn– VolatileReturn– RiskAdjustedReturn(SharpeRatio)
http://quantsoftware.gatech.edu/Optimize_something
HowtoOptimizeaPortfolio?(futureactivity)
• Exercise/Activity:Maximizeperformanceofaportfolio• Problem:Needtofind‘coefficients’ofstocksinaportfolio
(theallocationofeachstockinportfolio]– [‘GOOG’,‘GLD’,’APPL’,’XOM’]– [0.25,0.25,0.25,0.25]=equal– [0.0,0.0,0.0,1.0]=justAPPL?– Whichisbetter?
• Criteria(maximization)?Whichiseasiest?– Cumulativereturn(trivialjustthemaximumreturn)– VolatileReturn– RiskAdjustedReturn(SharpeRatio)
• OptimizingforVolatilityorSRyouhavetoevaluatevariouscombinationsofstocksandcheckresult.
http://quantsoftware.gatech.edu/Optimize_something
FramingtheProblem(andRecap)(similartopreviousexamples)
• Inordertouseanoptimizerthatminimizesweneedtodothefollowing:– Provideafunctiontominimizef(x)– ProvideaninitialguessforX– Calltheoptimizer
• NEW:– Constraint:allallocationsneedtosumto1.0– WhataboutSharpeRatio
• Arewelookingforaminimaormaxima?
• WewanttomaximizeSR,higherisbetter.• Sincewehaveaminimizerweshouldmakethemaximaaminima
ActivityHints
• f(x)=SR*(-1)• Provideaninitialguess• LimitsonvaluesforX• Constraints–allstocksaddsto1.
MoreDetailed(Hints)• F(allocs)WewanttooptimizeforSharperatio,
– Wewanttooptimizefor-1*SRto‘maximizeit’– Functioninoptimizer
• get_portfolio_value()• SR=get_porftolio_stats()• Return–SR
• Imaginethatthearethepercentageofeachofthefundsallocated• constraints=({'type':'eq','fun':lambdaallocs:1.0-
np.sum(allocs)})#allocationsmustsumto1(sameas1-sum=0)• result=spo.minimize(
f,initial_allocs,method='SLSQP',bounds=bounds,constraints=constraints)
Constraints:• Xaretheallocationswearelookingor
– Needtoadduptoamaximumof1.– Limitandconstraints
• Wewanttheoptimizertotrydifferentallocationstodiscoverbestsetofallocations
• SharpeRatio?Volatility?
Example:EqualAllocation
• .25GOOG• .25AAPL• .25GLD• .25XOM
Example:SharpeRatioOptimization
• .00GOOG• .40AAPL• .60GLD• .00XOM
Challenge:Bonus• Pickasetof4stocks• Pickaperiodtotestover.• Optimize
– SR– Volatility
• Dotheydiffer?– Discuss.
• Analyzeperformanceofresultingportfolio– Howdoesitperformcomparedtothemarket.– Usingtheseallocationstestitoveradifferentperiod
• Howdoesitperform?