PageRenderTime 44ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/python/pandas_3.py

https://bitbucket.org/jaredlander/lab
Python | 69 lines | 43 code | 14 blank | 12 comment | 3 complexity | 7af60806a5b1edae7178292b9c93523e MD5 | raw file
  1. # pandas group by
  2. import numpy as np
  3. import pandas as pd
  4. import pandas.io.data as web
  5. from pandas import DataFrame
  6. def pct_change(x):
  7. return x / x.shift(1) - 1
  8. stocks = ['AAPL', 'FB', 'GOOG']
  9. st = '2012-6-1'
  10. ed = '2012-9-29'
  11. dd = {}
  12. for s in stocks:
  13. dd[s] = web.get_data_yahoo(s, st, ed)['Adj Close']
  14. df = DataFrame(dd)
  15. df.head()
  16. returns = df.pct_change()
  17. df.groupby(mapper).apply(zscore)
  18. small = df.AAPL[0:5]
  19. mapper = [0, 0, 1, 1, 1]
  20. small.groupby(mapper).mean()
  21. (558.59+561.88)/2
  22. (560.42+569.02+569.28)/3
  23. months = Series(df.index.month, df.index)
  24. def running_product(data):
  25. assert len(data) > 0, "Must specify some numbers"
  26. result = []
  27. current = data[0]
  28. result.append(current)
  29. for value in data[1:]:
  30. current = current * value
  31. result.append(current)
  32. return result
  33. def cumulative_daily(returns):
  34. # cumulative daily returns
  35. result = []
  36. current = returns[0]
  37. result.append(current)
  38. for ret in returns[1:]:
  39. current += + ret
  40. result.append(current)
  41. return result
  42. cumulative_daily(df.GOOG)
  43. def cumulative_monthly(returns, grouper):
  44. # cumulative monthly returns
  45. # for each month, compute compounded daily return
  46. # compute the cumulative returns of all the months
  47. bigSum = returns.groupby(grouper).sum()
  48. return cumulative_daily(bigSum)
  49. # def cumulative_sum(n):
  50. # cum_sum = []
  51. # y = 0
  52. # for i in n:
  53. # y += i
  54. # cum_sum.append(y)
  55. # return(cum_sum)