def generate_ma_table(frequency, start=None, end=None, ma_list=None, market_ticker='^GSPC'):
    """

    :param frequency: ['w','d']
    :param ma_list: ['SMA','EMA','DMA']:Period
    :param start:
    :param end:
    :param :market_ticker:
    :return:
    """
    end = datetime.datetime.today() if end == None else end
    start = end - datetime.timedelta(days=365) if start == None else start

    if frequency == 'w':
        max_period = 100 if ma_list==None else max(max(ma_list.values()))
        timedelta = datetime.timedelta(weeks=max_period)
    else:
        max_period = 365 if ma_list==None else max(max(ma_list.values()))
        timedelta = datetime.timedelta(days=max_period)

    prices = pdr.get_data_yahoo(market_ticker, interval=frequency)['Close']

    datetest = datetime.datetime(2019, 2, 12)
    # print(prices)
    # print(type(prices))
    # print(prices.asof(datetest))
    print(prices)
    print(prices[prices.keys() == str(datetest)])

    # print(prices.take())
    pd.rolling(10)
def KeltnerChannel(df, n):
    MA=pd.Series(pd.rolling(df['Close']).mean())
    RangeMA = pd.Series(pd.rolling(df['High'] - df['Low']).mean())
    Upper=MA + RangeMA * kelt_mult
    Lower=MA - RangeMA * kelt_mult
    df = df.join(Upper)
    df = df.join(Lower)
    return df
Exemple #3
0
def smooth(df,columns,names,period,**keyword_parameters):
    """Smooths out spikey data in a 3D trajectory by running a moving average
    over specified columns of input dataframe. Optionally, the smoothed curve
    can be shifted back close to its originally position by including the shift
    optional argument.
    
    Args:
    df      (dataframe): pandas dataframe
    columns      (list): list of dataframe headers to smooth
    names        (list): names of new columns in same order as columns
    
    Returns:
    dataframe: pandas dataframe containing smoothed and/or shifted columns.
    """
    df=deepcopy(df)
    for i in range(len(columns)):
        df[names[i]]=pd.rolling(df[columns[i]],period).mean()
            
    if ('shift' in keyword_parameters):
        shift = keyword_parameters['shift']
    
    if shift:
        shift_names=keyword_parameters['shift_names']
        shift_period=keyword_parameters['shift_period']
        
        for i in range(len(columns)):
            df[shift_names[i]]=df[names[i]].shift(shift_period)   
    return df
Exemple #4
0
def test_run2():
    dates = pd.date_range('2010-01-01', '2012-12-31')
    symbols = ['SPY', 'FB', 'GOOG', 'NFLX']
    df = get_data(symbols, dates)

    # PLot SPY data, retain matplotlib axis object
    ax = df['SPY'].plot(title="SPY rolling mean", label='SPY')

    # Compute rolling mean using 20 day window
    rm_SPY = pd.rolling_mean(df['SPY'], window=20)
    # Non deprecated version
    pd.rolling(values, window=window).mean()

    def get_rolling_std(values, window):
        """Return rolling standard deviation of given values, using specified window size."""
        # TODO: Compute and return rolling standard deviation
        return pd.rolling(values, window=window).std()

    # ax=ax adds new plot to old plot
    rm_SPY.plot(label='Rolling mean', ax=ax)

    #labels
    ax.add_xlabel("Date")
    ax.add_ylabel("Price")
    ax.legend(loc='upper left')
    plt.show()

    # Compute Bollinger Bands
    # 1. Computer rolling mean
    # 2. Compute rolling standard deviation
    # 3. Computer upper_band and lower_band
    # NON DEPRECATED
    def get_rolling_mean(values, window):
        """Return rolling mean of given values, using specified window size."""
        return pd.rolling(values, window=window).mean()

    def get_rolling_std(values, window):
        """Return rolling standard deviation of given values, using specified window size."""
        # TODO: Compute and return rolling standard deviation
        return pd.rolling(values, window=window).std()

    def get_bollinger_bands(rm, rstd):
        """Return upper and lower Bollinger Bands."""
        # TODO: Compute upper_band and lower_band
        upper_band = rm + 2 * rstd
        lower_band = rm - 2 * rstd
        return upper_band, lower_band
Exemple #5
0
def OBV(df, n):
    i = 0
    OBV = [0]
    while i < df.index[-1]:
        if df.at(i + 1, 'Close') - df.at(i, 'Close') > 0:
            OBV.append(df.at(i + 1, 'TradeVolume'))
        if df.at(i + 1, 'Close') - df.at(i, 'Close') == 0:
            OBV.append(0)
        if df.at(i + 1, 'Close') - df.at(i, 'Close') < 0:
            OBV.append(-df.at(i + 1, 'TradeVolume'))
        i = i + 1
    OBV = pd.Series(OBV)
    OBV_ma = pd.Series(pd.rolling(OBV, n).mean(), name='OBV_' + str(n))

    return OBV_ma
