lab /python/pandas_3.py

Language Python Lines 69
MD5 Hash 7af60806a5b1edae7178292b9c93523e Estimated Cost $993 (why?)
Repository https://bitbucket.org/jaredlander/lab.git View Raw File View Project SPDX
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# pandas group by
import numpy as np
import pandas as pd
import pandas.io.data as web
from pandas import DataFrame

def pct_change(x):
    return x / x.shift(1) - 1
    
stocks = ['AAPL', 'FB', 'GOOG']

st = '2012-6-1'
ed = '2012-9-29'

dd = {}

for s in stocks:
    dd[s] = web.get_data_yahoo(s, st, ed)['Adj Close']

df = DataFrame(dd)
df.head()
returns = df.pct_change()

df.groupby(mapper).apply(zscore)

small = df.AAPL[0:5]
mapper = [0, 0, 1, 1, 1]
small.groupby(mapper).mean()
(558.59+561.88)/2
(560.42+569.02+569.28)/3

months = Series(df.index.month, df.index)

def running_product(data):
    assert len(data) > 0, "Must specify some numbers"
    result = []
    current = data[0]
    result.append(current)
    for value in data[1:]:
        current = current * value
        result.append(current)
    return result

def cumulative_daily(returns):
    # cumulative daily returns
    result = []
    current = returns[0]
    result.append(current)
    for ret in returns[1:]:
        current += + ret
        result.append(current)
    return result
cumulative_daily(df.GOOG)
    
    
def cumulative_monthly(returns, grouper):
    # cumulative monthly returns
    # for each month, compute compounded daily return
    # compute the cumulative returns of all the months
    bigSum = returns.groupby(grouper).sum()
    return cumulative_daily(bigSum)

# def cumulative_sum(n):
    # cum_sum = []
    # y = 0
    # for i in n:
        # y += i
        # cum_sum.append(y)
    # return(cum_sum)
Back to Top