test_window.py 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073
  1. from collections import OrderedDict
  2. from datetime import datetime, timedelta
  3. from itertools import product
  4. import warnings
  5. from warnings import catch_warnings
  6. import numpy as np
  7. from numpy.random import randn
  8. import pytest
  9. from pandas.compat import range, zip
  10. from pandas.errors import UnsupportedFunctionCall
  11. import pandas.util._test_decorators as td
  12. import pandas as pd
  13. from pandas import (
  14. DataFrame, Index, Series, Timestamp, bdate_range, concat, isna, notna)
  15. from pandas.core.base import SpecificationError
  16. from pandas.core.sorting import safe_sort
  17. import pandas.core.window as rwindow
  18. import pandas.util.testing as tm
  19. import pandas.tseries.offsets as offsets
  20. N, K = 100, 10
  21. def assert_equal(left, right):
  22. if isinstance(left, Series):
  23. tm.assert_series_equal(left, right)
  24. else:
  25. tm.assert_frame_equal(left, right)
  26. @pytest.fixture(params=[True, False])
  27. def raw(request):
  28. return request.param
  29. @pytest.fixture(params=['triang', 'blackman', 'hamming', 'bartlett', 'bohman',
  30. 'blackmanharris', 'nuttall', 'barthann'])
  31. def win_types(request):
  32. return request.param
  33. @pytest.fixture(params=['kaiser', 'gaussian', 'general_gaussian'])
  34. def win_types_special(request):
  35. return request.param
  36. class Base(object):
  37. _nan_locs = np.arange(20, 40)
  38. _inf_locs = np.array([])
  39. def _create_data(self):
  40. arr = randn(N)
  41. arr[self._nan_locs] = np.NaN
  42. self.arr = arr
  43. self.rng = bdate_range(datetime(2009, 1, 1), periods=N)
  44. self.series = Series(arr.copy(), index=self.rng)
  45. self.frame = DataFrame(randn(N, K), index=self.rng,
  46. columns=np.arange(K))
  47. class TestApi(Base):
  48. def setup_method(self, method):
  49. self._create_data()
  50. def test_getitem(self):
  51. r = self.frame.rolling(window=5)
  52. tm.assert_index_equal(r._selected_obj.columns, self.frame.columns)
  53. r = self.frame.rolling(window=5)[1]
  54. assert r._selected_obj.name == self.frame.columns[1]
  55. # technically this is allowed
  56. r = self.frame.rolling(window=5)[1, 3]
  57. tm.assert_index_equal(r._selected_obj.columns,
  58. self.frame.columns[[1, 3]])
  59. r = self.frame.rolling(window=5)[[1, 3]]
  60. tm.assert_index_equal(r._selected_obj.columns,
  61. self.frame.columns[[1, 3]])
  62. def test_select_bad_cols(self):
  63. df = DataFrame([[1, 2]], columns=['A', 'B'])
  64. g = df.rolling(window=5)
  65. pytest.raises(KeyError, g.__getitem__, ['C']) # g[['C']]
  66. pytest.raises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']]
  67. with pytest.raises(KeyError, match='^[^A]+$'):
  68. # A should not be referenced as a bad column...
  69. # will have to rethink regex if you change message!
  70. g[['A', 'C']]
  71. def test_attribute_access(self):
  72. df = DataFrame([[1, 2]], columns=['A', 'B'])
  73. r = df.rolling(window=5)
  74. tm.assert_series_equal(r.A.sum(), r['A'].sum())
  75. pytest.raises(AttributeError, lambda: r.F)
  76. def tests_skip_nuisance(self):
  77. df = DataFrame({'A': range(5), 'B': range(5, 10), 'C': 'foo'})
  78. r = df.rolling(window=3)
  79. result = r[['A', 'B']].sum()
  80. expected = DataFrame({'A': [np.nan, np.nan, 3, 6, 9],
  81. 'B': [np.nan, np.nan, 18, 21, 24]},
  82. columns=list('AB'))
  83. tm.assert_frame_equal(result, expected)
  84. def test_skip_sum_object_raises(self):
  85. df = DataFrame({'A': range(5), 'B': range(5, 10), 'C': 'foo'})
  86. r = df.rolling(window=3)
  87. with pytest.raises(TypeError, match='cannot handle this type'):
  88. r.sum()
  89. def test_agg(self):
  90. df = DataFrame({'A': range(5), 'B': range(0, 10, 2)})
  91. r = df.rolling(window=3)
  92. a_mean = r['A'].mean()
  93. a_std = r['A'].std()
  94. a_sum = r['A'].sum()
  95. b_mean = r['B'].mean()
  96. b_std = r['B'].std()
  97. b_sum = r['B'].sum()
  98. result = r.aggregate([np.mean, np.std])
  99. expected = concat([a_mean, a_std, b_mean, b_std], axis=1)
  100. expected.columns = pd.MultiIndex.from_product([['A', 'B'], ['mean',
  101. 'std']])
  102. tm.assert_frame_equal(result, expected)
  103. result = r.aggregate({'A': np.mean, 'B': np.std})
  104. expected = concat([a_mean, b_std], axis=1)
  105. tm.assert_frame_equal(result, expected, check_like=True)
  106. result = r.aggregate({'A': ['mean', 'std']})
  107. expected = concat([a_mean, a_std], axis=1)
  108. expected.columns = pd.MultiIndex.from_tuples([('A', 'mean'), ('A',
  109. 'std')])
  110. tm.assert_frame_equal(result, expected)
  111. result = r['A'].aggregate(['mean', 'sum'])
  112. expected = concat([a_mean, a_sum], axis=1)
  113. expected.columns = ['mean', 'sum']
  114. tm.assert_frame_equal(result, expected)
  115. with catch_warnings(record=True):
  116. # using a dict with renaming
  117. warnings.simplefilter("ignore", FutureWarning)
  118. result = r.aggregate({'A': {'mean': 'mean', 'sum': 'sum'}})
  119. expected = concat([a_mean, a_sum], axis=1)
  120. expected.columns = pd.MultiIndex.from_tuples([('A', 'mean'),
  121. ('A', 'sum')])
  122. tm.assert_frame_equal(result, expected, check_like=True)
  123. with catch_warnings(record=True):
  124. warnings.simplefilter("ignore", FutureWarning)
  125. result = r.aggregate({'A': {'mean': 'mean',
  126. 'sum': 'sum'},
  127. 'B': {'mean2': 'mean',
  128. 'sum2': 'sum'}})
  129. expected = concat([a_mean, a_sum, b_mean, b_sum], axis=1)
  130. exp_cols = [('A', 'mean'), ('A', 'sum'), ('B', 'mean2'), ('B', 'sum2')]
  131. expected.columns = pd.MultiIndex.from_tuples(exp_cols)
  132. tm.assert_frame_equal(result, expected, check_like=True)
  133. result = r.aggregate({'A': ['mean', 'std'], 'B': ['mean', 'std']})
  134. expected = concat([a_mean, a_std, b_mean, b_std], axis=1)
  135. exp_cols = [('A', 'mean'), ('A', 'std'), ('B', 'mean'), ('B', 'std')]
  136. expected.columns = pd.MultiIndex.from_tuples(exp_cols)
  137. tm.assert_frame_equal(result, expected, check_like=True)
  138. def test_agg_apply(self, raw):
  139. # passed lambda
  140. df = DataFrame({'A': range(5), 'B': range(0, 10, 2)})
  141. r = df.rolling(window=3)
  142. a_sum = r['A'].sum()
  143. result = r.agg({'A': np.sum, 'B': lambda x: np.std(x, ddof=1)})
  144. rcustom = r['B'].apply(lambda x: np.std(x, ddof=1), raw=raw)
  145. expected = concat([a_sum, rcustom], axis=1)
  146. tm.assert_frame_equal(result, expected, check_like=True)
  147. def test_agg_consistency(self):
  148. df = DataFrame({'A': range(5), 'B': range(0, 10, 2)})
  149. r = df.rolling(window=3)
  150. result = r.agg([np.sum, np.mean]).columns
  151. expected = pd.MultiIndex.from_product([list('AB'), ['sum', 'mean']])
  152. tm.assert_index_equal(result, expected)
  153. result = r['A'].agg([np.sum, np.mean]).columns
  154. expected = Index(['sum', 'mean'])
  155. tm.assert_index_equal(result, expected)
  156. result = r.agg({'A': [np.sum, np.mean]}).columns
  157. expected = pd.MultiIndex.from_tuples([('A', 'sum'), ('A', 'mean')])
  158. tm.assert_index_equal(result, expected)
  159. def test_agg_nested_dicts(self):
  160. # API change for disallowing these types of nested dicts
  161. df = DataFrame({'A': range(5), 'B': range(0, 10, 2)})
  162. r = df.rolling(window=3)
  163. def f():
  164. r.aggregate({'r1': {'A': ['mean', 'sum']},
  165. 'r2': {'B': ['mean', 'sum']}})
  166. pytest.raises(SpecificationError, f)
  167. expected = concat([r['A'].mean(), r['A'].std(),
  168. r['B'].mean(), r['B'].std()], axis=1)
  169. expected.columns = pd.MultiIndex.from_tuples([('ra', 'mean'), (
  170. 'ra', 'std'), ('rb', 'mean'), ('rb', 'std')])
  171. with catch_warnings(record=True):
  172. warnings.simplefilter("ignore", FutureWarning)
  173. result = r[['A', 'B']].agg({'A': {'ra': ['mean', 'std']},
  174. 'B': {'rb': ['mean', 'std']}})
  175. tm.assert_frame_equal(result, expected, check_like=True)
  176. with catch_warnings(record=True):
  177. warnings.simplefilter("ignore", FutureWarning)
  178. result = r.agg({'A': {'ra': ['mean', 'std']},
  179. 'B': {'rb': ['mean', 'std']}})
  180. expected.columns = pd.MultiIndex.from_tuples([('A', 'ra', 'mean'), (
  181. 'A', 'ra', 'std'), ('B', 'rb', 'mean'), ('B', 'rb', 'std')])
  182. tm.assert_frame_equal(result, expected, check_like=True)
  183. def test_count_nonnumeric_types(self):
  184. # GH12541
  185. cols = ['int', 'float', 'string', 'datetime', 'timedelta', 'periods',
  186. 'fl_inf', 'fl_nan', 'str_nan', 'dt_nat', 'periods_nat']
  187. df = DataFrame(
  188. {'int': [1, 2, 3],
  189. 'float': [4., 5., 6.],
  190. 'string': list('abc'),
  191. 'datetime': pd.date_range('20170101', periods=3),
  192. 'timedelta': pd.timedelta_range('1 s', periods=3, freq='s'),
  193. 'periods': [pd.Period('2012-01'), pd.Period('2012-02'),
  194. pd.Period('2012-03')],
  195. 'fl_inf': [1., 2., np.Inf],
  196. 'fl_nan': [1., 2., np.NaN],
  197. 'str_nan': ['aa', 'bb', np.NaN],
  198. 'dt_nat': [Timestamp('20170101'), Timestamp('20170203'),
  199. Timestamp(None)],
  200. 'periods_nat': [pd.Period('2012-01'), pd.Period('2012-02'),
  201. pd.Period(None)]},
  202. columns=cols)
  203. expected = DataFrame(
  204. {'int': [1., 2., 2.],
  205. 'float': [1., 2., 2.],
  206. 'string': [1., 2., 2.],
  207. 'datetime': [1., 2., 2.],
  208. 'timedelta': [1., 2., 2.],
  209. 'periods': [1., 2., 2.],
  210. 'fl_inf': [1., 2., 2.],
  211. 'fl_nan': [1., 2., 1.],
  212. 'str_nan': [1., 2., 1.],
  213. 'dt_nat': [1., 2., 1.],
  214. 'periods_nat': [1., 2., 1.]},
  215. columns=cols)
  216. result = df.rolling(window=2).count()
  217. tm.assert_frame_equal(result, expected)
  218. result = df.rolling(1).count()
  219. expected = df.notna().astype(float)
  220. tm.assert_frame_equal(result, expected)
  221. @td.skip_if_no_scipy
  222. @pytest.mark.filterwarnings("ignore:can't resolve:ImportWarning")
  223. def test_window_with_args(self):
  224. # make sure that we are aggregating window functions correctly with arg
  225. r = Series(np.random.randn(100)).rolling(window=10, min_periods=1,
  226. win_type='gaussian')
  227. expected = concat([r.mean(std=10), r.mean(std=.01)], axis=1)
  228. expected.columns = ['<lambda>', '<lambda>']
  229. result = r.aggregate([lambda x: x.mean(std=10),
  230. lambda x: x.mean(std=.01)])
  231. tm.assert_frame_equal(result, expected)
  232. def a(x):
  233. return x.mean(std=10)
  234. def b(x):
  235. return x.mean(std=0.01)
  236. expected = concat([r.mean(std=10), r.mean(std=.01)], axis=1)
  237. expected.columns = ['a', 'b']
  238. result = r.aggregate([a, b])
  239. tm.assert_frame_equal(result, expected)
  240. def test_preserve_metadata(self):
  241. # GH 10565
  242. s = Series(np.arange(100), name='foo')
  243. s2 = s.rolling(30).sum()
  244. s3 = s.rolling(20).sum()
  245. assert s2.name == 'foo'
  246. assert s3.name == 'foo'
  247. @pytest.mark.parametrize("func,window_size,expected_vals", [
  248. ('rolling', 2, [[np.nan, np.nan, np.nan, np.nan],
  249. [15., 20., 25., 20.],
  250. [25., 30., 35., 30.],
  251. [np.nan, np.nan, np.nan, np.nan],
  252. [20., 30., 35., 30.],
  253. [35., 40., 60., 40.],
  254. [60., 80., 85., 80]]),
  255. ('expanding', None, [[10., 10., 20., 20.],
  256. [15., 20., 25., 20.],
  257. [20., 30., 30., 20.],
  258. [10., 10., 30., 30.],
  259. [20., 30., 35., 30.],
  260. [26.666667, 40., 50., 30.],
  261. [40., 80., 60., 30.]])])
  262. def test_multiple_agg_funcs(self, func, window_size, expected_vals):
  263. # GH 15072
  264. df = pd.DataFrame([
  265. ['A', 10, 20],
  266. ['A', 20, 30],
  267. ['A', 30, 40],
  268. ['B', 10, 30],
  269. ['B', 30, 40],
  270. ['B', 40, 80],
  271. ['B', 80, 90]], columns=['stock', 'low', 'high'])
  272. f = getattr(df.groupby('stock'), func)
  273. if window_size:
  274. window = f(window_size)
  275. else:
  276. window = f()
  277. index = pd.MultiIndex.from_tuples([
  278. ('A', 0), ('A', 1), ('A', 2),
  279. ('B', 3), ('B', 4), ('B', 5), ('B', 6)], names=['stock', None])
  280. columns = pd.MultiIndex.from_tuples([
  281. ('low', 'mean'), ('low', 'max'), ('high', 'mean'),
  282. ('high', 'min')])
  283. expected = pd.DataFrame(expected_vals, index=index, columns=columns)
  284. result = window.agg(OrderedDict((
  285. ('low', ['mean', 'max']),
  286. ('high', ['mean', 'min']),
  287. )))
  288. tm.assert_frame_equal(result, expected)
  289. @pytest.mark.filterwarnings("ignore:can't resolve package:ImportWarning")
  290. class TestWindow(Base):
  291. def setup_method(self, method):
  292. self._create_data()
  293. @td.skip_if_no_scipy
  294. @pytest.mark.parametrize(
  295. 'which', ['series', 'frame'])
  296. def test_constructor(self, which):
  297. # GH 12669
  298. o = getattr(self, which)
  299. c = o.rolling
  300. # valid
  301. c(win_type='boxcar', window=2, min_periods=1)
  302. c(win_type='boxcar', window=2, min_periods=1, center=True)
  303. c(win_type='boxcar', window=2, min_periods=1, center=False)
  304. # not valid
  305. for w in [2., 'foo', np.array([2])]:
  306. with pytest.raises(ValueError):
  307. c(win_type='boxcar', window=2, min_periods=w)
  308. with pytest.raises(ValueError):
  309. c(win_type='boxcar', window=2, min_periods=1, center=w)
  310. for wt in ['foobar', 1]:
  311. with pytest.raises(ValueError):
  312. c(win_type=wt, window=2)
  313. @td.skip_if_no_scipy
  314. @pytest.mark.parametrize(
  315. 'which', ['series', 'frame'])
  316. def test_constructor_with_win_type(self, which, win_types):
  317. # GH 12669
  318. o = getattr(self, which)
  319. c = o.rolling
  320. c(win_type=win_types, window=2)
  321. @pytest.mark.parametrize(
  322. 'method', ['sum', 'mean'])
  323. def test_numpy_compat(self, method):
  324. # see gh-12811
  325. w = rwindow.Window(Series([2, 4, 6]), window=[0, 2])
  326. msg = "numpy operations are not valid with window objects"
  327. with pytest.raises(UnsupportedFunctionCall, match=msg):
  328. getattr(w, method)(1, 2, 3)
  329. with pytest.raises(UnsupportedFunctionCall, match=msg):
  330. getattr(w, method)(dtype=np.float64)
  331. class TestRolling(Base):
  332. def setup_method(self, method):
  333. self._create_data()
  334. def test_doc_string(self):
  335. df = DataFrame({'B': [0, 1, 2, np.nan, 4]})
  336. df
  337. df.rolling(2).sum()
  338. df.rolling(2, min_periods=1).sum()
  339. @pytest.mark.parametrize(
  340. 'which', ['series', 'frame'])
  341. def test_constructor(self, which):
  342. # GH 12669
  343. o = getattr(self, which)
  344. c = o.rolling
  345. # valid
  346. c(window=2)
  347. c(window=2, min_periods=1)
  348. c(window=2, min_periods=1, center=True)
  349. c(window=2, min_periods=1, center=False)
  350. # GH 13383
  351. with pytest.raises(ValueError):
  352. c(0)
  353. c(-1)
  354. # not valid
  355. for w in [2., 'foo', np.array([2])]:
  356. with pytest.raises(ValueError):
  357. c(window=w)
  358. with pytest.raises(ValueError):
  359. c(window=2, min_periods=w)
  360. with pytest.raises(ValueError):
  361. c(window=2, min_periods=1, center=w)
  362. @td.skip_if_no_scipy
  363. @pytest.mark.parametrize(
  364. 'which', ['series', 'frame'])
  365. def test_constructor_with_win_type(self, which):
  366. # GH 13383
  367. o = getattr(self, which)
  368. c = o.rolling
  369. with pytest.raises(ValueError):
  370. c(-1, win_type='boxcar')
  371. @pytest.mark.parametrize(
  372. 'window', [timedelta(days=3), pd.Timedelta(days=3)])
  373. def test_constructor_with_timedelta_window(self, window):
  374. # GH 15440
  375. n = 10
  376. df = DataFrame({'value': np.arange(n)},
  377. index=pd.date_range('2015-12-24', periods=n, freq="D"))
  378. expected_data = np.append([0., 1.], np.arange(3., 27., 3))
  379. result = df.rolling(window=window).sum()
  380. expected = DataFrame({'value': expected_data},
  381. index=pd.date_range('2015-12-24', periods=n,
  382. freq="D"))
  383. tm.assert_frame_equal(result, expected)
  384. expected = df.rolling('3D').sum()
  385. tm.assert_frame_equal(result, expected)
  386. @pytest.mark.parametrize(
  387. 'window', [timedelta(days=3), pd.Timedelta(days=3), '3D'])
  388. def test_constructor_timedelta_window_and_minperiods(self, window, raw):
  389. # GH 15305
  390. n = 10
  391. df = DataFrame({'value': np.arange(n)},
  392. index=pd.date_range('2017-08-08', periods=n, freq="D"))
  393. expected = DataFrame(
  394. {'value': np.append([np.NaN, 1.], np.arange(3., 27., 3))},
  395. index=pd.date_range('2017-08-08', periods=n, freq="D"))
  396. result_roll_sum = df.rolling(window=window, min_periods=2).sum()
  397. result_roll_generic = df.rolling(window=window,
  398. min_periods=2).apply(sum, raw=raw)
  399. tm.assert_frame_equal(result_roll_sum, expected)
  400. tm.assert_frame_equal(result_roll_generic, expected)
  401. @pytest.mark.parametrize(
  402. 'method', ['std', 'mean', 'sum', 'max', 'min', 'var'])
  403. def test_numpy_compat(self, method):
  404. # see gh-12811
  405. r = rwindow.Rolling(Series([2, 4, 6]), window=2)
  406. msg = "numpy operations are not valid with window objects"
  407. with pytest.raises(UnsupportedFunctionCall, match=msg):
  408. getattr(r, method)(1, 2, 3)
  409. with pytest.raises(UnsupportedFunctionCall, match=msg):
  410. getattr(r, method)(dtype=np.float64)
  411. def test_closed(self):
  412. df = DataFrame({'A': [0, 1, 2, 3, 4]})
  413. # closed only allowed for datetimelike
  414. with pytest.raises(ValueError):
  415. df.rolling(window=3, closed='neither')
  416. @pytest.mark.parametrize("func", ['min', 'max'])
  417. def test_closed_one_entry(self, func):
  418. # GH24718
  419. ser = pd.Series(data=[2], index=pd.date_range('2000', periods=1))
  420. result = getattr(ser.rolling('10D', closed='left'), func)()
  421. tm.assert_series_equal(result, pd.Series([np.nan], index=ser.index))
  422. @pytest.mark.parametrize("func", ['min', 'max'])
  423. def test_closed_one_entry_groupby(self, func):
  424. # GH24718
  425. ser = pd.DataFrame(data={'A': [1, 1, 2], 'B': [3, 2, 1]},
  426. index=pd.date_range('2000', periods=3))
  427. result = getattr(
  428. ser.groupby('A', sort=False)['B'].rolling('10D', closed='left'),
  429. func)()
  430. exp_idx = pd.MultiIndex.from_arrays(arrays=[[1, 1, 2], ser.index],
  431. names=('A', None))
  432. expected = pd.Series(data=[np.nan, 3, np.nan], index=exp_idx, name='B')
  433. tm.assert_series_equal(result, expected)
  434. @pytest.mark.parametrize("input_dtype", ['int', 'float'])
  435. @pytest.mark.parametrize("func,closed,expected", [
  436. ('min', 'right', [0.0, 0, 0, 1, 2, 3, 4, 5, 6, 7]),
  437. ('min', 'both', [0.0, 0, 0, 0, 1, 2, 3, 4, 5, 6]),
  438. ('min', 'neither', [np.nan, 0, 0, 1, 2, 3, 4, 5, 6, 7]),
  439. ('min', 'left', [np.nan, 0, 0, 0, 1, 2, 3, 4, 5, 6]),
  440. ('max', 'right', [0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
  441. ('max', 'both', [0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
  442. ('max', 'neither', [np.nan, 0, 1, 2, 3, 4, 5, 6, 7, 8]),
  443. ('max', 'left', [np.nan, 0, 1, 2, 3, 4, 5, 6, 7, 8])
  444. ])
  445. def test_closed_min_max_datetime(self, input_dtype,
  446. func, closed,
  447. expected):
  448. # see gh-21704
  449. ser = pd.Series(data=np.arange(10).astype(input_dtype),
  450. index=pd.date_range('2000', periods=10))
  451. result = getattr(ser.rolling('3D', closed=closed), func)()
  452. expected = pd.Series(expected, index=ser.index)
  453. tm.assert_series_equal(result, expected)
  454. def test_closed_uneven(self):
  455. # see gh-21704
  456. ser = pd.Series(data=np.arange(10),
  457. index=pd.date_range('2000', periods=10))
  458. # uneven
  459. ser = ser.drop(index=ser.index[[1, 5]])
  460. result = ser.rolling('3D', closed='left').min()
  461. expected = pd.Series([np.nan, 0, 0, 2, 3, 4, 6, 6],
  462. index=ser.index)
  463. tm.assert_series_equal(result, expected)
  464. @pytest.mark.parametrize("func,closed,expected", [
  465. ('min', 'right', [np.nan, 0, 0, 1, 2, 3, 4, 5, np.nan, np.nan]),
  466. ('min', 'both', [np.nan, 0, 0, 0, 1, 2, 3, 4, 5, np.nan]),
  467. ('min', 'neither', [np.nan, np.nan, 0, 1, 2, 3, 4, 5, np.nan, np.nan]),
  468. ('min', 'left', [np.nan, np.nan, 0, 0, 1, 2, 3, 4, 5, np.nan]),
  469. ('max', 'right', [np.nan, 1, 2, 3, 4, 5, 6, 6, np.nan, np.nan]),
  470. ('max', 'both', [np.nan, 1, 2, 3, 4, 5, 6, 6, 6, np.nan]),
  471. ('max', 'neither', [np.nan, np.nan, 1, 2, 3, 4, 5, 6, np.nan, np.nan]),
  472. ('max', 'left', [np.nan, np.nan, 1, 2, 3, 4, 5, 6, 6, np.nan])
  473. ])
  474. def test_closed_min_max_minp(self, func, closed, expected):
  475. # see gh-21704
  476. ser = pd.Series(data=np.arange(10),
  477. index=pd.date_range('2000', periods=10))
  478. ser[ser.index[-3:]] = np.nan
  479. result = getattr(ser.rolling('3D', min_periods=2, closed=closed),
  480. func)()
  481. expected = pd.Series(expected, index=ser.index)
  482. tm.assert_series_equal(result, expected)
  483. @pytest.mark.parametrize('roller', ['1s', 1])
  484. def tests_empty_df_rolling(self, roller):
  485. # GH 15819 Verifies that datetime and integer rolling windows can be
  486. # applied to empty DataFrames
  487. expected = DataFrame()
  488. result = DataFrame().rolling(roller).sum()
  489. tm.assert_frame_equal(result, expected)
  490. # Verifies that datetime and integer rolling windows can be applied to
  491. # empty DataFrames with datetime index
  492. expected = DataFrame(index=pd.DatetimeIndex([]))
  493. result = DataFrame(index=pd.DatetimeIndex([])).rolling(roller).sum()
  494. tm.assert_frame_equal(result, expected)
  495. def test_missing_minp_zero(self):
  496. # https://github.com/pandas-dev/pandas/pull/18921
  497. # minp=0
  498. x = pd.Series([np.nan])
  499. result = x.rolling(1, min_periods=0).sum()
  500. expected = pd.Series([0.0])
  501. tm.assert_series_equal(result, expected)
  502. # minp=1
  503. result = x.rolling(1, min_periods=1).sum()
  504. expected = pd.Series([np.nan])
  505. tm.assert_series_equal(result, expected)
  506. def test_missing_minp_zero_variable(self):
  507. # https://github.com/pandas-dev/pandas/pull/18921
  508. x = pd.Series([np.nan] * 4,
  509. index=pd.DatetimeIndex(['2017-01-01', '2017-01-04',
  510. '2017-01-06', '2017-01-07']))
  511. result = x.rolling(pd.Timedelta("2d"), min_periods=0).sum()
  512. expected = pd.Series(0.0, index=x.index)
  513. tm.assert_series_equal(result, expected)
  514. def test_multi_index_names(self):
  515. # GH 16789, 16825
  516. cols = pd.MultiIndex.from_product([['A', 'B'], ['C', 'D', 'E']],
  517. names=['1', '2'])
  518. df = DataFrame(np.ones((10, 6)), columns=cols)
  519. result = df.rolling(3).cov()
  520. tm.assert_index_equal(result.columns, df.columns)
  521. assert result.index.names == [None, '1', '2']
  522. @pytest.mark.parametrize('klass', [pd.Series, pd.DataFrame])
  523. def test_iter_raises(self, klass):
  524. # https://github.com/pandas-dev/pandas/issues/11704
  525. # Iteration over a Window
  526. obj = klass([1, 2, 3, 4])
  527. with pytest.raises(NotImplementedError):
  528. iter(obj.rolling(2))
  529. def test_rolling_axis(self, axis_frame):
  530. # see gh-23372.
  531. df = DataFrame(np.ones((10, 20)))
  532. axis = df._get_axis_number(axis_frame)
  533. if axis == 0:
  534. expected = DataFrame({
  535. i: [np.nan] * 2 + [3.0] * 8
  536. for i in range(20)
  537. })
  538. else:
  539. # axis == 1
  540. expected = DataFrame([
  541. [np.nan] * 2 + [3.0] * 18
  542. ] * 10)
  543. result = df.rolling(3, axis=axis_frame).sum()
  544. tm.assert_frame_equal(result, expected)
  545. class TestExpanding(Base):
  546. def setup_method(self, method):
  547. self._create_data()
  548. def test_doc_string(self):
  549. df = DataFrame({'B': [0, 1, 2, np.nan, 4]})
  550. df
  551. df.expanding(2).sum()
  552. @pytest.mark.parametrize(
  553. 'which', ['series', 'frame'])
  554. def test_constructor(self, which):
  555. # GH 12669
  556. o = getattr(self, which)
  557. c = o.expanding
  558. # valid
  559. c(min_periods=1)
  560. c(min_periods=1, center=True)
  561. c(min_periods=1, center=False)
  562. # not valid
  563. for w in [2., 'foo', np.array([2])]:
  564. with pytest.raises(ValueError):
  565. c(min_periods=w)
  566. with pytest.raises(ValueError):
  567. c(min_periods=1, center=w)
  568. @pytest.mark.parametrize(
  569. 'method', ['std', 'mean', 'sum', 'max', 'min', 'var'])
  570. def test_numpy_compat(self, method):
  571. # see gh-12811
  572. e = rwindow.Expanding(Series([2, 4, 6]), window=2)
  573. msg = "numpy operations are not valid with window objects"
  574. with pytest.raises(UnsupportedFunctionCall, match=msg):
  575. getattr(e, method)(1, 2, 3)
  576. with pytest.raises(UnsupportedFunctionCall, match=msg):
  577. getattr(e, method)(dtype=np.float64)
  578. @pytest.mark.parametrize(
  579. 'expander',
  580. [1, pytest.param('ls', marks=pytest.mark.xfail(
  581. reason='GH#16425 expanding with '
  582. 'offset not supported'))])
  583. def test_empty_df_expanding(self, expander):
  584. # GH 15819 Verifies that datetime and integer expanding windows can be
  585. # applied to empty DataFrames
  586. expected = DataFrame()
  587. result = DataFrame().expanding(expander).sum()
  588. tm.assert_frame_equal(result, expected)
  589. # Verifies that datetime and integer expanding windows can be applied
  590. # to empty DataFrames with datetime index
  591. expected = DataFrame(index=pd.DatetimeIndex([]))
  592. result = DataFrame(
  593. index=pd.DatetimeIndex([])).expanding(expander).sum()
  594. tm.assert_frame_equal(result, expected)
  595. def test_missing_minp_zero(self):
  596. # https://github.com/pandas-dev/pandas/pull/18921
  597. # minp=0
  598. x = pd.Series([np.nan])
  599. result = x.expanding(min_periods=0).sum()
  600. expected = pd.Series([0.0])
  601. tm.assert_series_equal(result, expected)
  602. # minp=1
  603. result = x.expanding(min_periods=1).sum()
  604. expected = pd.Series([np.nan])
  605. tm.assert_series_equal(result, expected)
  606. @pytest.mark.parametrize('klass', [pd.Series, pd.DataFrame])
  607. def test_iter_raises(self, klass):
  608. # https://github.com/pandas-dev/pandas/issues/11704
  609. # Iteration over a Window
  610. obj = klass([1, 2, 3, 4])
  611. with pytest.raises(NotImplementedError):
  612. iter(obj.expanding(2))
  613. def test_expanding_axis(self, axis_frame):
  614. # see gh-23372.
  615. df = DataFrame(np.ones((10, 20)))
  616. axis = df._get_axis_number(axis_frame)
  617. if axis == 0:
  618. expected = DataFrame({
  619. i: [np.nan] * 2 + [float(j) for j in range(3, 11)]
  620. for i in range(20)
  621. })
  622. else:
  623. # axis == 1
  624. expected = DataFrame([
  625. [np.nan] * 2 + [float(i) for i in range(3, 21)]
  626. ] * 10)
  627. result = df.expanding(3, axis=axis_frame).sum()
  628. tm.assert_frame_equal(result, expected)
  629. class TestEWM(Base):
  630. def setup_method(self, method):
  631. self._create_data()
  632. def test_doc_string(self):
  633. df = DataFrame({'B': [0, 1, 2, np.nan, 4]})
  634. df
  635. df.ewm(com=0.5).mean()
  636. @pytest.mark.parametrize(
  637. 'which', ['series', 'frame'])
  638. def test_constructor(self, which):
  639. o = getattr(self, which)
  640. c = o.ewm
  641. # valid
  642. c(com=0.5)
  643. c(span=1.5)
  644. c(alpha=0.5)
  645. c(halflife=0.75)
  646. c(com=0.5, span=None)
  647. c(alpha=0.5, com=None)
  648. c(halflife=0.75, alpha=None)
  649. # not valid: mutually exclusive
  650. with pytest.raises(ValueError):
  651. c(com=0.5, alpha=0.5)
  652. with pytest.raises(ValueError):
  653. c(span=1.5, halflife=0.75)
  654. with pytest.raises(ValueError):
  655. c(alpha=0.5, span=1.5)
  656. # not valid: com < 0
  657. with pytest.raises(ValueError):
  658. c(com=-0.5)
  659. # not valid: span < 1
  660. with pytest.raises(ValueError):
  661. c(span=0.5)
  662. # not valid: halflife <= 0
  663. with pytest.raises(ValueError):
  664. c(halflife=0)
  665. # not valid: alpha <= 0 or alpha > 1
  666. for alpha in (-0.5, 1.5):
  667. with pytest.raises(ValueError):
  668. c(alpha=alpha)
  669. @pytest.mark.parametrize(
  670. 'method', ['std', 'mean', 'var'])
  671. def test_numpy_compat(self, method):
  672. # see gh-12811
  673. e = rwindow.EWM(Series([2, 4, 6]), alpha=0.5)
  674. msg = "numpy operations are not valid with window objects"
  675. with pytest.raises(UnsupportedFunctionCall, match=msg):
  676. getattr(e, method)(1, 2, 3)
  677. with pytest.raises(UnsupportedFunctionCall, match=msg):
  678. getattr(e, method)(dtype=np.float64)
  679. # gh-12373 : rolling functions error on float32 data
  680. # make sure rolling functions works for different dtypes
  681. #
  682. # NOTE that these are yielded tests and so _create_data
  683. # is explicitly called.
  684. #
  685. # further note that we are only checking rolling for fully dtype
  686. # compliance (though both expanding and ewm inherit)
  687. class Dtype(object):
  688. window = 2
  689. funcs = {
  690. 'count': lambda v: v.count(),
  691. 'max': lambda v: v.max(),
  692. 'min': lambda v: v.min(),
  693. 'sum': lambda v: v.sum(),
  694. 'mean': lambda v: v.mean(),
  695. 'std': lambda v: v.std(),
  696. 'var': lambda v: v.var(),
  697. 'median': lambda v: v.median()
  698. }
  699. def get_expects(self):
  700. expects = {
  701. 'sr1': {
  702. 'count': Series([1, 2, 2, 2, 2], dtype='float64'),
  703. 'max': Series([np.nan, 1, 2, 3, 4], dtype='float64'),
  704. 'min': Series([np.nan, 0, 1, 2, 3], dtype='float64'),
  705. 'sum': Series([np.nan, 1, 3, 5, 7], dtype='float64'),
  706. 'mean': Series([np.nan, .5, 1.5, 2.5, 3.5], dtype='float64'),
  707. 'std': Series([np.nan] + [np.sqrt(.5)] * 4, dtype='float64'),
  708. 'var': Series([np.nan, .5, .5, .5, .5], dtype='float64'),
  709. 'median': Series([np.nan, .5, 1.5, 2.5, 3.5], dtype='float64')
  710. },
  711. 'sr2': {
  712. 'count': Series([1, 2, 2, 2, 2], dtype='float64'),
  713. 'max': Series([np.nan, 10, 8, 6, 4], dtype='float64'),
  714. 'min': Series([np.nan, 8, 6, 4, 2], dtype='float64'),
  715. 'sum': Series([np.nan, 18, 14, 10, 6], dtype='float64'),
  716. 'mean': Series([np.nan, 9, 7, 5, 3], dtype='float64'),
  717. 'std': Series([np.nan] + [np.sqrt(2)] * 4, dtype='float64'),
  718. 'var': Series([np.nan, 2, 2, 2, 2], dtype='float64'),
  719. 'median': Series([np.nan, 9, 7, 5, 3], dtype='float64')
  720. },
  721. 'df': {
  722. 'count': DataFrame({0: Series([1, 2, 2, 2, 2]),
  723. 1: Series([1, 2, 2, 2, 2])},
  724. dtype='float64'),
  725. 'max': DataFrame({0: Series([np.nan, 2, 4, 6, 8]),
  726. 1: Series([np.nan, 3, 5, 7, 9])},
  727. dtype='float64'),
  728. 'min': DataFrame({0: Series([np.nan, 0, 2, 4, 6]),
  729. 1: Series([np.nan, 1, 3, 5, 7])},
  730. dtype='float64'),
  731. 'sum': DataFrame({0: Series([np.nan, 2, 6, 10, 14]),
  732. 1: Series([np.nan, 4, 8, 12, 16])},
  733. dtype='float64'),
  734. 'mean': DataFrame({0: Series([np.nan, 1, 3, 5, 7]),
  735. 1: Series([np.nan, 2, 4, 6, 8])},
  736. dtype='float64'),
  737. 'std': DataFrame({0: Series([np.nan] + [np.sqrt(2)] * 4),
  738. 1: Series([np.nan] + [np.sqrt(2)] * 4)},
  739. dtype='float64'),
  740. 'var': DataFrame({0: Series([np.nan, 2, 2, 2, 2]),
  741. 1: Series([np.nan, 2, 2, 2, 2])},
  742. dtype='float64'),
  743. 'median': DataFrame({0: Series([np.nan, 1, 3, 5, 7]),
  744. 1: Series([np.nan, 2, 4, 6, 8])},
  745. dtype='float64'),
  746. }
  747. }
  748. return expects
  749. def _create_dtype_data(self, dtype):
  750. sr1 = Series(np.arange(5), dtype=dtype)
  751. sr2 = Series(np.arange(10, 0, -2), dtype=dtype)
  752. df = DataFrame(np.arange(10).reshape((5, 2)), dtype=dtype)
  753. data = {
  754. 'sr1': sr1,
  755. 'sr2': sr2,
  756. 'df': df
  757. }
  758. return data
  759. def _create_data(self):
  760. self.data = self._create_dtype_data(self.dtype)
  761. self.expects = self.get_expects()
  762. def test_dtypes(self):
  763. self._create_data()
  764. for f_name, d_name in product(self.funcs.keys(), self.data.keys()):
  765. f = self.funcs[f_name]
  766. d = self.data[d_name]
  767. exp = self.expects[d_name][f_name]
  768. self.check_dtypes(f, f_name, d, d_name, exp)
  769. def check_dtypes(self, f, f_name, d, d_name, exp):
  770. roll = d.rolling(window=self.window)
  771. result = f(roll)
  772. tm.assert_almost_equal(result, exp)
  773. class TestDtype_object(Dtype):
  774. dtype = object
  775. class Dtype_integer(Dtype):
  776. pass
  777. class TestDtype_int8(Dtype_integer):
  778. dtype = np.int8
  779. class TestDtype_int16(Dtype_integer):
  780. dtype = np.int16
  781. class TestDtype_int32(Dtype_integer):
  782. dtype = np.int32
  783. class TestDtype_int64(Dtype_integer):
  784. dtype = np.int64
  785. class Dtype_uinteger(Dtype):
  786. pass
  787. class TestDtype_uint8(Dtype_uinteger):
  788. dtype = np.uint8
  789. class TestDtype_uint16(Dtype_uinteger):
  790. dtype = np.uint16
  791. class TestDtype_uint32(Dtype_uinteger):
  792. dtype = np.uint32
  793. class TestDtype_uint64(Dtype_uinteger):
  794. dtype = np.uint64
  795. class Dtype_float(Dtype):
  796. pass
  797. class TestDtype_float16(Dtype_float):
  798. dtype = np.float16
  799. class TestDtype_float32(Dtype_float):
  800. dtype = np.float32
  801. class TestDtype_float64(Dtype_float):
  802. dtype = np.float64
  803. class TestDtype_category(Dtype):
  804. dtype = 'category'
  805. include_df = False
  806. def _create_dtype_data(self, dtype):
  807. sr1 = Series(range(5), dtype=dtype)
  808. sr2 = Series(range(10, 0, -2), dtype=dtype)
  809. data = {
  810. 'sr1': sr1,
  811. 'sr2': sr2
  812. }
  813. return data
  814. class DatetimeLike(Dtype):
  815. def check_dtypes(self, f, f_name, d, d_name, exp):
  816. roll = d.rolling(window=self.window)
  817. if f_name == 'count':
  818. result = f(roll)
  819. tm.assert_almost_equal(result, exp)
  820. else:
  821. # other methods not Implemented ATM
  822. with pytest.raises(NotImplementedError):
  823. f(roll)
  824. class TestDtype_timedelta(DatetimeLike):
  825. dtype = np.dtype('m8[ns]')
  826. class TestDtype_datetime(DatetimeLike):
  827. dtype = np.dtype('M8[ns]')
  828. class TestDtype_datetime64UTC(DatetimeLike):
  829. dtype = 'datetime64[ns, UTC]'
  830. def _create_data(self):
  831. pytest.skip("direct creation of extension dtype "
  832. "datetime64[ns, UTC] is not supported ATM")
  833. @pytest.mark.filterwarnings("ignore:can't resolve package:ImportWarning")
  834. class TestMoments(Base):
  835. def setup_method(self, method):
  836. self._create_data()
  837. def test_centered_axis_validation(self):
  838. # ok
  839. Series(np.ones(10)).rolling(window=3, center=True, axis=0).mean()
  840. # bad axis
  841. with pytest.raises(ValueError):
  842. Series(np.ones(10)).rolling(window=3, center=True, axis=1).mean()
  843. # ok ok
  844. DataFrame(np.ones((10, 10))).rolling(window=3, center=True,
  845. axis=0).mean()
  846. DataFrame(np.ones((10, 10))).rolling(window=3, center=True,
  847. axis=1).mean()
  848. # bad axis
  849. with pytest.raises(ValueError):
  850. (DataFrame(np.ones((10, 10)))
  851. .rolling(window=3, center=True, axis=2).mean())
  852. def test_rolling_sum(self):
  853. self._check_moment_func(np.nansum, name='sum',
  854. zero_min_periods_equal=False)
  855. def test_rolling_count(self):
  856. counter = lambda x: np.isfinite(x).astype(float).sum()
  857. self._check_moment_func(counter, name='count', has_min_periods=False,
  858. fill_value=0)
  859. def test_rolling_mean(self):
  860. self._check_moment_func(np.mean, name='mean')
  861. @td.skip_if_no_scipy
  862. def test_cmov_mean(self):
  863. # GH 8238
  864. vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48,
  865. 10.63, 14.48])
  866. result = Series(vals).rolling(5, center=True).mean()
  867. expected = Series([np.nan, np.nan, 9.962, 11.27, 11.564, 12.516,
  868. 12.818, 12.952, np.nan, np.nan])
  869. tm.assert_series_equal(expected, result)
  870. @td.skip_if_no_scipy
  871. def test_cmov_window(self):
  872. # GH 8238
  873. vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48,
  874. 10.63, 14.48])
  875. result = Series(vals).rolling(5, win_type='boxcar', center=True).mean()
  876. expected = Series([np.nan, np.nan, 9.962, 11.27, 11.564, 12.516,
  877. 12.818, 12.952, np.nan, np.nan])
  878. tm.assert_series_equal(expected, result)
  879. @td.skip_if_no_scipy
  880. def test_cmov_window_corner(self):
  881. # GH 8238
  882. # all nan
  883. vals = pd.Series([np.nan] * 10)
  884. result = vals.rolling(5, center=True, win_type='boxcar').mean()
  885. assert np.isnan(result).all()
  886. # empty
  887. vals = pd.Series([])
  888. result = vals.rolling(5, center=True, win_type='boxcar').mean()
  889. assert len(result) == 0
  890. # shorter than window
  891. vals = pd.Series(np.random.randn(5))
  892. result = vals.rolling(10, win_type='boxcar').mean()
  893. assert np.isnan(result).all()
  894. assert len(result) == 5
  895. @td.skip_if_no_scipy
  896. def test_cmov_window_frame(self):
  897. # Gh 8238
  898. vals = np.array([[12.18, 3.64], [10.18, 9.16], [13.24, 14.61],
  899. [4.51, 8.11], [6.15, 11.44], [9.14, 6.21],
  900. [11.31, 10.67], [2.94, 6.51], [9.42, 8.39], [12.44,
  901. 7.34]])
  902. xp = np.array([[np.nan, np.nan], [np.nan, np.nan], [9.252, 9.392],
  903. [8.644, 9.906], [8.87, 10.208], [6.81, 8.588],
  904. [7.792, 8.644], [9.05, 7.824], [np.nan, np.nan
  905. ], [np.nan, np.nan]])
  906. # DataFrame
  907. rs = DataFrame(vals).rolling(5, win_type='boxcar', center=True).mean()
  908. tm.assert_frame_equal(DataFrame(xp), rs)
  909. # invalid method
  910. with pytest.raises(AttributeError):
  911. (DataFrame(vals).rolling(5, win_type='boxcar', center=True)
  912. .std())
  913. # sum
  914. xp = np.array([[np.nan, np.nan], [np.nan, np.nan], [46.26, 46.96],
  915. [43.22, 49.53], [44.35, 51.04], [34.05, 42.94],
  916. [38.96, 43.22], [45.25, 39.12], [np.nan, np.nan
  917. ], [np.nan, np.nan]])
  918. rs = DataFrame(vals).rolling(5, win_type='boxcar', center=True).sum()
  919. tm.assert_frame_equal(DataFrame(xp), rs)
  920. @td.skip_if_no_scipy
  921. def test_cmov_window_na_min_periods(self):
  922. # min_periods
  923. vals = Series(np.random.randn(10))
  924. vals[4] = np.nan
  925. vals[8] = np.nan
  926. xp = vals.rolling(5, min_periods=4, center=True).mean()
  927. rs = vals.rolling(5, win_type='boxcar', min_periods=4,
  928. center=True).mean()
  929. tm.assert_series_equal(xp, rs)
  930. @td.skip_if_no_scipy
  931. def test_cmov_window_regular(self, win_types):
  932. # GH 8238
  933. vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48,
  934. 10.63, 14.48])
  935. xps = {
  936. 'hamming': [np.nan, np.nan, 8.71384, 9.56348, 12.38009, 14.03687,
  937. 13.8567, 11.81473, np.nan, np.nan],
  938. 'triang': [np.nan, np.nan, 9.28667, 10.34667, 12.00556, 13.33889,
  939. 13.38, 12.33667, np.nan, np.nan],
  940. 'barthann': [np.nan, np.nan, 8.4425, 9.1925, 12.5575, 14.3675,
  941. 14.0825, 11.5675, np.nan, np.nan],
  942. 'bohman': [np.nan, np.nan, 7.61599, 9.1764, 12.83559, 14.17267,
  943. 14.65923, 11.10401, np.nan, np.nan],
  944. 'blackmanharris': [np.nan, np.nan, 6.97691, 9.16438, 13.05052,
  945. 14.02156, 15.10512, 10.74574, np.nan, np.nan],
  946. 'nuttall': [np.nan, np.nan, 7.04618, 9.16786, 13.02671, 14.03559,
  947. 15.05657, 10.78514, np.nan, np.nan],
  948. 'blackman': [np.nan, np.nan, 7.73345, 9.17869, 12.79607, 14.20036,
  949. 14.57726, 11.16988, np.nan, np.nan],
  950. 'bartlett': [np.nan, np.nan, 8.4425, 9.1925, 12.5575, 14.3675,
  951. 14.0825, 11.5675, np.nan, np.nan]
  952. }
  953. xp = Series(xps[win_types])
  954. rs = Series(vals).rolling(5, win_type=win_types, center=True).mean()
  955. tm.assert_series_equal(xp, rs)
  956. @td.skip_if_no_scipy
  957. def test_cmov_window_regular_linear_range(self, win_types):
  958. # GH 8238
  959. vals = np.array(range(10), dtype=np.float)
  960. xp = vals.copy()
  961. xp[:2] = np.nan
  962. xp[-2:] = np.nan
  963. xp = Series(xp)
  964. rs = Series(vals).rolling(5, win_type=win_types, center=True).mean()
  965. tm.assert_series_equal(xp, rs)
  966. @td.skip_if_no_scipy
  967. def test_cmov_window_regular_missing_data(self, win_types):
  968. # GH 8238
  969. vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, np.nan,
  970. 10.63, 14.48])
  971. xps = {
  972. 'bartlett': [np.nan, np.nan, 9.70333, 10.5225, 8.4425, 9.1925,
  973. 12.5575, 14.3675, 15.61667, 13.655],
  974. 'blackman': [np.nan, np.nan, 9.04582, 11.41536, 7.73345, 9.17869,
  975. 12.79607, 14.20036, 15.8706, 13.655],
  976. 'barthann': [np.nan, np.nan, 9.70333, 10.5225, 8.4425, 9.1925,
  977. 12.5575, 14.3675, 15.61667, 13.655],
  978. 'bohman': [np.nan, np.nan, 8.9444, 11.56327, 7.61599, 9.1764,
  979. 12.83559, 14.17267, 15.90976, 13.655],
  980. 'hamming': [np.nan, np.nan, 9.59321, 10.29694, 8.71384, 9.56348,
  981. 12.38009, 14.20565, 15.24694, 13.69758],
  982. 'nuttall': [np.nan, np.nan, 8.47693, 12.2821, 7.04618, 9.16786,
  983. 13.02671, 14.03673, 16.08759, 13.65553],
  984. 'triang': [np.nan, np.nan, 9.33167, 9.76125, 9.28667, 10.34667,
  985. 12.00556, 13.82125, 14.49429, 13.765],
  986. 'blackmanharris': [np.nan, np.nan, 8.42526, 12.36824, 6.97691,
  987. 9.16438, 13.05052, 14.02175, 16.1098, 13.65509]
  988. }
  989. xp = Series(xps[win_types])
  990. rs = Series(vals).rolling(5, win_type=win_types, min_periods=3).mean()
  991. tm.assert_series_equal(xp, rs)
  992. @td.skip_if_no_scipy
  993. def test_cmov_window_special(self, win_types_special):
  994. # GH 8238
  995. kwds = {
  996. 'kaiser': {'beta': 1.},
  997. 'gaussian': {'std': 1.},
  998. 'general_gaussian': {'power': 2., 'width': 2.}}
  999. vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48,
  1000. 10.63, 14.48])
  1001. xps = {
  1002. 'gaussian': [np.nan, np.nan, 8.97297, 9.76077, 12.24763, 13.89053,
  1003. 13.65671, 12.01002, np.nan, np.nan],
  1004. 'general_gaussian': [np.nan, np.nan, 9.85011, 10.71589, 11.73161,
  1005. 13.08516, 12.95111, 12.74577, np.nan, np.nan],
  1006. 'kaiser': [np.nan, np.nan, 9.86851, 11.02969, 11.65161, 12.75129,
  1007. 12.90702, 12.83757, np.nan, np.nan]
  1008. }
  1009. xp = Series(xps[win_types_special])
  1010. rs = Series(vals).rolling(
  1011. 5, win_type=win_types_special, center=True).mean(
  1012. **kwds[win_types_special])
  1013. tm.assert_series_equal(xp, rs)
  1014. @td.skip_if_no_scipy
  1015. def test_cmov_window_special_linear_range(self, win_types_special):
  1016. # GH 8238
  1017. kwds = {
  1018. 'kaiser': {'beta': 1.},
  1019. 'gaussian': {'std': 1.},
  1020. 'general_gaussian': {'power': 2., 'width': 2.},
  1021. 'slepian': {'width': 0.5}}
  1022. vals = np.array(range(10), dtype=np.float)
  1023. xp = vals.copy()
  1024. xp[:2] = np.nan
  1025. xp[-2:] = np.nan
  1026. xp = Series(xp)
  1027. rs = Series(vals).rolling(
  1028. 5, win_type=win_types_special, center=True).mean(
  1029. **kwds[win_types_special])
  1030. tm.assert_series_equal(xp, rs)
  1031. def test_rolling_median(self):
  1032. self._check_moment_func(np.median, name='median')
  1033. def test_rolling_min(self):
  1034. self._check_moment_func(np.min, name='min')
  1035. a = pd.Series([1, 2, 3, 4, 5])
  1036. result = a.rolling(window=100, min_periods=1).min()
  1037. expected = pd.Series(np.ones(len(a)))
  1038. tm.assert_series_equal(result, expected)
  1039. with pytest.raises(ValueError):
  1040. pd.Series([1, 2, 3]).rolling(window=3, min_periods=5).min()
  1041. def test_rolling_max(self):
  1042. self._check_moment_func(np.max, name='max')
  1043. a = pd.Series([1, 2, 3, 4, 5], dtype=np.float64)
  1044. b = a.rolling(window=100, min_periods=1).max()
  1045. tm.assert_almost_equal(a, b)
  1046. with pytest.raises(ValueError):
  1047. pd.Series([1, 2, 3]).rolling(window=3, min_periods=5).max()
  1048. @pytest.mark.parametrize('q', [0.0, .1, .5, .9, 1.0])
  1049. def test_rolling_quantile(self, q):
  1050. def scoreatpercentile(a, per):
  1051. values = np.sort(a, axis=0)
  1052. idx = int(per / 1. * (values.shape[0] - 1))
  1053. if idx == values.shape[0] - 1:
  1054. retval = values[-1]
  1055. else:
  1056. qlow = float(idx) / float(values.shape[0] - 1)
  1057. qhig = float(idx + 1) / float(values.shape[0] - 1)
  1058. vlow = values[idx]
  1059. vhig = values[idx + 1]
  1060. retval = vlow + (vhig - vlow) * (per - qlow) / (qhig - qlow)
  1061. return retval
  1062. def quantile_func(x):
  1063. return scoreatpercentile(x, q)
  1064. self._check_moment_func(quantile_func, name='quantile',
  1065. quantile=q)
  1066. def test_rolling_quantile_np_percentile(self):
  1067. # #9413: Tests that rolling window's quantile default behavior
  1068. # is analogus to Numpy's percentile
  1069. row = 10
  1070. col = 5
  1071. idx = pd.date_range('20100101', periods=row, freq='B')
  1072. df = DataFrame(np.random.rand(row * col).reshape((row, -1)), index=idx)
  1073. df_quantile = df.quantile([0.25, 0.5, 0.75], axis=0)
  1074. np_percentile = np.percentile(df, [25, 50, 75], axis=0)
  1075. tm.assert_almost_equal(df_quantile.values, np.array(np_percentile))
  1076. @pytest.mark.parametrize('quantile', [0.0, 0.1, 0.45, 0.5, 1])
  1077. @pytest.mark.parametrize('interpolation', ['linear', 'lower', 'higher',
  1078. 'nearest', 'midpoint'])
  1079. @pytest.mark.parametrize('data', [[1., 2., 3., 4., 5., 6., 7.],
  1080. [8., 1., 3., 4., 5., 2., 6., 7.],
  1081. [0., np.nan, 0.2, np.nan, 0.4],
  1082. [np.nan, np.nan, np.nan, np.nan],
  1083. [np.nan, 0.1, np.nan, 0.3, 0.4, 0.5],
  1084. [0.5], [np.nan, 0.7, 0.6]])
  1085. def test_rolling_quantile_interpolation_options(self, quantile,
  1086. interpolation, data):
  1087. # Tests that rolling window's quantile behavior is analogous to
  1088. # Series' quantile for each interpolation option
  1089. s = Series(data)
  1090. q1 = s.quantile(quantile, interpolation)
  1091. q2 = s.expanding(min_periods=1).quantile(
  1092. quantile, interpolation).iloc[-1]
  1093. if np.isnan(q1):
  1094. assert np.isnan(q2)
  1095. else:
  1096. assert q1 == q2
  1097. def test_invalid_quantile_value(self):
  1098. data = np.arange(5)
  1099. s = Series(data)
  1100. with pytest.raises(ValueError, match="Interpolation 'invalid'"
  1101. " is not supported"):
  1102. s.rolling(len(data), min_periods=1).quantile(
  1103. 0.5, interpolation='invalid')
  1104. def test_rolling_quantile_param(self):
  1105. ser = Series([0.0, .1, .5, .9, 1.0])
  1106. with pytest.raises(ValueError):
  1107. ser.rolling(3).quantile(-0.1)
  1108. with pytest.raises(ValueError):
  1109. ser.rolling(3).quantile(10.0)
  1110. with pytest.raises(TypeError):
  1111. ser.rolling(3).quantile('foo')
  1112. def test_rolling_apply(self, raw):
  1113. # suppress warnings about empty slices, as we are deliberately testing
  1114. # with a 0-length Series
  1115. with warnings.catch_warnings():
  1116. warnings.filterwarnings("ignore",
  1117. message=".*(empty slice|0 for slice).*",
  1118. category=RuntimeWarning)
  1119. def f(x):
  1120. return x[np.isfinite(x)].mean()
  1121. self._check_moment_func(np.mean, name='apply', func=f, raw=raw)
  1122. expected = Series([])
  1123. result = expected.rolling(10).apply(lambda x: x.mean(), raw=raw)
  1124. tm.assert_series_equal(result, expected)
  1125. # gh-8080
  1126. s = Series([None, None, None])
  1127. result = s.rolling(2, min_periods=0).apply(lambda x: len(x), raw=raw)
  1128. expected = Series([1., 2., 2.])
  1129. tm.assert_series_equal(result, expected)
  1130. result = s.rolling(2, min_periods=0).apply(len, raw=raw)
  1131. tm.assert_series_equal(result, expected)
  1132. @pytest.mark.parametrize('klass', [Series, DataFrame])
  1133. @pytest.mark.parametrize(
  1134. 'method', [lambda x: x.rolling(window=2), lambda x: x.expanding()])
  1135. def test_apply_future_warning(self, klass, method):
  1136. # gh-5071
  1137. s = klass(np.arange(3))
  1138. with tm.assert_produces_warning(FutureWarning):
  1139. method(s).apply(lambda x: len(x))
  1140. def test_rolling_apply_out_of_bounds(self, raw):
  1141. # gh-1850
  1142. vals = pd.Series([1, 2, 3, 4])
  1143. result = vals.rolling(10).apply(np.sum, raw=raw)
  1144. assert result.isna().all()
  1145. result = vals.rolling(10, min_periods=1).apply(np.sum, raw=raw)
  1146. expected = pd.Series([1, 3, 6, 10], dtype=float)
  1147. tm.assert_almost_equal(result, expected)
  1148. @pytest.mark.parametrize('window', [2, '2s'])
  1149. def test_rolling_apply_with_pandas_objects(self, window):
  1150. # 5071
  1151. df = pd.DataFrame({'A': np.random.randn(5),
  1152. 'B': np.random.randint(0, 10, size=5)},
  1153. index=pd.date_range('20130101', periods=5, freq='s'))
  1154. # we have an equal spaced timeseries index
  1155. # so simulate removing the first period
  1156. def f(x):
  1157. if x.index[0] == df.index[0]:
  1158. return np.nan
  1159. return x.iloc[-1]
  1160. result = df.rolling(window).apply(f, raw=False)
  1161. expected = df.iloc[2:].reindex_like(df)
  1162. tm.assert_frame_equal(result, expected)
  1163. with pytest.raises(AttributeError):
  1164. df.rolling(window).apply(f, raw=True)
  1165. def test_rolling_std(self):
  1166. self._check_moment_func(lambda x: np.std(x, ddof=1),
  1167. name='std')
  1168. self._check_moment_func(lambda x: np.std(x, ddof=0),
  1169. name='std', ddof=0)
  1170. def test_rolling_std_1obs(self):
  1171. vals = pd.Series([1., 2., 3., 4., 5.])
  1172. result = vals.rolling(1, min_periods=1).std()
  1173. expected = pd.Series([np.nan] * 5)
  1174. tm.assert_series_equal(result, expected)
  1175. result = vals.rolling(1, min_periods=1).std(ddof=0)
  1176. expected = pd.Series([0.] * 5)
  1177. tm.assert_series_equal(result, expected)
  1178. result = (pd.Series([np.nan, np.nan, 3, 4, 5])
  1179. .rolling(3, min_periods=2).std())
  1180. assert np.isnan(result[2])
  1181. def test_rolling_std_neg_sqrt(self):
  1182. # unit test from Bottleneck
  1183. # Test move_nanstd for neg sqrt.
  1184. a = pd.Series([0.0011448196318903589, 0.00028718669878572767,
  1185. 0.00028718669878572767, 0.00028718669878572767,
  1186. 0.00028718669878572767])
  1187. b = a.rolling(window=3).std()
  1188. assert np.isfinite(b[2:]).all()
  1189. b = a.ewm(span=3).std()
  1190. assert np.isfinite(b[2:]).all()
  1191. def test_rolling_var(self):
  1192. self._check_moment_func(lambda x: np.var(x, ddof=1),
  1193. name='var')
  1194. self._check_moment_func(lambda x: np.var(x, ddof=0),
  1195. name='var', ddof=0)
  1196. @td.skip_if_no_scipy
  1197. def test_rolling_skew(self):
  1198. from scipy.stats import skew
  1199. self._check_moment_func(lambda x: skew(x, bias=False), name='skew')
  1200. @td.skip_if_no_scipy
  1201. def test_rolling_kurt(self):
  1202. from scipy.stats import kurtosis
  1203. self._check_moment_func(lambda x: kurtosis(x, bias=False),
  1204. name='kurt')
  1205. def _check_moment_func(self, static_comp, name, has_min_periods=True,
  1206. has_center=True, has_time_rule=True,
  1207. fill_value=None, zero_min_periods_equal=True,
  1208. **kwargs):
  1209. def get_result(obj, window, min_periods=None, center=False):
  1210. r = obj.rolling(window=window, min_periods=min_periods,
  1211. center=center)
  1212. return getattr(r, name)(**kwargs)
  1213. series_result = get_result(self.series, window=50)
  1214. assert isinstance(series_result, Series)
  1215. tm.assert_almost_equal(series_result.iloc[-1],
  1216. static_comp(self.series[-50:]))
  1217. frame_result = get_result(self.frame, window=50)
  1218. assert isinstance(frame_result, DataFrame)
  1219. tm.assert_series_equal(
  1220. frame_result.iloc[-1, :],
  1221. self.frame.iloc[-50:, :].apply(static_comp, axis=0, raw=raw),
  1222. check_names=False)
  1223. # check time_rule works
  1224. if has_time_rule:
  1225. win = 25
  1226. minp = 10
  1227. series = self.series[::2].resample('B').mean()
  1228. frame = self.frame[::2].resample('B').mean()
  1229. if has_min_periods:
  1230. series_result = get_result(series, window=win,
  1231. min_periods=minp)
  1232. frame_result = get_result(frame, window=win,
  1233. min_periods=minp)
  1234. else:
  1235. series_result = get_result(series, window=win)
  1236. frame_result = get_result(frame, window=win)
  1237. last_date = series_result.index[-1]
  1238. prev_date = last_date - 24 * offsets.BDay()
  1239. trunc_series = self.series[::2].truncate(prev_date, last_date)
  1240. trunc_frame = self.frame[::2].truncate(prev_date, last_date)
  1241. tm.assert_almost_equal(series_result[-1],
  1242. static_comp(trunc_series))
  1243. tm.assert_series_equal(frame_result.xs(last_date),
  1244. trunc_frame.apply(static_comp, raw=raw),
  1245. check_names=False)
  1246. # excluding NaNs correctly
  1247. obj = Series(randn(50))
  1248. obj[:10] = np.NaN
  1249. obj[-10:] = np.NaN
  1250. if has_min_periods:
  1251. result = get_result(obj, 50, min_periods=30)
  1252. tm.assert_almost_equal(result.iloc[-1], static_comp(obj[10:-10]))
  1253. # min_periods is working correctly
  1254. result = get_result(obj, 20, min_periods=15)
  1255. assert isna(result.iloc[23])
  1256. assert not isna(result.iloc[24])
  1257. assert not isna(result.iloc[-6])
  1258. assert isna(result.iloc[-5])
  1259. obj2 = Series(randn(20))
  1260. result = get_result(obj2, 10, min_periods=5)
  1261. assert isna(result.iloc[3])
  1262. assert notna(result.iloc[4])
  1263. if zero_min_periods_equal:
  1264. # min_periods=0 may be equivalent to min_periods=1
  1265. result0 = get_result(obj, 20, min_periods=0)
  1266. result1 = get_result(obj, 20, min_periods=1)
  1267. tm.assert_almost_equal(result0, result1)
  1268. else:
  1269. result = get_result(obj, 50)
  1270. tm.assert_almost_equal(result.iloc[-1], static_comp(obj[10:-10]))
  1271. # window larger than series length (#7297)
  1272. if has_min_periods:
  1273. for minp in (0, len(self.series) - 1, len(self.series)):
  1274. result = get_result(self.series, len(self.series) + 1,
  1275. min_periods=minp)
  1276. expected = get_result(self.series, len(self.series),
  1277. min_periods=minp)
  1278. nan_mask = isna(result)
  1279. tm.assert_series_equal(nan_mask, isna(expected))
  1280. nan_mask = ~nan_mask
  1281. tm.assert_almost_equal(result[nan_mask],
  1282. expected[nan_mask])
  1283. else:
  1284. result = get_result(self.series, len(self.series) + 1)
  1285. expected = get_result(self.series, len(self.series))
  1286. nan_mask = isna(result)
  1287. tm.assert_series_equal(nan_mask, isna(expected))
  1288. nan_mask = ~nan_mask
  1289. tm.assert_almost_equal(result[nan_mask], expected[nan_mask])
  1290. # check center=True
  1291. if has_center:
  1292. if has_min_periods:
  1293. result = get_result(obj, 20, min_periods=15, center=True)
  1294. expected = get_result(
  1295. pd.concat([obj, Series([np.NaN] * 9)]), 20,
  1296. min_periods=15)[9:].reset_index(drop=True)
  1297. else:
  1298. result = get_result(obj, 20, center=True)
  1299. expected = get_result(
  1300. pd.concat([obj, Series([np.NaN] * 9)]),
  1301. 20)[9:].reset_index(drop=True)
  1302. tm.assert_series_equal(result, expected)
  1303. # shifter index
  1304. s = ['x%d' % x for x in range(12)]
  1305. if has_min_periods:
  1306. minp = 10
  1307. series_xp = get_result(
  1308. self.series.reindex(list(self.series.index) + s),
  1309. window=25,
  1310. min_periods=minp).shift(-12).reindex(self.series.index)
  1311. frame_xp = get_result(
  1312. self.frame.reindex(list(self.frame.index) + s),
  1313. window=25,
  1314. min_periods=minp).shift(-12).reindex(self.frame.index)
  1315. series_rs = get_result(self.series, window=25,
  1316. min_periods=minp, center=True)
  1317. frame_rs = get_result(self.frame, window=25, min_periods=minp,
  1318. center=True)
  1319. else:
  1320. series_xp = get_result(
  1321. self.series.reindex(list(self.series.index) + s),
  1322. window=25).shift(-12).reindex(self.series.index)
  1323. frame_xp = get_result(
  1324. self.frame.reindex(list(self.frame.index) + s),
  1325. window=25).shift(-12).reindex(self.frame.index)
  1326. series_rs = get_result(self.series, window=25, center=True)
  1327. frame_rs = get_result(self.frame, window=25, center=True)
  1328. if fill_value is not None:
  1329. series_xp = series_xp.fillna(fill_value)
  1330. frame_xp = frame_xp.fillna(fill_value)
  1331. tm.assert_series_equal(series_xp, series_rs)
  1332. tm.assert_frame_equal(frame_xp, frame_rs)
  1333. def test_ewma(self):
  1334. self._check_ew(name='mean')
  1335. vals = pd.Series(np.zeros(1000))
  1336. vals[5] = 1
  1337. result = vals.ewm(span=100, adjust=False).mean().sum()
  1338. assert np.abs(result - 1) < 1e-2
  1339. @pytest.mark.parametrize('adjust', [True, False])
  1340. @pytest.mark.parametrize('ignore_na', [True, False])
  1341. def test_ewma_cases(self, adjust, ignore_na):
  1342. # try adjust/ignore_na args matrix
  1343. s = Series([1.0, 2.0, 4.0, 8.0])
  1344. if adjust:
  1345. expected = Series([1.0, 1.6, 2.736842, 4.923077])
  1346. else:
  1347. expected = Series([1.0, 1.333333, 2.222222, 4.148148])
  1348. result = s.ewm(com=2.0, adjust=adjust, ignore_na=ignore_na).mean()
  1349. tm.assert_series_equal(result, expected)
  1350. def test_ewma_nan_handling(self):
  1351. s = Series([1.] + [np.nan] * 5 + [1.])
  1352. result = s.ewm(com=5).mean()
  1353. tm.assert_series_equal(result, Series([1.] * len(s)))
  1354. s = Series([np.nan] * 2 + [1.] + [np.nan] * 2 + [1.])
  1355. result = s.ewm(com=5).mean()
  1356. tm.assert_series_equal(result, Series([np.nan] * 2 + [1.] * 4))
  1357. # GH 7603
  1358. s0 = Series([np.nan, 1., 101.])
  1359. s1 = Series([1., np.nan, 101.])
  1360. s2 = Series([np.nan, 1., np.nan, np.nan, 101., np.nan])
  1361. s3 = Series([1., np.nan, 101., 50.])
  1362. com = 2.
  1363. alpha = 1. / (1. + com)
  1364. def simple_wma(s, w):
  1365. return (s.multiply(w).cumsum() / w.cumsum()).fillna(method='ffill')
  1366. for (s, adjust, ignore_na, w) in [
  1367. (s0, True, False, [np.nan, (1. - alpha), 1.]),
  1368. (s0, True, True, [np.nan, (1. - alpha), 1.]),
  1369. (s0, False, False, [np.nan, (1. - alpha), alpha]),
  1370. (s0, False, True, [np.nan, (1. - alpha), alpha]),
  1371. (s1, True, False, [(1. - alpha) ** 2, np.nan, 1.]),
  1372. (s1, True, True, [(1. - alpha), np.nan, 1.]),
  1373. (s1, False, False, [(1. - alpha) ** 2, np.nan, alpha]),
  1374. (s1, False, True, [(1. - alpha), np.nan, alpha]),
  1375. (s2, True, False, [np.nan, (1. - alpha) **
  1376. 3, np.nan, np.nan, 1., np.nan]),
  1377. (s2, True, True, [np.nan, (1. - alpha),
  1378. np.nan, np.nan, 1., np.nan]),
  1379. (s2, False, False, [np.nan, (1. - alpha) **
  1380. 3, np.nan, np.nan, alpha, np.nan]),
  1381. (s2, False, True, [np.nan, (1. - alpha),
  1382. np.nan, np.nan, alpha, np.nan]),
  1383. (s3, True, False, [(1. - alpha) **
  1384. 3, np.nan, (1. - alpha), 1.]),
  1385. (s3, True, True, [(1. - alpha) **
  1386. 2, np.nan, (1. - alpha), 1.]),
  1387. (s3, False, False, [(1. - alpha) ** 3, np.nan,
  1388. (1. - alpha) * alpha,
  1389. alpha * ((1. - alpha) ** 2 + alpha)]),
  1390. (s3, False, True, [(1. - alpha) ** 2,
  1391. np.nan, (1. - alpha) * alpha, alpha])]:
  1392. expected = simple_wma(s, Series(w))
  1393. result = s.ewm(com=com, adjust=adjust, ignore_na=ignore_na).mean()
  1394. tm.assert_series_equal(result, expected)
  1395. if ignore_na is False:
  1396. # check that ignore_na defaults to False
  1397. result = s.ewm(com=com, adjust=adjust).mean()
  1398. tm.assert_series_equal(result, expected)
  1399. def test_ewmvar(self):
  1400. self._check_ew(name='var')
  1401. def test_ewmvol(self):
  1402. self._check_ew(name='vol')
  1403. def test_ewma_span_com_args(self):
  1404. A = self.series.ewm(com=9.5).mean()
  1405. B = self.series.ewm(span=20).mean()
  1406. tm.assert_almost_equal(A, B)
  1407. with pytest.raises(ValueError):
  1408. self.series.ewm(com=9.5, span=20)
  1409. with pytest.raises(ValueError):
  1410. self.series.ewm().mean()
  1411. def test_ewma_halflife_arg(self):
  1412. A = self.series.ewm(com=13.932726172912965).mean()
  1413. B = self.series.ewm(halflife=10.0).mean()
  1414. tm.assert_almost_equal(A, B)
  1415. with pytest.raises(ValueError):
  1416. self.series.ewm(span=20, halflife=50)
  1417. with pytest.raises(ValueError):
  1418. self.series.ewm(com=9.5, halflife=50)
  1419. with pytest.raises(ValueError):
  1420. self.series.ewm(com=9.5, span=20, halflife=50)
  1421. with pytest.raises(ValueError):
  1422. self.series.ewm()
  1423. def test_ewm_alpha(self):
  1424. # GH 10789
  1425. s = Series(self.arr)
  1426. a = s.ewm(alpha=0.61722699889169674).mean()
  1427. b = s.ewm(com=0.62014947789973052).mean()
  1428. c = s.ewm(span=2.240298955799461).mean()
  1429. d = s.ewm(halflife=0.721792864318).mean()
  1430. tm.assert_series_equal(a, b)
  1431. tm.assert_series_equal(a, c)
  1432. tm.assert_series_equal(a, d)
  1433. def test_ewm_alpha_arg(self):
  1434. # GH 10789
  1435. s = self.series
  1436. with pytest.raises(ValueError):
  1437. s.ewm()
  1438. with pytest.raises(ValueError):
  1439. s.ewm(com=10.0, alpha=0.5)
  1440. with pytest.raises(ValueError):
  1441. s.ewm(span=10.0, alpha=0.5)
  1442. with pytest.raises(ValueError):
  1443. s.ewm(halflife=10.0, alpha=0.5)
  1444. def test_ewm_domain_checks(self):
  1445. # GH 12492
  1446. s = Series(self.arr)
  1447. # com must satisfy: com >= 0
  1448. pytest.raises(ValueError, s.ewm, com=-0.1)
  1449. s.ewm(com=0.0)
  1450. s.ewm(com=0.1)
  1451. # span must satisfy: span >= 1
  1452. pytest.raises(ValueError, s.ewm, span=-0.1)
  1453. pytest.raises(ValueError, s.ewm, span=0.0)
  1454. pytest.raises(ValueError, s.ewm, span=0.9)
  1455. s.ewm(span=1.0)
  1456. s.ewm(span=1.1)
  1457. # halflife must satisfy: halflife > 0
  1458. pytest.raises(ValueError, s.ewm, halflife=-0.1)
  1459. pytest.raises(ValueError, s.ewm, halflife=0.0)
  1460. s.ewm(halflife=0.1)
  1461. # alpha must satisfy: 0 < alpha <= 1
  1462. pytest.raises(ValueError, s.ewm, alpha=-0.1)
  1463. pytest.raises(ValueError, s.ewm, alpha=0.0)
  1464. s.ewm(alpha=0.1)
  1465. s.ewm(alpha=1.0)
  1466. pytest.raises(ValueError, s.ewm, alpha=1.1)
  1467. @pytest.mark.parametrize('method', ['mean', 'vol', 'var'])
  1468. def test_ew_empty_series(self, method):
  1469. vals = pd.Series([], dtype=np.float64)
  1470. ewm = vals.ewm(3)
  1471. result = getattr(ewm, method)()
  1472. tm.assert_almost_equal(result, vals)
  1473. def _check_ew(self, name=None, preserve_nan=False):
  1474. series_result = getattr(self.series.ewm(com=10), name)()
  1475. assert isinstance(series_result, Series)
  1476. frame_result = getattr(self.frame.ewm(com=10), name)()
  1477. assert type(frame_result) == DataFrame
  1478. result = getattr(self.series.ewm(com=10), name)()
  1479. if preserve_nan:
  1480. assert result[self._nan_locs].isna().all()
  1481. # excluding NaNs correctly
  1482. arr = randn(50)
  1483. arr[:10] = np.NaN
  1484. arr[-10:] = np.NaN
  1485. s = Series(arr)
  1486. # check min_periods
  1487. # GH 7898
  1488. result = getattr(s.ewm(com=50, min_periods=2), name)()
  1489. assert result[:11].isna().all()
  1490. assert not result[11:].isna().any()
  1491. for min_periods in (0, 1):
  1492. result = getattr(s.ewm(com=50, min_periods=min_periods), name)()
  1493. if name == 'mean':
  1494. assert result[:10].isna().all()
  1495. assert not result[10:].isna().any()
  1496. else:
  1497. # ewm.std, ewm.vol, ewm.var (with bias=False) require at least
  1498. # two values
  1499. assert result[:11].isna().all()
  1500. assert not result[11:].isna().any()
  1501. # check series of length 0
  1502. result = getattr(Series().ewm(com=50, min_periods=min_periods),
  1503. name)()
  1504. tm.assert_series_equal(result, Series())
  1505. # check series of length 1
  1506. result = getattr(Series([1.]).ewm(50, min_periods=min_periods),
  1507. name)()
  1508. if name == 'mean':
  1509. tm.assert_series_equal(result, Series([1.]))
  1510. else:
  1511. # ewm.std, ewm.vol, ewm.var with bias=False require at least
  1512. # two values
  1513. tm.assert_series_equal(result, Series([np.NaN]))
  1514. # pass in ints
  1515. result2 = getattr(Series(np.arange(50)).ewm(span=10), name)()
  1516. assert result2.dtype == np.float_
  1517. class TestPairwise(object):
  1518. # GH 7738
  1519. df1s = [DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[0, 1]),
  1520. DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1, 0]),
  1521. DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1, 1]),
  1522. DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]],
  1523. columns=['C', 'C']),
  1524. DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1., 0]),
  1525. DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[0., 1]),
  1526. DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=['C', 1]),
  1527. DataFrame([[2., 4.], [1., 2.], [5., 2.], [8., 1.]],
  1528. columns=[1, 0.]),
  1529. DataFrame([[2, 4.], [1, 2.], [5, 2.], [8, 1.]],
  1530. columns=[0, 1.]),
  1531. DataFrame([[2, 4], [1, 2], [5, 2], [8, 1.]],
  1532. columns=[1., 'X']), ]
  1533. df2 = DataFrame([[None, 1, 1], [None, 1, 2],
  1534. [None, 3, 2], [None, 8, 1]], columns=['Y', 'Z', 'X'])
  1535. s = Series([1, 1, 3, 8])
  1536. def compare(self, result, expected):
  1537. # since we have sorted the results
  1538. # we can only compare non-nans
  1539. result = result.dropna().values
  1540. expected = expected.dropna().values
  1541. tm.assert_numpy_array_equal(result, expected, check_dtype=False)
  1542. @pytest.mark.parametrize('f', [lambda x: x.cov(), lambda x: x.corr()])
  1543. def test_no_flex(self, f):
  1544. # DataFrame methods (which do not call _flex_binary_moment())
  1545. results = [f(df) for df in self.df1s]
  1546. for (df, result) in zip(self.df1s, results):
  1547. tm.assert_index_equal(result.index, df.columns)
  1548. tm.assert_index_equal(result.columns, df.columns)
  1549. for i, result in enumerate(results):
  1550. if i > 0:
  1551. self.compare(result, results[0])
  1552. @pytest.mark.parametrize(
  1553. 'f', [lambda x: x.expanding().cov(pairwise=True),
  1554. lambda x: x.expanding().corr(pairwise=True),
  1555. lambda x: x.rolling(window=3).cov(pairwise=True),
  1556. lambda x: x.rolling(window=3).corr(pairwise=True),
  1557. lambda x: x.ewm(com=3).cov(pairwise=True),
  1558. lambda x: x.ewm(com=3).corr(pairwise=True)])
  1559. def test_pairwise_with_self(self, f):
  1560. # DataFrame with itself, pairwise=True
  1561. # note that we may construct the 1st level of the MI
  1562. # in a non-motononic way, so compare accordingly
  1563. results = []
  1564. for i, df in enumerate(self.df1s):
  1565. result = f(df)
  1566. tm.assert_index_equal(result.index.levels[0],
  1567. df.index,
  1568. check_names=False)
  1569. tm.assert_numpy_array_equal(safe_sort(result.index.levels[1]),
  1570. safe_sort(df.columns.unique()))
  1571. tm.assert_index_equal(result.columns, df.columns)
  1572. results.append(df)
  1573. for i, result in enumerate(results):
  1574. if i > 0:
  1575. self.compare(result, results[0])
  1576. @pytest.mark.parametrize(
  1577. 'f', [lambda x: x.expanding().cov(pairwise=False),
  1578. lambda x: x.expanding().corr(pairwise=False),
  1579. lambda x: x.rolling(window=3).cov(pairwise=False),
  1580. lambda x: x.rolling(window=3).corr(pairwise=False),
  1581. lambda x: x.ewm(com=3).cov(pairwise=False),
  1582. lambda x: x.ewm(com=3).corr(pairwise=False), ])
  1583. def test_no_pairwise_with_self(self, f):
  1584. # DataFrame with itself, pairwise=False
  1585. results = [f(df) for df in self.df1s]
  1586. for (df, result) in zip(self.df1s, results):
  1587. tm.assert_index_equal(result.index, df.index)
  1588. tm.assert_index_equal(result.columns, df.columns)
  1589. for i, result in enumerate(results):
  1590. if i > 0:
  1591. self.compare(result, results[0])
  1592. @pytest.mark.parametrize(
  1593. 'f', [lambda x, y: x.expanding().cov(y, pairwise=True),
  1594. lambda x, y: x.expanding().corr(y, pairwise=True),
  1595. lambda x, y: x.rolling(window=3).cov(y, pairwise=True),
  1596. lambda x, y: x.rolling(window=3).corr(y, pairwise=True),
  1597. lambda x, y: x.ewm(com=3).cov(y, pairwise=True),
  1598. lambda x, y: x.ewm(com=3).corr(y, pairwise=True), ])
  1599. def test_pairwise_with_other(self, f):
  1600. # DataFrame with another DataFrame, pairwise=True
  1601. results = [f(df, self.df2) for df in self.df1s]
  1602. for (df, result) in zip(self.df1s, results):
  1603. tm.assert_index_equal(result.index.levels[0],
  1604. df.index,
  1605. check_names=False)
  1606. tm.assert_numpy_array_equal(safe_sort(result.index.levels[1]),
  1607. safe_sort(self.df2.columns.unique()))
  1608. for i, result in enumerate(results):
  1609. if i > 0:
  1610. self.compare(result, results[0])
  1611. @pytest.mark.parametrize(
  1612. 'f', [lambda x, y: x.expanding().cov(y, pairwise=False),
  1613. lambda x, y: x.expanding().corr(y, pairwise=False),
  1614. lambda x, y: x.rolling(window=3).cov(y, pairwise=False),
  1615. lambda x, y: x.rolling(window=3).corr(y, pairwise=False),
  1616. lambda x, y: x.ewm(com=3).cov(y, pairwise=False),
  1617. lambda x, y: x.ewm(com=3).corr(y, pairwise=False), ])
  1618. def test_no_pairwise_with_other(self, f):
  1619. # DataFrame with another DataFrame, pairwise=False
  1620. results = [f(df, self.df2) if df.columns.is_unique else None
  1621. for df in self.df1s]
  1622. for (df, result) in zip(self.df1s, results):
  1623. if result is not None:
  1624. with catch_warnings(record=True):
  1625. warnings.simplefilter("ignore", RuntimeWarning)
  1626. # we can have int and str columns
  1627. expected_index = df.index.union(self.df2.index)
  1628. expected_columns = df.columns.union(self.df2.columns)
  1629. tm.assert_index_equal(result.index, expected_index)
  1630. tm.assert_index_equal(result.columns, expected_columns)
  1631. else:
  1632. with pytest.raises(ValueError,
  1633. match="'arg1' columns are not unique"):
  1634. f(df, self.df2)
  1635. with pytest.raises(ValueError,
  1636. match="'arg2' columns are not unique"):
  1637. f(self.df2, df)
  1638. @pytest.mark.parametrize(
  1639. 'f', [lambda x, y: x.expanding().cov(y),
  1640. lambda x, y: x.expanding().corr(y),
  1641. lambda x, y: x.rolling(window=3).cov(y),
  1642. lambda x, y: x.rolling(window=3).corr(y),
  1643. lambda x, y: x.ewm(com=3).cov(y),
  1644. lambda x, y: x.ewm(com=3).corr(y), ])
  1645. def test_pairwise_with_series(self, f):
  1646. # DataFrame with a Series
  1647. results = ([f(df, self.s) for df in self.df1s] +
  1648. [f(self.s, df) for df in self.df1s])
  1649. for (df, result) in zip(self.df1s, results):
  1650. tm.assert_index_equal(result.index, df.index)
  1651. tm.assert_index_equal(result.columns, df.columns)
  1652. for i, result in enumerate(results):
  1653. if i > 0:
  1654. self.compare(result, results[0])
  1655. # create the data only once as we are not setting it
  1656. def _create_consistency_data():
  1657. def create_series():
  1658. return [Series(),
  1659. Series([np.nan]),
  1660. Series([np.nan, np.nan]),
  1661. Series([3.]),
  1662. Series([np.nan, 3.]),
  1663. Series([3., np.nan]),
  1664. Series([1., 3.]),
  1665. Series([2., 2.]),
  1666. Series([3., 1.]),
  1667. Series([5., 5., 5., 5., np.nan, np.nan, np.nan, 5., 5., np.nan,
  1668. np.nan]),
  1669. Series([np.nan, 5., 5., 5., np.nan, np.nan, np.nan, 5., 5.,
  1670. np.nan, np.nan]),
  1671. Series([np.nan, np.nan, 5., 5., np.nan, np.nan, np.nan, 5., 5.,
  1672. np.nan, np.nan]),
  1673. Series([np.nan, 3., np.nan, 3., 4., 5., 6., np.nan, np.nan, 7.,
  1674. 12., 13., 14., 15.]),
  1675. Series([np.nan, 5., np.nan, 2., 4., 0., 9., np.nan, np.nan, 3.,
  1676. 12., 13., 14., 15.]),
  1677. Series([2., 3., np.nan, 3., 4., 5., 6., np.nan, np.nan, 7.,
  1678. 12., 13., 14., 15.]),
  1679. Series([2., 5., np.nan, 2., 4., 0., 9., np.nan, np.nan, 3.,
  1680. 12., 13., 14., 15.]),
  1681. Series(range(10)),
  1682. Series(range(20, 0, -2)), ]
  1683. def create_dataframes():
  1684. return ([DataFrame(),
  1685. DataFrame(columns=['a']),
  1686. DataFrame(columns=['a', 'a']),
  1687. DataFrame(columns=['a', 'b']),
  1688. DataFrame(np.arange(10).reshape((5, 2))),
  1689. DataFrame(np.arange(25).reshape((5, 5))),
  1690. DataFrame(np.arange(25).reshape((5, 5)),
  1691. columns=['a', 'b', 99, 'd', 'd'])] +
  1692. [DataFrame(s) for s in create_series()])
  1693. def is_constant(x):
  1694. values = x.values.ravel()
  1695. return len(set(values[notna(values)])) == 1
  1696. def no_nans(x):
  1697. return x.notna().all().all()
  1698. # data is a tuple(object, is_contant, no_nans)
  1699. data = create_series() + create_dataframes()
  1700. return [(x, is_constant(x), no_nans(x)) for x in data]
  1701. _consistency_data = _create_consistency_data()
  1702. def _rolling_consistency_cases():
  1703. for window in [1, 2, 3, 10, 20]:
  1704. for min_periods in {0, 1, 2, 3, 4, window}:
  1705. if min_periods and (min_periods > window):
  1706. continue
  1707. for center in [False, True]:
  1708. yield window, min_periods, center
  1709. class TestMomentsConsistency(Base):
  1710. base_functions = [
  1711. (lambda v: Series(v).count(), None, 'count'),
  1712. (lambda v: Series(v).max(), None, 'max'),
  1713. (lambda v: Series(v).min(), None, 'min'),
  1714. (lambda v: Series(v).sum(), None, 'sum'),
  1715. (lambda v: Series(v).mean(), None, 'mean'),
  1716. (lambda v: Series(v).std(), 1, 'std'),
  1717. (lambda v: Series(v).cov(Series(v)), None, 'cov'),
  1718. (lambda v: Series(v).corr(Series(v)), None, 'corr'),
  1719. (lambda v: Series(v).var(), 1, 'var'),
  1720. # restore once GH 8086 is fixed
  1721. # lambda v: Series(v).skew(), 3, 'skew'),
  1722. # (lambda v: Series(v).kurt(), 4, 'kurt'),
  1723. # restore once GH 8084 is fixed
  1724. # lambda v: Series(v).quantile(0.3), None, 'quantile'),
  1725. (lambda v: Series(v).median(), None, 'median'),
  1726. (np.nanmax, 1, 'max'),
  1727. (np.nanmin, 1, 'min'),
  1728. (np.nansum, 1, 'sum'),
  1729. (np.nanmean, 1, 'mean'),
  1730. (lambda v: np.nanstd(v, ddof=1), 1, 'std'),
  1731. (lambda v: np.nanvar(v, ddof=1), 1, 'var'),
  1732. (np.nanmedian, 1, 'median'),
  1733. ]
  1734. no_nan_functions = [
  1735. (np.max, None, 'max'),
  1736. (np.min, None, 'min'),
  1737. (np.sum, None, 'sum'),
  1738. (np.mean, None, 'mean'),
  1739. (lambda v: np.std(v, ddof=1), 1, 'std'),
  1740. (lambda v: np.var(v, ddof=1), 1, 'var'),
  1741. (np.median, None, 'median'),
  1742. ]
  1743. def _create_data(self):
  1744. super(TestMomentsConsistency, self)._create_data()
  1745. self.data = _consistency_data
  1746. def setup_method(self, method):
  1747. self._create_data()
  1748. def _test_moments_consistency(self, min_periods, count, mean, mock_mean,
  1749. corr, var_unbiased=None, std_unbiased=None,
  1750. cov_unbiased=None, var_biased=None,
  1751. std_biased=None, cov_biased=None,
  1752. var_debiasing_factors=None):
  1753. def _non_null_values(x):
  1754. values = x.values.ravel()
  1755. return set(values[notna(values)].tolist())
  1756. for (x, is_constant, no_nans) in self.data:
  1757. count_x = count(x)
  1758. mean_x = mean(x)
  1759. if mock_mean:
  1760. # check that mean equals mock_mean
  1761. expected = mock_mean(x)
  1762. assert_equal(mean_x, expected.astype('float64'))
  1763. # check that correlation of a series with itself is either 1 or NaN
  1764. corr_x_x = corr(x, x)
  1765. # assert _non_null_values(corr_x_x).issubset(set([1.]))
  1766. # restore once rolling_cov(x, x) is identically equal to var(x)
  1767. if is_constant:
  1768. exp = x.max() if isinstance(x, Series) else x.max().max()
  1769. # check mean of constant series
  1770. expected = x * np.nan
  1771. expected[count_x >= max(min_periods, 1)] = exp
  1772. assert_equal(mean_x, expected)
  1773. # check correlation of constant series with itself is NaN
  1774. expected[:] = np.nan
  1775. assert_equal(corr_x_x, expected)
  1776. if var_unbiased and var_biased and var_debiasing_factors:
  1777. # check variance debiasing factors
  1778. var_unbiased_x = var_unbiased(x)
  1779. var_biased_x = var_biased(x)
  1780. var_debiasing_factors_x = var_debiasing_factors(x)
  1781. assert_equal(var_unbiased_x, var_biased_x *
  1782. var_debiasing_factors_x)
  1783. for (std, var, cov) in [(std_biased, var_biased, cov_biased),
  1784. (std_unbiased, var_unbiased, cov_unbiased)
  1785. ]:
  1786. # check that var(x), std(x), and cov(x) are all >= 0
  1787. var_x = var(x)
  1788. std_x = std(x)
  1789. assert not (var_x < 0).any().any()
  1790. assert not (std_x < 0).any().any()
  1791. if cov:
  1792. cov_x_x = cov(x, x)
  1793. assert not (cov_x_x < 0).any().any()
  1794. # check that var(x) == cov(x, x)
  1795. assert_equal(var_x, cov_x_x)
  1796. # check that var(x) == std(x)^2
  1797. assert_equal(var_x, std_x * std_x)
  1798. if var is var_biased:
  1799. # check that biased var(x) == mean(x^2) - mean(x)^2
  1800. mean_x2 = mean(x * x)
  1801. assert_equal(var_x, mean_x2 - (mean_x * mean_x))
  1802. if is_constant:
  1803. # check that variance of constant series is identically 0
  1804. assert not (var_x > 0).any().any()
  1805. expected = x * np.nan
  1806. expected[count_x >= max(min_periods, 1)] = 0.
  1807. if var is var_unbiased:
  1808. expected[count_x < 2] = np.nan
  1809. assert_equal(var_x, expected)
  1810. if isinstance(x, Series):
  1811. for (y, is_constant, no_nans) in self.data:
  1812. if not x.isna().equals(y.isna()):
  1813. # can only easily test two Series with similar
  1814. # structure
  1815. continue
  1816. # check that cor(x, y) is symmetric
  1817. corr_x_y = corr(x, y)
  1818. corr_y_x = corr(y, x)
  1819. assert_equal(corr_x_y, corr_y_x)
  1820. if cov:
  1821. # check that cov(x, y) is symmetric
  1822. cov_x_y = cov(x, y)
  1823. cov_y_x = cov(y, x)
  1824. assert_equal(cov_x_y, cov_y_x)
  1825. # check that cov(x, y) == (var(x+y) - var(x) -
  1826. # var(y)) / 2
  1827. var_x_plus_y = var(x + y)
  1828. var_y = var(y)
  1829. assert_equal(cov_x_y, 0.5 *
  1830. (var_x_plus_y - var_x - var_y))
  1831. # check that corr(x, y) == cov(x, y) / (std(x) *
  1832. # std(y))
  1833. std_y = std(y)
  1834. assert_equal(corr_x_y, cov_x_y / (std_x * std_y))
  1835. if cov is cov_biased:
  1836. # check that biased cov(x, y) == mean(x*y) -
  1837. # mean(x)*mean(y)
  1838. mean_y = mean(y)
  1839. mean_x_times_y = mean(x * y)
  1840. assert_equal(cov_x_y, mean_x_times_y -
  1841. (mean_x * mean_y))
  1842. @pytest.mark.slow
  1843. @pytest.mark.parametrize('min_periods', [0, 1, 2, 3, 4])
  1844. @pytest.mark.parametrize('adjust', [True, False])
  1845. @pytest.mark.parametrize('ignore_na', [True, False])
  1846. def test_ewm_consistency(self, min_periods, adjust, ignore_na):
  1847. def _weights(s, com, adjust, ignore_na):
  1848. if isinstance(s, DataFrame):
  1849. if not len(s.columns):
  1850. return DataFrame(index=s.index, columns=s.columns)
  1851. w = concat([
  1852. _weights(s.iloc[:, i], com=com, adjust=adjust,
  1853. ignore_na=ignore_na)
  1854. for i, _ in enumerate(s.columns)], axis=1)
  1855. w.index = s.index
  1856. w.columns = s.columns
  1857. return w
  1858. w = Series(np.nan, index=s.index)
  1859. alpha = 1. / (1. + com)
  1860. if ignore_na:
  1861. w[s.notna()] = _weights(s[s.notna()], com=com,
  1862. adjust=adjust, ignore_na=False)
  1863. elif adjust:
  1864. for i in range(len(s)):
  1865. if s.iat[i] == s.iat[i]:
  1866. w.iat[i] = pow(1. / (1. - alpha), i)
  1867. else:
  1868. sum_wts = 0.
  1869. prev_i = -1
  1870. for i in range(len(s)):
  1871. if s.iat[i] == s.iat[i]:
  1872. if prev_i == -1:
  1873. w.iat[i] = 1.
  1874. else:
  1875. w.iat[i] = alpha * sum_wts / pow(1. - alpha,
  1876. i - prev_i)
  1877. sum_wts += w.iat[i]
  1878. prev_i = i
  1879. return w
  1880. def _variance_debiasing_factors(s, com, adjust, ignore_na):
  1881. weights = _weights(s, com=com, adjust=adjust, ignore_na=ignore_na)
  1882. cum_sum = weights.cumsum().fillna(method='ffill')
  1883. cum_sum_sq = (weights * weights).cumsum().fillna(method='ffill')
  1884. numerator = cum_sum * cum_sum
  1885. denominator = numerator - cum_sum_sq
  1886. denominator[denominator <= 0.] = np.nan
  1887. return numerator / denominator
  1888. def _ewma(s, com, min_periods, adjust, ignore_na):
  1889. weights = _weights(s, com=com, adjust=adjust, ignore_na=ignore_na)
  1890. result = s.multiply(weights).cumsum().divide(weights.cumsum(
  1891. )).fillna(method='ffill')
  1892. result[s.expanding().count() < (max(min_periods, 1) if min_periods
  1893. else 1)] = np.nan
  1894. return result
  1895. com = 3.
  1896. # test consistency between different ewm* moments
  1897. self._test_moments_consistency(
  1898. min_periods=min_periods,
  1899. count=lambda x: x.expanding().count(),
  1900. mean=lambda x: x.ewm(com=com, min_periods=min_periods,
  1901. adjust=adjust,
  1902. ignore_na=ignore_na).mean(),
  1903. mock_mean=lambda x: _ewma(x, com=com,
  1904. min_periods=min_periods,
  1905. adjust=adjust,
  1906. ignore_na=ignore_na),
  1907. corr=lambda x, y: x.ewm(com=com, min_periods=min_periods,
  1908. adjust=adjust,
  1909. ignore_na=ignore_na).corr(y),
  1910. var_unbiased=lambda x: (
  1911. x.ewm(com=com, min_periods=min_periods,
  1912. adjust=adjust,
  1913. ignore_na=ignore_na).var(bias=False)),
  1914. std_unbiased=lambda x: (
  1915. x.ewm(com=com, min_periods=min_periods,
  1916. adjust=adjust, ignore_na=ignore_na)
  1917. .std(bias=False)),
  1918. cov_unbiased=lambda x, y: (
  1919. x.ewm(com=com, min_periods=min_periods,
  1920. adjust=adjust, ignore_na=ignore_na)
  1921. .cov(y, bias=False)),
  1922. var_biased=lambda x: (
  1923. x.ewm(com=com, min_periods=min_periods,
  1924. adjust=adjust, ignore_na=ignore_na)
  1925. .var(bias=True)),
  1926. std_biased=lambda x: x.ewm(com=com, min_periods=min_periods,
  1927. adjust=adjust,
  1928. ignore_na=ignore_na).std(bias=True),
  1929. cov_biased=lambda x, y: (
  1930. x.ewm(com=com, min_periods=min_periods,
  1931. adjust=adjust, ignore_na=ignore_na)
  1932. .cov(y, bias=True)),
  1933. var_debiasing_factors=lambda x: (
  1934. _variance_debiasing_factors(x, com=com, adjust=adjust,
  1935. ignore_na=ignore_na)))
  1936. @pytest.mark.slow
  1937. @pytest.mark.parametrize(
  1938. 'min_periods', [0, 1, 2, 3, 4])
  1939. def test_expanding_consistency(self, min_periods):
  1940. # suppress warnings about empty slices, as we are deliberately testing
  1941. # with empty/0-length Series/DataFrames
  1942. with warnings.catch_warnings():
  1943. warnings.filterwarnings("ignore",
  1944. message=".*(empty slice|0 for slice).*",
  1945. category=RuntimeWarning)
  1946. # test consistency between different expanding_* moments
  1947. self._test_moments_consistency(
  1948. min_periods=min_periods,
  1949. count=lambda x: x.expanding().count(),
  1950. mean=lambda x: x.expanding(
  1951. min_periods=min_periods).mean(),
  1952. mock_mean=lambda x: x.expanding(
  1953. min_periods=min_periods).sum() / x.expanding().count(),
  1954. corr=lambda x, y: x.expanding(
  1955. min_periods=min_periods).corr(y),
  1956. var_unbiased=lambda x: x.expanding(
  1957. min_periods=min_periods).var(),
  1958. std_unbiased=lambda x: x.expanding(
  1959. min_periods=min_periods).std(),
  1960. cov_unbiased=lambda x, y: x.expanding(
  1961. min_periods=min_periods).cov(y),
  1962. var_biased=lambda x: x.expanding(
  1963. min_periods=min_periods).var(ddof=0),
  1964. std_biased=lambda x: x.expanding(
  1965. min_periods=min_periods).std(ddof=0),
  1966. cov_biased=lambda x, y: x.expanding(
  1967. min_periods=min_periods).cov(y, ddof=0),
  1968. var_debiasing_factors=lambda x: (
  1969. x.expanding().count() /
  1970. (x.expanding().count() - 1.)
  1971. .replace(0., np.nan)))
  1972. # test consistency between expanding_xyz() and either (a)
  1973. # expanding_apply of Series.xyz(), or (b) expanding_apply of
  1974. # np.nanxyz()
  1975. for (x, is_constant, no_nans) in self.data:
  1976. functions = self.base_functions
  1977. # GH 8269
  1978. if no_nans:
  1979. functions = self.base_functions + self.no_nan_functions
  1980. for (f, require_min_periods, name) in functions:
  1981. expanding_f = getattr(
  1982. x.expanding(min_periods=min_periods), name)
  1983. if (require_min_periods and
  1984. (min_periods is not None) and
  1985. (min_periods < require_min_periods)):
  1986. continue
  1987. if name == 'count':
  1988. expanding_f_result = expanding_f()
  1989. expanding_apply_f_result = x.expanding(
  1990. min_periods=0).apply(func=f, raw=True)
  1991. else:
  1992. if name in ['cov', 'corr']:
  1993. expanding_f_result = expanding_f(
  1994. pairwise=False)
  1995. else:
  1996. expanding_f_result = expanding_f()
  1997. expanding_apply_f_result = x.expanding(
  1998. min_periods=min_periods).apply(func=f, raw=True)
  1999. # GH 9422
  2000. if name in ['sum', 'prod']:
  2001. assert_equal(expanding_f_result,
  2002. expanding_apply_f_result)
  2003. @pytest.mark.slow
  2004. @pytest.mark.parametrize(
  2005. 'window,min_periods,center', list(_rolling_consistency_cases()))
  2006. def test_rolling_consistency(self, window, min_periods, center):
  2007. # suppress warnings about empty slices, as we are deliberately testing
  2008. # with empty/0-length Series/DataFrames
  2009. with warnings.catch_warnings():
  2010. warnings.filterwarnings("ignore",
  2011. message=".*(empty slice|0 for slice).*",
  2012. category=RuntimeWarning)
  2013. # test consistency between different rolling_* moments
  2014. self._test_moments_consistency(
  2015. min_periods=min_periods,
  2016. count=lambda x: (
  2017. x.rolling(window=window, center=center)
  2018. .count()),
  2019. mean=lambda x: (
  2020. x.rolling(window=window, min_periods=min_periods,
  2021. center=center).mean()),
  2022. mock_mean=lambda x: (
  2023. x.rolling(window=window,
  2024. min_periods=min_periods,
  2025. center=center).sum()
  2026. .divide(x.rolling(window=window,
  2027. min_periods=min_periods,
  2028. center=center).count())),
  2029. corr=lambda x, y: (
  2030. x.rolling(window=window, min_periods=min_periods,
  2031. center=center).corr(y)),
  2032. var_unbiased=lambda x: (
  2033. x.rolling(window=window, min_periods=min_periods,
  2034. center=center).var()),
  2035. std_unbiased=lambda x: (
  2036. x.rolling(window=window, min_periods=min_periods,
  2037. center=center).std()),
  2038. cov_unbiased=lambda x, y: (
  2039. x.rolling(window=window, min_periods=min_periods,
  2040. center=center).cov(y)),
  2041. var_biased=lambda x: (
  2042. x.rolling(window=window, min_periods=min_periods,
  2043. center=center).var(ddof=0)),
  2044. std_biased=lambda x: (
  2045. x.rolling(window=window, min_periods=min_periods,
  2046. center=center).std(ddof=0)),
  2047. cov_biased=lambda x, y: (
  2048. x.rolling(window=window, min_periods=min_periods,
  2049. center=center).cov(y, ddof=0)),
  2050. var_debiasing_factors=lambda x: (
  2051. x.rolling(window=window, center=center).count()
  2052. .divide((x.rolling(window=window, center=center)
  2053. .count() - 1.)
  2054. .replace(0., np.nan))))
  2055. # test consistency between rolling_xyz() and either (a)
  2056. # rolling_apply of Series.xyz(), or (b) rolling_apply of
  2057. # np.nanxyz()
  2058. for (x, is_constant, no_nans) in self.data:
  2059. functions = self.base_functions
  2060. # GH 8269
  2061. if no_nans:
  2062. functions = self.base_functions + self.no_nan_functions
  2063. for (f, require_min_periods, name) in functions:
  2064. rolling_f = getattr(
  2065. x.rolling(window=window, center=center,
  2066. min_periods=min_periods), name)
  2067. if require_min_periods and (
  2068. min_periods is not None) and (
  2069. min_periods < require_min_periods):
  2070. continue
  2071. if name == 'count':
  2072. rolling_f_result = rolling_f()
  2073. rolling_apply_f_result = x.rolling(
  2074. window=window, min_periods=0,
  2075. center=center).apply(func=f, raw=True)
  2076. else:
  2077. if name in ['cov', 'corr']:
  2078. rolling_f_result = rolling_f(
  2079. pairwise=False)
  2080. else:
  2081. rolling_f_result = rolling_f()
  2082. rolling_apply_f_result = x.rolling(
  2083. window=window, min_periods=min_periods,
  2084. center=center).apply(func=f, raw=True)
  2085. # GH 9422
  2086. if name in ['sum', 'prod']:
  2087. assert_equal(rolling_f_result,
  2088. rolling_apply_f_result)
  2089. # binary moments
  2090. def test_rolling_cov(self):
  2091. A = self.series
  2092. B = A + randn(len(A))
  2093. result = A.rolling(window=50, min_periods=25).cov(B)
  2094. tm.assert_almost_equal(result[-1], np.cov(A[-50:], B[-50:])[0, 1])
  2095. def test_rolling_cov_pairwise(self):
  2096. self._check_pairwise_moment('rolling', 'cov', window=10, min_periods=5)
  2097. def test_rolling_corr(self):
  2098. A = self.series
  2099. B = A + randn(len(A))
  2100. result = A.rolling(window=50, min_periods=25).corr(B)
  2101. tm.assert_almost_equal(result[-1], np.corrcoef(A[-50:], B[-50:])[0, 1])
  2102. # test for correct bias correction
  2103. a = tm.makeTimeSeries()
  2104. b = tm.makeTimeSeries()
  2105. a[:5] = np.nan
  2106. b[:10] = np.nan
  2107. result = a.rolling(window=len(a), min_periods=1).corr(b)
  2108. tm.assert_almost_equal(result[-1], a.corr(b))
  2109. def test_rolling_corr_pairwise(self):
  2110. self._check_pairwise_moment('rolling', 'corr', window=10,
  2111. min_periods=5)
  2112. @pytest.mark.parametrize('window', range(7))
  2113. def test_rolling_corr_with_zero_variance(self, window):
  2114. # GH 18430
  2115. s = pd.Series(np.zeros(20))
  2116. other = pd.Series(np.arange(20))
  2117. assert s.rolling(window=window).corr(other=other).isna().all()
  2118. def _check_pairwise_moment(self, dispatch, name, **kwargs):
  2119. def get_result(obj, obj2=None):
  2120. return getattr(getattr(obj, dispatch)(**kwargs), name)(obj2)
  2121. result = get_result(self.frame)
  2122. result = result.loc[(slice(None), 1), 5]
  2123. result.index = result.index.droplevel(1)
  2124. expected = get_result(self.frame[1], self.frame[5])
  2125. tm.assert_series_equal(result, expected, check_names=False)
  2126. def test_flex_binary_moment(self):
  2127. # GH3155
  2128. # don't blow the stack
  2129. pytest.raises(TypeError, rwindow._flex_binary_moment, 5, 6, None)
  2130. def test_corr_sanity(self):
  2131. # GH 3155
  2132. df = DataFrame(np.array(
  2133. [[0.87024726, 0.18505595], [0.64355431, 0.3091617],
  2134. [0.92372966, 0.50552513], [0.00203756, 0.04520709],
  2135. [0.84780328, 0.33394331], [0.78369152, 0.63919667]]))
  2136. res = df[0].rolling(5, center=True).corr(df[1])
  2137. assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res)
  2138. # and some fuzzing
  2139. for _ in range(10):
  2140. df = DataFrame(np.random.rand(30, 2))
  2141. res = df[0].rolling(5, center=True).corr(df[1])
  2142. try:
  2143. assert all(np.abs(np.nan_to_num(x)) <= 1 for x in res)
  2144. except AssertionError:
  2145. print(res)
  2146. @pytest.mark.parametrize('method', ['corr', 'cov'])
  2147. def test_flex_binary_frame(self, method):
  2148. series = self.frame[1]
  2149. res = getattr(series.rolling(window=10), method)(self.frame)
  2150. res2 = getattr(self.frame.rolling(window=10), method)(series)
  2151. exp = self.frame.apply(lambda x: getattr(
  2152. series.rolling(window=10), method)(x))
  2153. tm.assert_frame_equal(res, exp)
  2154. tm.assert_frame_equal(res2, exp)
  2155. frame2 = self.frame.copy()
  2156. frame2.values[:] = np.random.randn(*frame2.shape)
  2157. res3 = getattr(self.frame.rolling(window=10), method)(frame2)
  2158. exp = DataFrame({k: getattr(self.frame[k].rolling(
  2159. window=10), method)(frame2[k]) for k in self.frame})
  2160. tm.assert_frame_equal(res3, exp)
  2161. def test_ewmcov(self):
  2162. self._check_binary_ew('cov')
  2163. def test_ewmcov_pairwise(self):
  2164. self._check_pairwise_moment('ewm', 'cov', span=10, min_periods=5)
  2165. def test_ewmcorr(self):
  2166. self._check_binary_ew('corr')
  2167. def test_ewmcorr_pairwise(self):
  2168. self._check_pairwise_moment('ewm', 'corr', span=10, min_periods=5)
  2169. def _check_binary_ew(self, name):
  2170. def func(A, B, com, **kwargs):
  2171. return getattr(A.ewm(com, **kwargs), name)(B)
  2172. A = Series(randn(50), index=np.arange(50))
  2173. B = A[2:] + randn(48)
  2174. A[:10] = np.NaN
  2175. B[-10:] = np.NaN
  2176. result = func(A, B, 20, min_periods=5)
  2177. assert np.isnan(result.values[:14]).all()
  2178. assert not np.isnan(result.values[14:]).any()
  2179. # GH 7898
  2180. for min_periods in (0, 1, 2):
  2181. result = func(A, B, 20, min_periods=min_periods)
  2182. # binary functions (ewmcov, ewmcorr) with bias=False require at
  2183. # least two values
  2184. assert np.isnan(result.values[:11]).all()
  2185. assert not np.isnan(result.values[11:]).any()
  2186. # check series of length 0
  2187. result = func(Series([]), Series([]), 50, min_periods=min_periods)
  2188. tm.assert_series_equal(result, Series([]))
  2189. # check series of length 1
  2190. result = func(
  2191. Series([1.]), Series([1.]), 50, min_periods=min_periods)
  2192. tm.assert_series_equal(result, Series([np.NaN]))
  2193. pytest.raises(Exception, func, A, randn(50), 20, min_periods=5)
  2194. def test_expanding_apply_args_kwargs(self, raw):
  2195. def mean_w_arg(x, const):
  2196. return np.mean(x) + const
  2197. df = DataFrame(np.random.rand(20, 3))
  2198. expected = df.expanding().apply(np.mean, raw=raw) + 20.
  2199. result = df.expanding().apply(mean_w_arg,
  2200. raw=raw,
  2201. args=(20, ))
  2202. tm.assert_frame_equal(result, expected)
  2203. result = df.expanding().apply(mean_w_arg,
  2204. raw=raw,
  2205. kwargs={'const': 20})
  2206. tm.assert_frame_equal(result, expected)
  2207. def test_expanding_corr(self):
  2208. A = self.series.dropna()
  2209. B = (A + randn(len(A)))[:-5]
  2210. result = A.expanding().corr(B)
  2211. rolling_result = A.rolling(window=len(A), min_periods=1).corr(B)
  2212. tm.assert_almost_equal(rolling_result, result)
  2213. def test_expanding_count(self):
  2214. result = self.series.expanding().count()
  2215. tm.assert_almost_equal(result, self.series.rolling(
  2216. window=len(self.series)).count())
  2217. def test_expanding_quantile(self):
  2218. result = self.series.expanding().quantile(0.5)
  2219. rolling_result = self.series.rolling(window=len(self.series),
  2220. min_periods=1).quantile(0.5)
  2221. tm.assert_almost_equal(result, rolling_result)
  2222. def test_expanding_cov(self):
  2223. A = self.series
  2224. B = (A + randn(len(A)))[:-5]
  2225. result = A.expanding().cov(B)
  2226. rolling_result = A.rolling(window=len(A), min_periods=1).cov(B)
  2227. tm.assert_almost_equal(rolling_result, result)
  2228. def test_expanding_cov_pairwise(self):
  2229. result = self.frame.expanding().corr()
  2230. rolling_result = self.frame.rolling(window=len(self.frame),
  2231. min_periods=1).corr()
  2232. tm.assert_frame_equal(result, rolling_result)
  2233. def test_expanding_corr_pairwise(self):
  2234. result = self.frame.expanding().corr()
  2235. rolling_result = self.frame.rolling(window=len(self.frame),
  2236. min_periods=1).corr()
  2237. tm.assert_frame_equal(result, rolling_result)
  2238. def test_expanding_cov_diff_index(self):
  2239. # GH 7512
  2240. s1 = Series([1, 2, 3], index=[0, 1, 2])
  2241. s2 = Series([1, 3], index=[0, 2])
  2242. result = s1.expanding().cov(s2)
  2243. expected = Series([None, None, 2.0])
  2244. tm.assert_series_equal(result, expected)
  2245. s2a = Series([1, None, 3], index=[0, 1, 2])
  2246. result = s1.expanding().cov(s2a)
  2247. tm.assert_series_equal(result, expected)
  2248. s1 = Series([7, 8, 10], index=[0, 1, 3])
  2249. s2 = Series([7, 9, 10], index=[0, 2, 3])
  2250. result = s1.expanding().cov(s2)
  2251. expected = Series([None, None, None, 4.5])
  2252. tm.assert_series_equal(result, expected)
  2253. def test_expanding_corr_diff_index(self):
  2254. # GH 7512
  2255. s1 = Series([1, 2, 3], index=[0, 1, 2])
  2256. s2 = Series([1, 3], index=[0, 2])
  2257. result = s1.expanding().corr(s2)
  2258. expected = Series([None, None, 1.0])
  2259. tm.assert_series_equal(result, expected)
  2260. s2a = Series([1, None, 3], index=[0, 1, 2])
  2261. result = s1.expanding().corr(s2a)
  2262. tm.assert_series_equal(result, expected)
  2263. s1 = Series([7, 8, 10], index=[0, 1, 3])
  2264. s2 = Series([7, 9, 10], index=[0, 2, 3])
  2265. result = s1.expanding().corr(s2)
  2266. expected = Series([None, None, None, 1.])
  2267. tm.assert_series_equal(result, expected)
  2268. def test_rolling_cov_diff_length(self):
  2269. # GH 7512
  2270. s1 = Series([1, 2, 3], index=[0, 1, 2])
  2271. s2 = Series([1, 3], index=[0, 2])
  2272. result = s1.rolling(window=3, min_periods=2).cov(s2)
  2273. expected = Series([None, None, 2.0])
  2274. tm.assert_series_equal(result, expected)
  2275. s2a = Series([1, None, 3], index=[0, 1, 2])
  2276. result = s1.rolling(window=3, min_periods=2).cov(s2a)
  2277. tm.assert_series_equal(result, expected)
  2278. def test_rolling_corr_diff_length(self):
  2279. # GH 7512
  2280. s1 = Series([1, 2, 3], index=[0, 1, 2])
  2281. s2 = Series([1, 3], index=[0, 2])
  2282. result = s1.rolling(window=3, min_periods=2).corr(s2)
  2283. expected = Series([None, None, 1.0])
  2284. tm.assert_series_equal(result, expected)
  2285. s2a = Series([1, None, 3], index=[0, 1, 2])
  2286. result = s1.rolling(window=3, min_periods=2).corr(s2a)
  2287. tm.assert_series_equal(result, expected)
  2288. @pytest.mark.parametrize(
  2289. 'f',
  2290. [
  2291. lambda x: (x.rolling(window=10, min_periods=5)
  2292. .cov(x, pairwise=False)),
  2293. lambda x: (x.rolling(window=10, min_periods=5)
  2294. .corr(x, pairwise=False)),
  2295. lambda x: x.rolling(window=10, min_periods=5).max(),
  2296. lambda x: x.rolling(window=10, min_periods=5).min(),
  2297. lambda x: x.rolling(window=10, min_periods=5).sum(),
  2298. lambda x: x.rolling(window=10, min_periods=5).mean(),
  2299. lambda x: x.rolling(window=10, min_periods=5).std(),
  2300. lambda x: x.rolling(window=10, min_periods=5).var(),
  2301. lambda x: x.rolling(window=10, min_periods=5).skew(),
  2302. lambda x: x.rolling(window=10, min_periods=5).kurt(),
  2303. lambda x: x.rolling(
  2304. window=10, min_periods=5).quantile(quantile=0.5),
  2305. lambda x: x.rolling(window=10, min_periods=5).median(),
  2306. lambda x: x.rolling(window=10, min_periods=5).apply(
  2307. sum, raw=False),
  2308. lambda x: x.rolling(window=10, min_periods=5).apply(
  2309. sum, raw=True),
  2310. lambda x: x.rolling(win_type='boxcar',
  2311. window=10, min_periods=5).mean()])
  2312. def test_rolling_functions_window_non_shrinkage(self, f):
  2313. # GH 7764
  2314. s = Series(range(4))
  2315. s_expected = Series(np.nan, index=s.index)
  2316. df = DataFrame([[1, 5], [3, 2], [3, 9], [-1, 0]], columns=['A', 'B'])
  2317. df_expected = DataFrame(np.nan, index=df.index, columns=df.columns)
  2318. try:
  2319. s_result = f(s)
  2320. tm.assert_series_equal(s_result, s_expected)
  2321. df_result = f(df)
  2322. tm.assert_frame_equal(df_result, df_expected)
  2323. except (ImportError):
  2324. # scipy needed for rolling_window
  2325. pytest.skip("scipy not available")
  2326. def test_rolling_functions_window_non_shrinkage_binary(self):
  2327. # corr/cov return a MI DataFrame
  2328. df = DataFrame([[1, 5], [3, 2], [3, 9], [-1, 0]],
  2329. columns=Index(['A', 'B'], name='foo'),
  2330. index=Index(range(4), name='bar'))
  2331. df_expected = DataFrame(
  2332. columns=Index(['A', 'B'], name='foo'),
  2333. index=pd.MultiIndex.from_product([df.index, df.columns],
  2334. names=['bar', 'foo']),
  2335. dtype='float64')
  2336. functions = [lambda x: (x.rolling(window=10, min_periods=5)
  2337. .cov(x, pairwise=True)),
  2338. lambda x: (x.rolling(window=10, min_periods=5)
  2339. .corr(x, pairwise=True))]
  2340. for f in functions:
  2341. df_result = f(df)
  2342. tm.assert_frame_equal(df_result, df_expected)
  2343. def test_moment_functions_zero_length(self):
  2344. # GH 8056
  2345. s = Series()
  2346. s_expected = s
  2347. df1 = DataFrame()
  2348. df1_expected = df1
  2349. df2 = DataFrame(columns=['a'])
  2350. df2['a'] = df2['a'].astype('float64')
  2351. df2_expected = df2
  2352. functions = [lambda x: x.expanding().count(),
  2353. lambda x: x.expanding(min_periods=5).cov(
  2354. x, pairwise=False),
  2355. lambda x: x.expanding(min_periods=5).corr(
  2356. x, pairwise=False),
  2357. lambda x: x.expanding(min_periods=5).max(),
  2358. lambda x: x.expanding(min_periods=5).min(),
  2359. lambda x: x.expanding(min_periods=5).sum(),
  2360. lambda x: x.expanding(min_periods=5).mean(),
  2361. lambda x: x.expanding(min_periods=5).std(),
  2362. lambda x: x.expanding(min_periods=5).var(),
  2363. lambda x: x.expanding(min_periods=5).skew(),
  2364. lambda x: x.expanding(min_periods=5).kurt(),
  2365. lambda x: x.expanding(min_periods=5).quantile(0.5),
  2366. lambda x: x.expanding(min_periods=5).median(),
  2367. lambda x: x.expanding(min_periods=5).apply(
  2368. sum, raw=False),
  2369. lambda x: x.expanding(min_periods=5).apply(
  2370. sum, raw=True),
  2371. lambda x: x.rolling(window=10).count(),
  2372. lambda x: x.rolling(window=10, min_periods=5).cov(
  2373. x, pairwise=False),
  2374. lambda x: x.rolling(window=10, min_periods=5).corr(
  2375. x, pairwise=False),
  2376. lambda x: x.rolling(window=10, min_periods=5).max(),
  2377. lambda x: x.rolling(window=10, min_periods=5).min(),
  2378. lambda x: x.rolling(window=10, min_periods=5).sum(),
  2379. lambda x: x.rolling(window=10, min_periods=5).mean(),
  2380. lambda x: x.rolling(window=10, min_periods=5).std(),
  2381. lambda x: x.rolling(window=10, min_periods=5).var(),
  2382. lambda x: x.rolling(window=10, min_periods=5).skew(),
  2383. lambda x: x.rolling(window=10, min_periods=5).kurt(),
  2384. lambda x: x.rolling(
  2385. window=10, min_periods=5).quantile(0.5),
  2386. lambda x: x.rolling(window=10, min_periods=5).median(),
  2387. lambda x: x.rolling(window=10, min_periods=5).apply(
  2388. sum, raw=False),
  2389. lambda x: x.rolling(window=10, min_periods=5).apply(
  2390. sum, raw=True),
  2391. lambda x: x.rolling(win_type='boxcar',
  2392. window=10, min_periods=5).mean(),
  2393. ]
  2394. for f in functions:
  2395. try:
  2396. s_result = f(s)
  2397. tm.assert_series_equal(s_result, s_expected)
  2398. df1_result = f(df1)
  2399. tm.assert_frame_equal(df1_result, df1_expected)
  2400. df2_result = f(df2)
  2401. tm.assert_frame_equal(df2_result, df2_expected)
  2402. except (ImportError):
  2403. # scipy needed for rolling_window
  2404. continue
  2405. def test_moment_functions_zero_length_pairwise(self):
  2406. df1 = DataFrame()
  2407. df1_expected = df1
  2408. df2 = DataFrame(columns=Index(['a'], name='foo'),
  2409. index=Index([], name='bar'))
  2410. df2['a'] = df2['a'].astype('float64')
  2411. df1_expected = DataFrame(
  2412. index=pd.MultiIndex.from_product([df1.index, df1.columns]),
  2413. columns=Index([]))
  2414. df2_expected = DataFrame(
  2415. index=pd.MultiIndex.from_product([df2.index, df2.columns],
  2416. names=['bar', 'foo']),
  2417. columns=Index(['a'], name='foo'),
  2418. dtype='float64')
  2419. functions = [lambda x: (x.expanding(min_periods=5)
  2420. .cov(x, pairwise=True)),
  2421. lambda x: (x.expanding(min_periods=5)
  2422. .corr(x, pairwise=True)),
  2423. lambda x: (x.rolling(window=10, min_periods=5)
  2424. .cov(x, pairwise=True)),
  2425. lambda x: (x.rolling(window=10, min_periods=5)
  2426. .corr(x, pairwise=True)),
  2427. ]
  2428. for f in functions:
  2429. df1_result = f(df1)
  2430. tm.assert_frame_equal(df1_result, df1_expected)
  2431. df2_result = f(df2)
  2432. tm.assert_frame_equal(df2_result, df2_expected)
  2433. def test_expanding_cov_pairwise_diff_length(self):
  2434. # GH 7512
  2435. df1 = DataFrame([[1, 5], [3, 2], [3, 9]],
  2436. columns=Index(['A', 'B'], name='foo'))
  2437. df1a = DataFrame([[1, 5], [3, 9]],
  2438. index=[0, 2],
  2439. columns=Index(['A', 'B'], name='foo'))
  2440. df2 = DataFrame([[5, 6], [None, None], [2, 1]],
  2441. columns=Index(['X', 'Y'], name='foo'))
  2442. df2a = DataFrame([[5, 6], [2, 1]],
  2443. index=[0, 2],
  2444. columns=Index(['X', 'Y'], name='foo'))
  2445. # TODO: xref gh-15826
  2446. # .loc is not preserving the names
  2447. result1 = df1.expanding().cov(df2a, pairwise=True).loc[2]
  2448. result2 = df1.expanding().cov(df2a, pairwise=True).loc[2]
  2449. result3 = df1a.expanding().cov(df2, pairwise=True).loc[2]
  2450. result4 = df1a.expanding().cov(df2a, pairwise=True).loc[2]
  2451. expected = DataFrame([[-3.0, -6.0], [-5.0, -10.0]],
  2452. columns=Index(['A', 'B'], name='foo'),
  2453. index=Index(['X', 'Y'], name='foo'))
  2454. tm.assert_frame_equal(result1, expected)
  2455. tm.assert_frame_equal(result2, expected)
  2456. tm.assert_frame_equal(result3, expected)
  2457. tm.assert_frame_equal(result4, expected)
  2458. def test_expanding_corr_pairwise_diff_length(self):
  2459. # GH 7512
  2460. df1 = DataFrame([[1, 2], [3, 2], [3, 4]],
  2461. columns=['A', 'B'],
  2462. index=Index(range(3), name='bar'))
  2463. df1a = DataFrame([[1, 2], [3, 4]],
  2464. index=Index([0, 2], name='bar'),
  2465. columns=['A', 'B'])
  2466. df2 = DataFrame([[5, 6], [None, None], [2, 1]],
  2467. columns=['X', 'Y'],
  2468. index=Index(range(3), name='bar'))
  2469. df2a = DataFrame([[5, 6], [2, 1]],
  2470. index=Index([0, 2], name='bar'),
  2471. columns=['X', 'Y'])
  2472. result1 = df1.expanding().corr(df2, pairwise=True).loc[2]
  2473. result2 = df1.expanding().corr(df2a, pairwise=True).loc[2]
  2474. result3 = df1a.expanding().corr(df2, pairwise=True).loc[2]
  2475. result4 = df1a.expanding().corr(df2a, pairwise=True).loc[2]
  2476. expected = DataFrame([[-1.0, -1.0], [-1.0, -1.0]],
  2477. columns=['A', 'B'],
  2478. index=Index(['X', 'Y']))
  2479. tm.assert_frame_equal(result1, expected)
  2480. tm.assert_frame_equal(result2, expected)
  2481. tm.assert_frame_equal(result3, expected)
  2482. tm.assert_frame_equal(result4, expected)
  2483. def test_rolling_skew_edge_cases(self):
  2484. all_nan = Series([np.NaN] * 5)
  2485. # yields all NaN (0 variance)
  2486. d = Series([1] * 5)
  2487. x = d.rolling(window=5).skew()
  2488. tm.assert_series_equal(all_nan, x)
  2489. # yields all NaN (window too small)
  2490. d = Series(np.random.randn(5))
  2491. x = d.rolling(window=2).skew()
  2492. tm.assert_series_equal(all_nan, x)
  2493. # yields [NaN, NaN, NaN, 0.177994, 1.548824]
  2494. d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401
  2495. ])
  2496. expected = Series([np.NaN, np.NaN, np.NaN, 0.177994, 1.548824])
  2497. x = d.rolling(window=4).skew()
  2498. tm.assert_series_equal(expected, x)
  2499. def test_rolling_kurt_edge_cases(self):
  2500. all_nan = Series([np.NaN] * 5)
  2501. # yields all NaN (0 variance)
  2502. d = Series([1] * 5)
  2503. x = d.rolling(window=5).kurt()
  2504. tm.assert_series_equal(all_nan, x)
  2505. # yields all NaN (window too small)
  2506. d = Series(np.random.randn(5))
  2507. x = d.rolling(window=3).kurt()
  2508. tm.assert_series_equal(all_nan, x)
  2509. # yields [NaN, NaN, NaN, 1.224307, 2.671499]
  2510. d = Series([-1.50837035, -0.1297039, 0.19501095, 1.73508164, 0.41941401
  2511. ])
  2512. expected = Series([np.NaN, np.NaN, np.NaN, 1.224307, 2.671499])
  2513. x = d.rolling(window=4).kurt()
  2514. tm.assert_series_equal(expected, x)
  2515. def test_rolling_skew_eq_value_fperr(self):
  2516. # #18804 all rolling skew for all equal values should return Nan
  2517. a = Series([1.1] * 15).rolling(window=10).skew()
  2518. assert np.isnan(a).all()
  2519. def test_rolling_kurt_eq_value_fperr(self):
  2520. # #18804 all rolling kurt for all equal values should return Nan
  2521. a = Series([1.1] * 15).rolling(window=10).kurt()
  2522. assert np.isnan(a).all()
  2523. @pytest.mark.parametrize('func,static_comp', [('sum', np.sum),
  2524. ('mean', np.mean),
  2525. ('max', np.max),
  2526. ('min', np.min)],
  2527. ids=['sum', 'mean', 'max', 'min'])
  2528. def test_expanding_func(self, func, static_comp):
  2529. def expanding_func(x, min_periods=1, center=False, axis=0):
  2530. exp = x.expanding(min_periods=min_periods,
  2531. center=center, axis=axis)
  2532. return getattr(exp, func)()
  2533. self._check_expanding(expanding_func, static_comp, preserve_nan=False)
  2534. def test_expanding_apply(self, raw):
  2535. def expanding_mean(x, min_periods=1):
  2536. exp = x.expanding(min_periods=min_periods)
  2537. result = exp.apply(lambda x: x.mean(), raw=raw)
  2538. return result
  2539. # TODO(jreback), needed to add preserve_nan=False
  2540. # here to make this pass
  2541. self._check_expanding(expanding_mean, np.mean, preserve_nan=False)
  2542. ser = Series([])
  2543. tm.assert_series_equal(ser, ser.expanding().apply(
  2544. lambda x: x.mean(), raw=raw))
  2545. # GH 8080
  2546. s = Series([None, None, None])
  2547. result = s.expanding(min_periods=0).apply(lambda x: len(x), raw=raw)
  2548. expected = Series([1., 2., 3.])
  2549. tm.assert_series_equal(result, expected)
  2550. def _check_expanding(self, func, static_comp, has_min_periods=True,
  2551. has_time_rule=True, preserve_nan=True):
  2552. series_result = func(self.series)
  2553. assert isinstance(series_result, Series)
  2554. frame_result = func(self.frame)
  2555. assert isinstance(frame_result, DataFrame)
  2556. result = func(self.series)
  2557. tm.assert_almost_equal(result[10], static_comp(self.series[:11]))
  2558. if preserve_nan:
  2559. assert result.iloc[self._nan_locs].isna().all()
  2560. ser = Series(randn(50))
  2561. if has_min_periods:
  2562. result = func(ser, min_periods=30)
  2563. assert result[:29].isna().all()
  2564. tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50]))
  2565. # min_periods is working correctly
  2566. result = func(ser, min_periods=15)
  2567. assert isna(result.iloc[13])
  2568. assert notna(result.iloc[14])
  2569. ser2 = Series(randn(20))
  2570. result = func(ser2, min_periods=5)
  2571. assert isna(result[3])
  2572. assert notna(result[4])
  2573. # min_periods=0
  2574. result0 = func(ser, min_periods=0)
  2575. result1 = func(ser, min_periods=1)
  2576. tm.assert_almost_equal(result0, result1)
  2577. else:
  2578. result = func(ser)
  2579. tm.assert_almost_equal(result.iloc[-1], static_comp(ser[:50]))
  2580. def test_rolling_max_gh6297(self):
  2581. """Replicate result expected in GH #6297"""
  2582. indices = [datetime(1975, 1, i) for i in range(1, 6)]
  2583. # So that we can have 2 datapoints on one of the days
  2584. indices.append(datetime(1975, 1, 3, 6, 0))
  2585. series = Series(range(1, 7), index=indices)
  2586. # Use floats instead of ints as values
  2587. series = series.map(lambda x: float(x))
  2588. # Sort chronologically
  2589. series = series.sort_index()
  2590. expected = Series([1.0, 2.0, 6.0, 4.0, 5.0],
  2591. index=[datetime(1975, 1, i, 0) for i in range(1, 6)])
  2592. x = series.resample('D').max().rolling(window=1).max()
  2593. tm.assert_series_equal(expected, x)
  2594. def test_rolling_max_resample(self):
  2595. indices = [datetime(1975, 1, i) for i in range(1, 6)]
  2596. # So that we can have 3 datapoints on last day (4, 10, and 20)
  2597. indices.append(datetime(1975, 1, 5, 1))
  2598. indices.append(datetime(1975, 1, 5, 2))
  2599. series = Series(list(range(0, 5)) + [10, 20], index=indices)
  2600. # Use floats instead of ints as values
  2601. series = series.map(lambda x: float(x))
  2602. # Sort chronologically
  2603. series = series.sort_index()
  2604. # Default how should be max
  2605. expected = Series([0.0, 1.0, 2.0, 3.0, 20.0],
  2606. index=[datetime(1975, 1, i, 0) for i in range(1, 6)])
  2607. x = series.resample('D').max().rolling(window=1).max()
  2608. tm.assert_series_equal(expected, x)
  2609. # Now specify median (10.0)
  2610. expected = Series([0.0, 1.0, 2.0, 3.0, 10.0],
  2611. index=[datetime(1975, 1, i, 0) for i in range(1, 6)])
  2612. x = series.resample('D').median().rolling(window=1).max()
  2613. tm.assert_series_equal(expected, x)
  2614. # Now specify mean (4+10+20)/3
  2615. v = (4.0 + 10.0 + 20.0) / 3.0
  2616. expected = Series([0.0, 1.0, 2.0, 3.0, v],
  2617. index=[datetime(1975, 1, i, 0) for i in range(1, 6)])
  2618. x = series.resample('D').mean().rolling(window=1).max()
  2619. tm.assert_series_equal(expected, x)
  2620. def test_rolling_min_resample(self):
  2621. indices = [datetime(1975, 1, i) for i in range(1, 6)]
  2622. # So that we can have 3 datapoints on last day (4, 10, and 20)
  2623. indices.append(datetime(1975, 1, 5, 1))
  2624. indices.append(datetime(1975, 1, 5, 2))
  2625. series = Series(list(range(0, 5)) + [10, 20], index=indices)
  2626. # Use floats instead of ints as values
  2627. series = series.map(lambda x: float(x))
  2628. # Sort chronologically
  2629. series = series.sort_index()
  2630. # Default how should be min
  2631. expected = Series([0.0, 1.0, 2.0, 3.0, 4.0],
  2632. index=[datetime(1975, 1, i, 0) for i in range(1, 6)])
  2633. r = series.resample('D').min().rolling(window=1)
  2634. tm.assert_series_equal(expected, r.min())
  2635. def test_rolling_median_resample(self):
  2636. indices = [datetime(1975, 1, i) for i in range(1, 6)]
  2637. # So that we can have 3 datapoints on last day (4, 10, and 20)
  2638. indices.append(datetime(1975, 1, 5, 1))
  2639. indices.append(datetime(1975, 1, 5, 2))
  2640. series = Series(list(range(0, 5)) + [10, 20], index=indices)
  2641. # Use floats instead of ints as values
  2642. series = series.map(lambda x: float(x))
  2643. # Sort chronologically
  2644. series = series.sort_index()
  2645. # Default how should be median
  2646. expected = Series([0.0, 1.0, 2.0, 3.0, 10],
  2647. index=[datetime(1975, 1, i, 0) for i in range(1, 6)])
  2648. x = series.resample('D').median().rolling(window=1).median()
  2649. tm.assert_series_equal(expected, x)
  2650. def test_rolling_median_memory_error(self):
  2651. # GH11722
  2652. n = 20000
  2653. Series(np.random.randn(n)).rolling(window=2, center=False).median()
  2654. Series(np.random.randn(n)).rolling(window=2, center=False).median()
  2655. def test_rolling_min_max_numeric_types(self):
  2656. # GH12373
  2657. types_test = [np.dtype("f{}".format(width)) for width in [4, 8]]
  2658. types_test.extend([np.dtype("{}{}".format(sign, width))
  2659. for width in [1, 2, 4, 8] for sign in "ui"])
  2660. for data_type in types_test:
  2661. # Just testing that these don't throw exceptions and that
  2662. # the return type is float64. Other tests will cover quantitative
  2663. # correctness
  2664. result = (DataFrame(np.arange(20, dtype=data_type))
  2665. .rolling(window=5).max())
  2666. assert result.dtypes[0] == np.dtype("f8")
  2667. result = (DataFrame(np.arange(20, dtype=data_type))
  2668. .rolling(window=5).min())
  2669. assert result.dtypes[0] == np.dtype("f8")
  2670. class TestGrouperGrouping(object):
  2671. def setup_method(self, method):
  2672. self.series = Series(np.arange(10))
  2673. self.frame = DataFrame({'A': [1] * 20 + [2] * 12 + [3] * 8,
  2674. 'B': np.arange(40)})
  2675. def test_mutated(self):
  2676. def f():
  2677. self.frame.groupby('A', foo=1)
  2678. pytest.raises(TypeError, f)
  2679. g = self.frame.groupby('A')
  2680. assert not g.mutated
  2681. g = self.frame.groupby('A', mutated=True)
  2682. assert g.mutated
  2683. def test_getitem(self):
  2684. g = self.frame.groupby('A')
  2685. g_mutated = self.frame.groupby('A', mutated=True)
  2686. expected = g_mutated.B.apply(lambda x: x.rolling(2).mean())
  2687. result = g.rolling(2).mean().B
  2688. tm.assert_series_equal(result, expected)
  2689. result = g.rolling(2).B.mean()
  2690. tm.assert_series_equal(result, expected)
  2691. result = g.B.rolling(2).mean()
  2692. tm.assert_series_equal(result, expected)
  2693. result = self.frame.B.groupby(self.frame.A).rolling(2).mean()
  2694. tm.assert_series_equal(result, expected)
  2695. def test_getitem_multiple(self):
  2696. # GH 13174
  2697. g = self.frame.groupby('A')
  2698. r = g.rolling(2)
  2699. g_mutated = self.frame.groupby('A', mutated=True)
  2700. expected = g_mutated.B.apply(lambda x: x.rolling(2).count())
  2701. result = r.B.count()
  2702. tm.assert_series_equal(result, expected)
  2703. result = r.B.count()
  2704. tm.assert_series_equal(result, expected)
  2705. def test_rolling(self):
  2706. g = self.frame.groupby('A')
  2707. r = g.rolling(window=4)
  2708. for f in ['sum', 'mean', 'min', 'max', 'count', 'kurt', 'skew']:
  2709. result = getattr(r, f)()
  2710. expected = g.apply(lambda x: getattr(x.rolling(4), f)())
  2711. tm.assert_frame_equal(result, expected)
  2712. for f in ['std', 'var']:
  2713. result = getattr(r, f)(ddof=1)
  2714. expected = g.apply(lambda x: getattr(x.rolling(4), f)(ddof=1))
  2715. tm.assert_frame_equal(result, expected)
  2716. result = r.quantile(0.5)
  2717. expected = g.apply(lambda x: x.rolling(4).quantile(0.5))
  2718. tm.assert_frame_equal(result, expected)
  2719. def test_rolling_corr_cov(self):
  2720. g = self.frame.groupby('A')
  2721. r = g.rolling(window=4)
  2722. for f in ['corr', 'cov']:
  2723. result = getattr(r, f)(self.frame)
  2724. def func(x):
  2725. return getattr(x.rolling(4), f)(self.frame)
  2726. expected = g.apply(func)
  2727. tm.assert_frame_equal(result, expected)
  2728. result = getattr(r.B, f)(pairwise=True)
  2729. def func(x):
  2730. return getattr(x.B.rolling(4), f)(pairwise=True)
  2731. expected = g.apply(func)
  2732. tm.assert_series_equal(result, expected)
  2733. def test_rolling_apply(self, raw):
  2734. g = self.frame.groupby('A')
  2735. r = g.rolling(window=4)
  2736. # reduction
  2737. result = r.apply(lambda x: x.sum(), raw=raw)
  2738. expected = g.apply(
  2739. lambda x: x.rolling(4).apply(lambda y: y.sum(), raw=raw))
  2740. tm.assert_frame_equal(result, expected)
  2741. def test_rolling_apply_mutability(self):
  2742. # GH 14013
  2743. df = pd.DataFrame({'A': ['foo'] * 3 + ['bar'] * 3, 'B': [1] * 6})
  2744. g = df.groupby('A')
  2745. mi = pd.MultiIndex.from_tuples([('bar', 3), ('bar', 4), ('bar', 5),
  2746. ('foo', 0), ('foo', 1), ('foo', 2)])
  2747. mi.names = ['A', None]
  2748. # Grouped column should not be a part of the output
  2749. expected = pd.DataFrame([np.nan, 2., 2.] * 2, columns=['B'], index=mi)
  2750. result = g.rolling(window=2).sum()
  2751. tm.assert_frame_equal(result, expected)
  2752. # Call an arbitrary function on the groupby
  2753. g.sum()
  2754. # Make sure nothing has been mutated
  2755. result = g.rolling(window=2).sum()
  2756. tm.assert_frame_equal(result, expected)
  2757. def test_expanding(self):
  2758. g = self.frame.groupby('A')
  2759. r = g.expanding()
  2760. for f in ['sum', 'mean', 'min', 'max', 'count', 'kurt', 'skew']:
  2761. result = getattr(r, f)()
  2762. expected = g.apply(lambda x: getattr(x.expanding(), f)())
  2763. tm.assert_frame_equal(result, expected)
  2764. for f in ['std', 'var']:
  2765. result = getattr(r, f)(ddof=0)
  2766. expected = g.apply(lambda x: getattr(x.expanding(), f)(ddof=0))
  2767. tm.assert_frame_equal(result, expected)
  2768. result = r.quantile(0.5)
  2769. expected = g.apply(lambda x: x.expanding().quantile(0.5))
  2770. tm.assert_frame_equal(result, expected)
  2771. def test_expanding_corr_cov(self):
  2772. g = self.frame.groupby('A')
  2773. r = g.expanding()
  2774. for f in ['corr', 'cov']:
  2775. result = getattr(r, f)(self.frame)
  2776. def func(x):
  2777. return getattr(x.expanding(), f)(self.frame)
  2778. expected = g.apply(func)
  2779. tm.assert_frame_equal(result, expected)
  2780. result = getattr(r.B, f)(pairwise=True)
  2781. def func(x):
  2782. return getattr(x.B.expanding(), f)(pairwise=True)
  2783. expected = g.apply(func)
  2784. tm.assert_series_equal(result, expected)
  2785. def test_expanding_apply(self, raw):
  2786. g = self.frame.groupby('A')
  2787. r = g.expanding()
  2788. # reduction
  2789. result = r.apply(lambda x: x.sum(), raw=raw)
  2790. expected = g.apply(
  2791. lambda x: x.expanding().apply(lambda y: y.sum(), raw=raw))
  2792. tm.assert_frame_equal(result, expected)
  2793. class TestRollingTS(object):
  2794. # rolling time-series friendly
  2795. # xref GH13327
  2796. def setup_method(self, method):
  2797. self.regular = DataFrame({'A': pd.date_range('20130101',
  2798. periods=5,
  2799. freq='s'),
  2800. 'B': range(5)}).set_index('A')
  2801. self.ragged = DataFrame({'B': range(5)})
  2802. self.ragged.index = [Timestamp('20130101 09:00:00'),
  2803. Timestamp('20130101 09:00:02'),
  2804. Timestamp('20130101 09:00:03'),
  2805. Timestamp('20130101 09:00:05'),
  2806. Timestamp('20130101 09:00:06')]
  2807. def test_doc_string(self):
  2808. df = DataFrame({'B': [0, 1, 2, np.nan, 4]},
  2809. index=[Timestamp('20130101 09:00:00'),
  2810. Timestamp('20130101 09:00:02'),
  2811. Timestamp('20130101 09:00:03'),
  2812. Timestamp('20130101 09:00:05'),
  2813. Timestamp('20130101 09:00:06')])
  2814. df
  2815. df.rolling('2s').sum()
  2816. def test_valid(self):
  2817. df = self.regular
  2818. # not a valid freq
  2819. with pytest.raises(ValueError):
  2820. df.rolling(window='foobar')
  2821. # not a datetimelike index
  2822. with pytest.raises(ValueError):
  2823. df.reset_index().rolling(window='foobar')
  2824. # non-fixed freqs
  2825. for freq in ['2MS', pd.offsets.MonthBegin(2)]:
  2826. with pytest.raises(ValueError):
  2827. df.rolling(window=freq)
  2828. for freq in ['1D', pd.offsets.Day(2), '2ms']:
  2829. df.rolling(window=freq)
  2830. # non-integer min_periods
  2831. for minp in [1.0, 'foo', np.array([1, 2, 3])]:
  2832. with pytest.raises(ValueError):
  2833. df.rolling(window='1D', min_periods=minp)
  2834. # center is not implemented
  2835. with pytest.raises(NotImplementedError):
  2836. df.rolling(window='1D', center=True)
  2837. def test_on(self):
  2838. df = self.regular
  2839. # not a valid column
  2840. with pytest.raises(ValueError):
  2841. df.rolling(window='2s', on='foobar')
  2842. # column is valid
  2843. df = df.copy()
  2844. df['C'] = pd.date_range('20130101', periods=len(df))
  2845. df.rolling(window='2d', on='C').sum()
  2846. # invalid columns
  2847. with pytest.raises(ValueError):
  2848. df.rolling(window='2d', on='B')
  2849. # ok even though on non-selected
  2850. df.rolling(window='2d', on='C').B.sum()
  2851. def test_monotonic_on(self):
  2852. # on/index must be monotonic
  2853. df = DataFrame({'A': pd.date_range('20130101',
  2854. periods=5,
  2855. freq='s'),
  2856. 'B': range(5)})
  2857. assert df.A.is_monotonic
  2858. df.rolling('2s', on='A').sum()
  2859. df = df.set_index('A')
  2860. assert df.index.is_monotonic
  2861. df.rolling('2s').sum()
  2862. # non-monotonic
  2863. df.index = reversed(df.index.tolist())
  2864. assert not df.index.is_monotonic
  2865. with pytest.raises(ValueError):
  2866. df.rolling('2s').sum()
  2867. df = df.reset_index()
  2868. with pytest.raises(ValueError):
  2869. df.rolling('2s', on='A').sum()
  2870. def test_frame_on(self):
  2871. df = DataFrame({'B': range(5),
  2872. 'C': pd.date_range('20130101 09:00:00',
  2873. periods=5,
  2874. freq='3s')})
  2875. df['A'] = [Timestamp('20130101 09:00:00'),
  2876. Timestamp('20130101 09:00:02'),
  2877. Timestamp('20130101 09:00:03'),
  2878. Timestamp('20130101 09:00:05'),
  2879. Timestamp('20130101 09:00:06')]
  2880. # we are doing simulating using 'on'
  2881. expected = (df.set_index('A')
  2882. .rolling('2s')
  2883. .B
  2884. .sum()
  2885. .reset_index(drop=True)
  2886. )
  2887. result = (df.rolling('2s', on='A')
  2888. .B
  2889. .sum()
  2890. )
  2891. tm.assert_series_equal(result, expected)
  2892. # test as a frame
  2893. # we should be ignoring the 'on' as an aggregation column
  2894. # note that the expected is setting, computing, and resetting
  2895. # so the columns need to be switched compared
  2896. # to the actual result where they are ordered as in the
  2897. # original
  2898. expected = (df.set_index('A')
  2899. .rolling('2s')[['B']]
  2900. .sum()
  2901. .reset_index()[['B', 'A']]
  2902. )
  2903. result = (df.rolling('2s', on='A')[['B']]
  2904. .sum()
  2905. )
  2906. tm.assert_frame_equal(result, expected)
  2907. def test_frame_on2(self):
  2908. # using multiple aggregation columns
  2909. df = DataFrame({'A': [0, 1, 2, 3, 4],
  2910. 'B': [0, 1, 2, np.nan, 4],
  2911. 'C': Index([Timestamp('20130101 09:00:00'),
  2912. Timestamp('20130101 09:00:02'),
  2913. Timestamp('20130101 09:00:03'),
  2914. Timestamp('20130101 09:00:05'),
  2915. Timestamp('20130101 09:00:06')])},
  2916. columns=['A', 'C', 'B'])
  2917. expected1 = DataFrame({'A': [0., 1, 3, 3, 7],
  2918. 'B': [0, 1, 3, np.nan, 4],
  2919. 'C': df['C']},
  2920. columns=['A', 'C', 'B'])
  2921. result = df.rolling('2s', on='C').sum()
  2922. expected = expected1
  2923. tm.assert_frame_equal(result, expected)
  2924. expected = Series([0, 1, 3, np.nan, 4], name='B')
  2925. result = df.rolling('2s', on='C').B.sum()
  2926. tm.assert_series_equal(result, expected)
  2927. expected = expected1[['A', 'B', 'C']]
  2928. result = df.rolling('2s', on='C')[['A', 'B', 'C']].sum()
  2929. tm.assert_frame_equal(result, expected)
  2930. def test_basic_regular(self):
  2931. df = self.regular.copy()
  2932. df.index = pd.date_range('20130101', periods=5, freq='D')
  2933. expected = df.rolling(window=1, min_periods=1).sum()
  2934. result = df.rolling(window='1D').sum()
  2935. tm.assert_frame_equal(result, expected)
  2936. df.index = pd.date_range('20130101', periods=5, freq='2D')
  2937. expected = df.rolling(window=1, min_periods=1).sum()
  2938. result = df.rolling(window='2D', min_periods=1).sum()
  2939. tm.assert_frame_equal(result, expected)
  2940. expected = df.rolling(window=1, min_periods=1).sum()
  2941. result = df.rolling(window='2D', min_periods=1).sum()
  2942. tm.assert_frame_equal(result, expected)
  2943. expected = df.rolling(window=1).sum()
  2944. result = df.rolling(window='2D').sum()
  2945. tm.assert_frame_equal(result, expected)
  2946. def test_min_periods(self):
  2947. # compare for min_periods
  2948. df = self.regular
  2949. # these slightly different
  2950. expected = df.rolling(2, min_periods=1).sum()
  2951. result = df.rolling('2s').sum()
  2952. tm.assert_frame_equal(result, expected)
  2953. expected = df.rolling(2, min_periods=1).sum()
  2954. result = df.rolling('2s', min_periods=1).sum()
  2955. tm.assert_frame_equal(result, expected)
  2956. def test_closed(self):
  2957. # xref GH13965
  2958. df = DataFrame({'A': [1] * 5},
  2959. index=[Timestamp('20130101 09:00:01'),
  2960. Timestamp('20130101 09:00:02'),
  2961. Timestamp('20130101 09:00:03'),
  2962. Timestamp('20130101 09:00:04'),
  2963. Timestamp('20130101 09:00:06')])
  2964. # closed must be 'right', 'left', 'both', 'neither'
  2965. with pytest.raises(ValueError):
  2966. self.regular.rolling(window='2s', closed="blabla")
  2967. expected = df.copy()
  2968. expected["A"] = [1.0, 2, 2, 2, 1]
  2969. result = df.rolling('2s', closed='right').sum()
  2970. tm.assert_frame_equal(result, expected)
  2971. # default should be 'right'
  2972. result = df.rolling('2s').sum()
  2973. tm.assert_frame_equal(result, expected)
  2974. expected = df.copy()
  2975. expected["A"] = [1.0, 2, 3, 3, 2]
  2976. result = df.rolling('2s', closed='both').sum()
  2977. tm.assert_frame_equal(result, expected)
  2978. expected = df.copy()
  2979. expected["A"] = [np.nan, 1.0, 2, 2, 1]
  2980. result = df.rolling('2s', closed='left').sum()
  2981. tm.assert_frame_equal(result, expected)
  2982. expected = df.copy()
  2983. expected["A"] = [np.nan, 1.0, 1, 1, np.nan]
  2984. result = df.rolling('2s', closed='neither').sum()
  2985. tm.assert_frame_equal(result, expected)
  2986. def test_ragged_sum(self):
  2987. df = self.ragged
  2988. result = df.rolling(window='1s', min_periods=1).sum()
  2989. expected = df.copy()
  2990. expected['B'] = [0.0, 1, 2, 3, 4]
  2991. tm.assert_frame_equal(result, expected)
  2992. result = df.rolling(window='2s', min_periods=1).sum()
  2993. expected = df.copy()
  2994. expected['B'] = [0.0, 1, 3, 3, 7]
  2995. tm.assert_frame_equal(result, expected)
  2996. result = df.rolling(window='2s', min_periods=2).sum()
  2997. expected = df.copy()
  2998. expected['B'] = [np.nan, np.nan, 3, np.nan, 7]
  2999. tm.assert_frame_equal(result, expected)
  3000. result = df.rolling(window='3s', min_periods=1).sum()
  3001. expected = df.copy()
  3002. expected['B'] = [0.0, 1, 3, 5, 7]
  3003. tm.assert_frame_equal(result, expected)
  3004. result = df.rolling(window='3s').sum()
  3005. expected = df.copy()
  3006. expected['B'] = [0.0, 1, 3, 5, 7]
  3007. tm.assert_frame_equal(result, expected)
  3008. result = df.rolling(window='4s', min_periods=1).sum()
  3009. expected = df.copy()
  3010. expected['B'] = [0.0, 1, 3, 6, 9]
  3011. tm.assert_frame_equal(result, expected)
  3012. result = df.rolling(window='4s', min_periods=3).sum()
  3013. expected = df.copy()
  3014. expected['B'] = [np.nan, np.nan, 3, 6, 9]
  3015. tm.assert_frame_equal(result, expected)
  3016. result = df.rolling(window='5s', min_periods=1).sum()
  3017. expected = df.copy()
  3018. expected['B'] = [0.0, 1, 3, 6, 10]
  3019. tm.assert_frame_equal(result, expected)
  3020. def test_ragged_mean(self):
  3021. df = self.ragged
  3022. result = df.rolling(window='1s', min_periods=1).mean()
  3023. expected = df.copy()
  3024. expected['B'] = [0.0, 1, 2, 3, 4]
  3025. tm.assert_frame_equal(result, expected)
  3026. result = df.rolling(window='2s', min_periods=1).mean()
  3027. expected = df.copy()
  3028. expected['B'] = [0.0, 1, 1.5, 3.0, 3.5]
  3029. tm.assert_frame_equal(result, expected)
  3030. def test_ragged_median(self):
  3031. df = self.ragged
  3032. result = df.rolling(window='1s', min_periods=1).median()
  3033. expected = df.copy()
  3034. expected['B'] = [0.0, 1, 2, 3, 4]
  3035. tm.assert_frame_equal(result, expected)
  3036. result = df.rolling(window='2s', min_periods=1).median()
  3037. expected = df.copy()
  3038. expected['B'] = [0.0, 1, 1.5, 3.0, 3.5]
  3039. tm.assert_frame_equal(result, expected)
  3040. def test_ragged_quantile(self):
  3041. df = self.ragged
  3042. result = df.rolling(window='1s', min_periods=1).quantile(0.5)
  3043. expected = df.copy()
  3044. expected['B'] = [0.0, 1, 2, 3, 4]
  3045. tm.assert_frame_equal(result, expected)
  3046. result = df.rolling(window='2s', min_periods=1).quantile(0.5)
  3047. expected = df.copy()
  3048. expected['B'] = [0.0, 1, 1.5, 3.0, 3.5]
  3049. tm.assert_frame_equal(result, expected)
  3050. def test_ragged_std(self):
  3051. df = self.ragged
  3052. result = df.rolling(window='1s', min_periods=1).std(ddof=0)
  3053. expected = df.copy()
  3054. expected['B'] = [0.0] * 5
  3055. tm.assert_frame_equal(result, expected)
  3056. result = df.rolling(window='1s', min_periods=1).std(ddof=1)
  3057. expected = df.copy()
  3058. expected['B'] = [np.nan] * 5
  3059. tm.assert_frame_equal(result, expected)
  3060. result = df.rolling(window='3s', min_periods=1).std(ddof=0)
  3061. expected = df.copy()
  3062. expected['B'] = [0.0] + [0.5] * 4
  3063. tm.assert_frame_equal(result, expected)
  3064. result = df.rolling(window='5s', min_periods=1).std(ddof=1)
  3065. expected = df.copy()
  3066. expected['B'] = [np.nan, 0.707107, 1.0, 1.0, 1.290994]
  3067. tm.assert_frame_equal(result, expected)
  3068. def test_ragged_var(self):
  3069. df = self.ragged
  3070. result = df.rolling(window='1s', min_periods=1).var(ddof=0)
  3071. expected = df.copy()
  3072. expected['B'] = [0.0] * 5
  3073. tm.assert_frame_equal(result, expected)
  3074. result = df.rolling(window='1s', min_periods=1).var(ddof=1)
  3075. expected = df.copy()
  3076. expected['B'] = [np.nan] * 5
  3077. tm.assert_frame_equal(result, expected)
  3078. result = df.rolling(window='3s', min_periods=1).var(ddof=0)
  3079. expected = df.copy()
  3080. expected['B'] = [0.0] + [0.25] * 4
  3081. tm.assert_frame_equal(result, expected)
  3082. result = df.rolling(window='5s', min_periods=1).var(ddof=1)
  3083. expected = df.copy()
  3084. expected['B'] = [np.nan, 0.5, 1.0, 1.0, 1 + 2 / 3.]
  3085. tm.assert_frame_equal(result, expected)
  3086. def test_ragged_skew(self):
  3087. df = self.ragged
  3088. result = df.rolling(window='3s', min_periods=1).skew()
  3089. expected = df.copy()
  3090. expected['B'] = [np.nan] * 5
  3091. tm.assert_frame_equal(result, expected)
  3092. result = df.rolling(window='5s', min_periods=1).skew()
  3093. expected = df.copy()
  3094. expected['B'] = [np.nan] * 2 + [0.0, 0.0, 0.0]
  3095. tm.assert_frame_equal(result, expected)
  3096. def test_ragged_kurt(self):
  3097. df = self.ragged
  3098. result = df.rolling(window='3s', min_periods=1).kurt()
  3099. expected = df.copy()
  3100. expected['B'] = [np.nan] * 5
  3101. tm.assert_frame_equal(result, expected)
  3102. result = df.rolling(window='5s', min_periods=1).kurt()
  3103. expected = df.copy()
  3104. expected['B'] = [np.nan] * 4 + [-1.2]
  3105. tm.assert_frame_equal(result, expected)
  3106. def test_ragged_count(self):
  3107. df = self.ragged
  3108. result = df.rolling(window='1s', min_periods=1).count()
  3109. expected = df.copy()
  3110. expected['B'] = [1.0, 1, 1, 1, 1]
  3111. tm.assert_frame_equal(result, expected)
  3112. df = self.ragged
  3113. result = df.rolling(window='1s').count()
  3114. tm.assert_frame_equal(result, expected)
  3115. result = df.rolling(window='2s', min_periods=1).count()
  3116. expected = df.copy()
  3117. expected['B'] = [1.0, 1, 2, 1, 2]
  3118. tm.assert_frame_equal(result, expected)
  3119. result = df.rolling(window='2s', min_periods=2).count()
  3120. expected = df.copy()
  3121. expected['B'] = [np.nan, np.nan, 2, np.nan, 2]
  3122. tm.assert_frame_equal(result, expected)
  3123. def test_regular_min(self):
  3124. df = DataFrame({'A': pd.date_range('20130101',
  3125. periods=5,
  3126. freq='s'),
  3127. 'B': [0.0, 1, 2, 3, 4]}).set_index('A')
  3128. result = df.rolling('1s').min()
  3129. expected = df.copy()
  3130. expected['B'] = [0.0, 1, 2, 3, 4]
  3131. tm.assert_frame_equal(result, expected)
  3132. df = DataFrame({'A': pd.date_range('20130101',
  3133. periods=5,
  3134. freq='s'),
  3135. 'B': [5, 4, 3, 4, 5]}).set_index('A')
  3136. tm.assert_frame_equal(result, expected)
  3137. result = df.rolling('2s').min()
  3138. expected = df.copy()
  3139. expected['B'] = [5.0, 4, 3, 3, 4]
  3140. tm.assert_frame_equal(result, expected)
  3141. result = df.rolling('5s').min()
  3142. expected = df.copy()
  3143. expected['B'] = [5.0, 4, 3, 3, 3]
  3144. tm.assert_frame_equal(result, expected)
  3145. def test_ragged_min(self):
  3146. df = self.ragged
  3147. result = df.rolling(window='1s', min_periods=1).min()
  3148. expected = df.copy()
  3149. expected['B'] = [0.0, 1, 2, 3, 4]
  3150. tm.assert_frame_equal(result, expected)
  3151. result = df.rolling(window='2s', min_periods=1).min()
  3152. expected = df.copy()
  3153. expected['B'] = [0.0, 1, 1, 3, 3]
  3154. tm.assert_frame_equal(result, expected)
  3155. result = df.rolling(window='5s', min_periods=1).min()
  3156. expected = df.copy()
  3157. expected['B'] = [0.0, 0, 0, 1, 1]
  3158. tm.assert_frame_equal(result, expected)
  3159. def test_perf_min(self):
  3160. N = 10000
  3161. dfp = DataFrame({'B': np.random.randn(N)},
  3162. index=pd.date_range('20130101',
  3163. periods=N,
  3164. freq='s'))
  3165. expected = dfp.rolling(2, min_periods=1).min()
  3166. result = dfp.rolling('2s').min()
  3167. assert ((result - expected) < 0.01).all().bool()
  3168. expected = dfp.rolling(200, min_periods=1).min()
  3169. result = dfp.rolling('200s').min()
  3170. assert ((result - expected) < 0.01).all().bool()
  3171. def test_ragged_max(self):
  3172. df = self.ragged
  3173. result = df.rolling(window='1s', min_periods=1).max()
  3174. expected = df.copy()
  3175. expected['B'] = [0.0, 1, 2, 3, 4]
  3176. tm.assert_frame_equal(result, expected)
  3177. result = df.rolling(window='2s', min_periods=1).max()
  3178. expected = df.copy()
  3179. expected['B'] = [0.0, 1, 2, 3, 4]
  3180. tm.assert_frame_equal(result, expected)
  3181. result = df.rolling(window='5s', min_periods=1).max()
  3182. expected = df.copy()
  3183. expected['B'] = [0.0, 1, 2, 3, 4]
  3184. tm.assert_frame_equal(result, expected)
  3185. def test_ragged_apply(self, raw):
  3186. df = self.ragged
  3187. f = lambda x: 1
  3188. result = df.rolling(window='1s', min_periods=1).apply(f, raw=raw)
  3189. expected = df.copy()
  3190. expected['B'] = 1.
  3191. tm.assert_frame_equal(result, expected)
  3192. result = df.rolling(window='2s', min_periods=1).apply(f, raw=raw)
  3193. expected = df.copy()
  3194. expected['B'] = 1.
  3195. tm.assert_frame_equal(result, expected)
  3196. result = df.rolling(window='5s', min_periods=1).apply(f, raw=raw)
  3197. expected = df.copy()
  3198. expected['B'] = 1.
  3199. tm.assert_frame_equal(result, expected)
  3200. def test_all(self):
  3201. # simple comparison of integer vs time-based windowing
  3202. df = self.regular * 2
  3203. er = df.rolling(window=1)
  3204. r = df.rolling(window='1s')
  3205. for f in ['sum', 'mean', 'count', 'median', 'std',
  3206. 'var', 'kurt', 'skew', 'min', 'max']:
  3207. result = getattr(r, f)()
  3208. expected = getattr(er, f)()
  3209. tm.assert_frame_equal(result, expected)
  3210. result = r.quantile(0.5)
  3211. expected = er.quantile(0.5)
  3212. tm.assert_frame_equal(result, expected)
  3213. def test_all_apply(self, raw):
  3214. df = self.regular * 2
  3215. er = df.rolling(window=1)
  3216. r = df.rolling(window='1s')
  3217. result = r.apply(lambda x: 1, raw=raw)
  3218. expected = er.apply(lambda x: 1, raw=raw)
  3219. tm.assert_frame_equal(result, expected)
  3220. def test_all2(self):
  3221. # more sophisticated comparison of integer vs.
  3222. # time-based windowing
  3223. df = DataFrame({'B': np.arange(50)},
  3224. index=pd.date_range('20130101',
  3225. periods=50, freq='H')
  3226. )
  3227. # in-range data
  3228. dft = df.between_time("09:00", "16:00")
  3229. r = dft.rolling(window='5H')
  3230. for f in ['sum', 'mean', 'count', 'median', 'std',
  3231. 'var', 'kurt', 'skew', 'min', 'max']:
  3232. result = getattr(r, f)()
  3233. # we need to roll the days separately
  3234. # to compare with a time-based roll
  3235. # finally groupby-apply will return a multi-index
  3236. # so we need to drop the day
  3237. def agg_by_day(x):
  3238. x = x.between_time("09:00", "16:00")
  3239. return getattr(x.rolling(5, min_periods=1), f)()
  3240. expected = df.groupby(df.index.day).apply(
  3241. agg_by_day).reset_index(level=0, drop=True)
  3242. tm.assert_frame_equal(result, expected)
  3243. def test_groupby_monotonic(self):
  3244. # GH 15130
  3245. # we don't need to validate monotonicity when grouping
  3246. data = [
  3247. ['David', '1/1/2015', 100], ['David', '1/5/2015', 500],
  3248. ['David', '5/30/2015', 50], ['David', '7/25/2015', 50],
  3249. ['Ryan', '1/4/2014', 100], ['Ryan', '1/19/2015', 500],
  3250. ['Ryan', '3/31/2016', 50], ['Joe', '7/1/2015', 100],
  3251. ['Joe', '9/9/2015', 500], ['Joe', '10/15/2015', 50]]
  3252. df = DataFrame(data=data, columns=['name', 'date', 'amount'])
  3253. df['date'] = pd.to_datetime(df['date'])
  3254. expected = df.set_index('date').groupby('name').apply(
  3255. lambda x: x.rolling('180D')['amount'].sum())
  3256. result = df.groupby('name').rolling('180D', on='date')['amount'].sum()
  3257. tm.assert_series_equal(result, expected)
  3258. def test_non_monotonic(self):
  3259. # GH 13966 (similar to #15130, closed by #15175)
  3260. dates = pd.date_range(start='2016-01-01 09:30:00',
  3261. periods=20, freq='s')
  3262. df = DataFrame({'A': [1] * 20 + [2] * 12 + [3] * 8,
  3263. 'B': np.concatenate((dates, dates)),
  3264. 'C': np.arange(40)})
  3265. result = df.groupby('A').rolling('4s', on='B').C.mean()
  3266. expected = df.set_index('B').groupby('A').apply(
  3267. lambda x: x.rolling('4s')['C'].mean())
  3268. tm.assert_series_equal(result, expected)
  3269. df2 = df.sort_values('B')
  3270. result = df2.groupby('A').rolling('4s', on='B').C.mean()
  3271. tm.assert_series_equal(result, expected)
  3272. def test_rolling_cov_offset(self):
  3273. # GH16058
  3274. idx = pd.date_range('2017-01-01', periods=24, freq='1h')
  3275. ss = Series(np.arange(len(idx)), index=idx)
  3276. result = ss.rolling('2h').cov()
  3277. expected = Series([np.nan] + [0.5] * (len(idx) - 1), index=idx)
  3278. tm.assert_series_equal(result, expected)
  3279. expected2 = ss.rolling(2, min_periods=1).cov()
  3280. tm.assert_series_equal(result, expected2)
  3281. result = ss.rolling('3h').cov()
  3282. expected = Series([np.nan, 0.5] + [1.0] * (len(idx) - 2), index=idx)
  3283. tm.assert_series_equal(result, expected)
  3284. expected2 = ss.rolling(3, min_periods=1).cov()
  3285. tm.assert_series_equal(result, expected2)