Exemple #6
0
def zmld_so(s, t, p, threshold=0.05, smooth=None):
    """
    Computes mixed layer depth of Southern Ocean waters.

    Parameters
    ----------
    s : array_like
        salinity [psu (PSS-78)]
    t : array_like
        temperature [℃ (ITS-90)]
    p : array_like
        pressure [db].
    smooth : int
        size of running mean window, to smooth data.

    References
    ----------
    Mitchell B. G., Holm-Hansen, O., 1991. Observations of modeling of the
        Antartic phytoplankton crop in relation to mixing depth. Deep Sea
        Research, 38(89):981-1007. doi:10.1016/0198-0149(91)90093-U

    """
    from pandas import rolling

    sigma_t = sigmatheta(s, t, p)
    depth = copy(p)
    if smooth is not None:
        sigma_t = rolling(sigma_t, smooth, min_periods=1).mean()

    sublayer = np.where(depth[(depth >= 5) & (depth <= 10)])[0]
    sigma_x = np.nanmean(sigma_t[sublayer])
    nan_sigma = np.where(sigma_t < sigma_x + threshold)[0]
    sigma_t[nan_sigma] = np.nan
    der = np.divide(np.diff(sigma_t), np.diff(depth))
    mld = np.where(der == np.nanmax(der))[0]
    zmld = depth[mld]

    return zmld
Exemple #7
0
def zmld_so(s, t, p, threshold=0.05, smooth=None):
    """
    Computes mixed layer depth of Southern Ocean waters.

    Parameters
    ----------
    s : array_like
        salinity [psu (PSS-78)]
    t : array_like
        temperature [℃ (ITS-90)]
    p : array_like
        pressure [db].
    smooth : int
        size of running mean window, to smooth data.

    References
    ----------
    Mitchell B. G., Holm-Hansen, O., 1991. Observations of modeling of the
        Antartic phytoplankton crop in relation to mixing depth. Deep Sea
        Research, 38(89):981-1007. doi:10.1016/0198-0149(91)90093-U

    """
    from pandas import rolling
    sigma_t = sigmatheta(s, t, p)
    depth = copy(p)
    if smooth is not None:
        sigma_t = rolling(sigma_t, smooth, min_periods=1).mean()

    sublayer = np.where(depth[(depth >= 5) & (depth <= 10)])[0]
    sigma_x = np.nanmean(sigma_t[sublayer])
    nan_sigma = np.where(sigma_t < sigma_x + threshold)[0]
    sigma_t[nan_sigma] = np.nan
    der = np.divide(np.diff(sigma_t), np.diff(depth))
    mld = np.where(der == np.nanmax(der))[0]
    zmld = depth[mld]

    return zmld
Exemple #8
0
def CCI(df, n):
    PP = (df['High'] + df['Low'] + df['Close']) / 3
    CCI = pd.Series((PP - pd.rolling(PP, n).mean()) / pd.rolling(PP, n).std(),
                    name='CCI_' + str(n))

    return CCI
Exemple #9
0
def 변동성대비모멘텀(데이터):
    return (데이터 / 데이터.shift(12)) / pd.rolling(12).std(데이터)
Exemple #10
0
#!/usr/bin/python
# coding: UTF-8

import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import talib

df = ts.get_k_data('600600')
df['MA10_rolling'] = pd.rolling(df['close']).mean(10)
close = [float(x) for x in df['close']]  # 调用talib计算10日移动平均线的值
df['MA10_talib'] = talib.MA(np.array(close), timeperiod=10)
df.tail(12)
Exemple #11
0
def MA(df, n):
    ##MA = pd.Series(pd.rolling_mean(df['Close'], n), name = 'MA_' + str(n))
    MA = pd.Series(pd.rolling(n).mean(), name='MA_' + str(n))
    df = df.join(MA)
    return df
Exemple #12
0
close_px
close_px['AAPL'].plot()
close_px.ix['2009'].plot()
close_px['AAPL'].ix['01-2011':'03-2011'].plot()
appl_q = close_px['AAPL'].resample('Q-DEC',fill_method='ffill')
appl_q.ix['2009'].plot()
close()
close()
appl_q.ix['2009'].plot()
close()
appl_q = close_px['AAPL'].resample('Q-DEC',fill_method='ffill')
close_px['AAPL'].ix['01-2011':'03-2011'].plot()
close()
close_px.AAPL.plot()
pd.rolling_mean(close_px.AAPL,250).plot()
pd.rolling(close_px.AAPL,250).mean().plot()
pd.rolling_mean(close_px.AAPL,250).plot()
appl_std250 = pd.rolling_std(close_px.AAPL,250,min_periods=10)
appl_std250 = pd.rolling(close_px.AAPL,250,min_periods=10).std()
appl_std250 = close_px.AAPL.rolling(250,min_periods=10).std()
appl_std250[5:12]
appl_std250.plot()
close()
appl_std250.plot()
expanding_mean = lambda x:rolling_mean(x, len(x), min_periods=1)
close_px.rolling(60).mean().plot(logy=True)
close()
fig_axes = plt.subplots(nrows=2,ncols=1,sharex=True,sharey=True,figsize=(12,7))
aapl_px = close_px.AAPL['2005':'2009']
ma60 = aapl_px.rolling(60,min_periods=50)
ewma60 = pd.ewma(aapl_px,span=60)
Exemple #13
0
 def get_rolling_std(values, window):
     """Return rolling standard deviation of given values, using specified window size."""
     # TODO: Compute and return rolling standard deviation
     return pd.rolling(values, window=window).std()
Exemple #14
0
 def get_rolling_mean(values, window):
     """Return rolling mean of given values, using specified window size."""
     return pd.rolling(values, window=window).mean()