finmathstudent
finmathstudent

Reputation: 189

Winning and losing streak using Pandas Python

May I get some help in replicating the function, with input a pandas series (daily series of closing-prices), below? It computes daily streaks.

cp = pd.Series(index=range(1,8+1), name='Closing_Price',
    data=[20.00, 20.50, 20.75, 19.75, 19.50, 19.35, 19.35, 19.40])

1    20.00
2    20.50
3    20.75
4    19.75
5    19.50
6    19.35
7    19.35
8    19.40

Interpretation is:

I think I will need cumsum() and groupby. Something like

def fxn(series):
    x = series.diff()

but I'm not sure how to proceed

Upvotes: 0

Views: 656

Answers (1)

finmathstudent
finmathstudent

Reputation: 189

Might this be the answer? Shout out to @smci for providing the much-needed and much-appreciated hints!!

def streak(x):
  c = x.copy()
  c['diff'] = c.diff()
  c['sign'] = c['diff'].apply(func = lambda y: y if not y else y // abs(y))
  grouper = (c['sign'] != c['sign'].shift()).cumsum()
  c['streak'] = c['sign'].groupby(grouper).cumsum()
  return c['streak']

Upvotes: 1

Related Questions