Beispiel #1
0
def test_returns_hist(symbol, start_date: datetime, end_date: datetime,
                      ind_return, ax):
    df_main = pd.DataFrame(index=pd.date_range(start_date, end_date))
    df_temp = quotes_manager.get_daily_quotes(start_date, end_date, symbol)
    df_main = df_main.join(df_temp[quotes_manager.COL_ADJ_CLOSE]).rename(
        columns={quotes_manager.COL_ADJ_CLOSE: symbol})

    df_main.dropna(inplace=True)

    ind_return.calculate_ind_into_df(df_main, symbol)

    ind_column_name = ind_return.get_column_name(symbol)

    mean = df_main[ind_column_name].mean()
    print(ind_column_name + ' mean=' + str(mean))
    std = df_main[ind_column_name].std()
    print(ind_column_name + ' std=' + str(std))
    kurtosis = df_main[ind_column_name].kurtosis()
    # to check if the tail of the histogran is aligned with a normal distribution or not
    print(ind_column_name + ' kurtosis=' + str(kurtosis))

    ax = df_main[ind_column_name].hist(ax=ax, bins=20)
    ax.axvline(mean, color='w', linestyle='dashed', linewidth=2)
    ax.axvline(std, color='r', linestyle='dashed', linewidth=2)
    ax.axvline(-std, color='r', linestyle='dashed', linewidth=2)
Beispiel #2
0
def test_returns_hist_same_ax(symbol, start_date: datetime, end_date: datetime,ind_return):
    df_main = pd.DataFrame(index=pd.date_range(start_date,end_date))
    df_temp = quotes_manager.get_daily_quotes(start_date,end_date,symbol)
    df_main = df_main.join(df_temp[quotes_manager.COL_ADJ_CLOSE]).rename(columns={quotes_manager.COL_ADJ_CLOSE:symbol})

    df_main.dropna(inplace=True)
    ind_return.calculate_ind_into_df(df_main,symbol)
    ind_column_name = ind_return.get_column_name(symbol)
    df_main[ind_column_name].hist(bins=30,alpha=0.5, label=symbol)
Beispiel #3
0
def compare_returns(symbols, start_date: datetime, end_date: datetime):
    df_main = pd.DataFrame(index=pd.date_range(start_date, end_date))
    for symbol in symbols:
        df_temp = quotes_manager.get_daily_quotes(start_date, end_date, symbol)
        # df_temp = df_temp[[quotes_manager.COL_DATE,quotes_manager.COL_ADJ_CLOSE]].rename(columns={quotes_manager.COL_ADJ_CLOSE:symbol})
        df_main = df_main.join(df_temp[quotes_manager.COL_ADJ_CLOSE]).rename(
            columns={quotes_manager.COL_ADJ_CLOSE: symbol})
        # df_main = df_main.join(df_temp)

    df_main = df_main.dropna()
    df_returns = df_main / df_main.iloc[0]
    df_returns.plot()
    plt.show()
Beispiel #4
0
def calculate_portifolio(start_portfolio_value,start_date,end_date, symbols, allocations=[],use_quotes_cache=True):
    df_quotes = pd.DataFrame(index=pd.date_range(start_date, end_date))
    for symbol in symbols:
        df_temp = quotes_manager.get_daily_quotes(start_date, end_date, symbol, use_cache=use_quotes_cache)
        df_quotes = df_quotes.join(df_temp[quotes_manager.COL_ADJ_CLOSE]).rename(
            columns={quotes_manager.COL_ADJ_CLOSE: symbol})
    df_quotes.dropna(inplace=True)
    df_normalized_returns = pd.DataFrame(index=pd.date_range(start_date, end_date))
    norm_ret = NormalizedDailyReturn()
    for symbol in symbols:
        df_normalized_returns = df_normalized_returns.join(norm_ret.calculate_ind_series(df_quotes[symbol]))
    df_normalized_returns.dropna(inplace=True)

    if not allocations or len(allocations) == 0:
        # guess allocation, just a simple distribution
        guess_alloc = np.full(len(symbols), 100 / len(symbols))

        # limiting the values to be from 0 to 100
        bounds = [(0, 100) for x in range(len(symbols))]

        # only satisfied when sum of elements is 1.
        cons = ({'type': 'eq', 'fun': lambda x: 100 - np.sum(x)})
        result = spo.minimize(find_sharpe_allocation, guess_alloc, args=(df_normalized_returns), bounds=bounds, constraints=cons, method='SLSQP',
                              options={'disp': True})
        allocations = result.x / 100
        print('Calculated Sharpe = ' + str(result.fun))
        print('Calculated Allocations = ')
        np.savetxt(sys.stdout, allocations, '%5.2f')

    df_allocations = df_normalized_returns * allocations
    df_position_value = df_allocations * start_portfolio_value
    df_portfolio_value = df_position_value.sum(axis=1)

    day_ret = DailyReturn()
    day_ret_series = day_ret.calculate_ind_series(df_portfolio_value)
    avg_daily_return = day_ret_series.mean()
    # Risk, Vol
    std_daily_return = day_ret_series.std()
    end_value = df_portfolio_value.iloc[-1]
    cum_return = (end_value / start_portfolio_value) - 1
    rf = 0.
    sharpe = np.sqrt(252) * ((avg_daily_return - rf) / std_daily_return)

    print('Statistics for ' + str(symbols))
    print('avg_daily_return = ' + str(avg_daily_return))
    print('std_daily_return = ' + str(std_daily_return))
    print('end_value = ' + str(end_value))
    print('cum_return = ' + str(cum_return))
    print('sharpe = ' + str(sharpe))

    return df_quotes, df_normalized_returns, df_allocations, df_position_value, df_portfolio_value
Beispiel #5
0
def bollinger_bands_test(symbol, start_date: datetime, end_date: datetime,
                         window: int, n_std: int):
    df = quotes_manager.get_daily_quotes(start_date, end_date, symbol)
    df = df.rename(columns={quotes_manager.COL_ADJ_CLOSE: symbol})[[symbol]]

    boll_band_sma = BollingerBandsSMA(window, n_std)
    boll_band_sma_df = boll_band_sma.calculate_ind_into_df(df, symbol)
    boll_band_sma_df.plot(figsize=(12, 6))
    plt.show()

    boll_band_ema = BollingerBandsEMA(window, n_std)
    boll_band_ema_df = boll_band_ema.calculate_ind_into_df(df, symbol)
    boll_band_ema_df.plot(figsize=(12, 6))
    plt.show()
Beispiel #6
0
def test_returns(symbols, start_date: datetime, end_date: datetime, ind_return,
                 ax):
    df_main = pd.DataFrame(index=pd.date_range(start_date, end_date))
    for symbol in symbols:
        df_temp = quotes_manager.get_daily_quotes(start_date, end_date, symbol)
        df_main = df_main.join(df_temp[quotes_manager.COL_ADJ_CLOSE]).rename(
            columns={quotes_manager.COL_ADJ_CLOSE: symbol})

    df_main.dropna(inplace=True)

    for symbol in symbols:
        ind_return.calculate_ind_into_df(df_main, symbol)

    df_main[[ind_return.get_column_name(symbol)
             for symbol in symbols]].plot(ax=ax)
Beispiel #7
0
def test_exponential_moving__avg(symbol, start_date: datetime,
                                 end_date: datetime):
    df = quotes_manager.get_daily_quotes(start_date, end_date, symbol)
    df = df.rename(columns={quotes_manager.COL_ADJ_CLOSE: symbol})

    ema = ExponentialMovingAvg(20)
    ema.calculate_ind_into_df(df, symbol)

    sma = SimpleMovingAvg(20)
    sma.calculate_ind_into_df(df, symbol)

    ax = df[[symbol,
             ema.get_ind_column_name(),
             sma.get_ind_column_name()]].plot()
    plt.show()
Beispiel #8
0
def calculate_portifolio(start_portfolio_value,
                         start_date,
                         end_date,
                         symbols,
                         allocations,
                         use_quotes_cache=True):
    df_quotes = pd.DataFrame(index=pd.date_range(start_date, end_date))
    for symbol in symbols:
        df_temp = quotes_manager.get_daily_quotes(start_date,
                                                  end_date,
                                                  symbol,
                                                  use_cache=use_quotes_cache)
        df_quotes = df_quotes.join(
            df_temp[quotes_manager.COL_ADJ_CLOSE]).rename(
                columns={quotes_manager.COL_ADJ_CLOSE: symbol})
    df_quotes.dropna(inplace=True)
    df_normalized_returns = pd.DataFrame(
        index=pd.date_range(start_date, end_date))
    norm_ret = NormalizedDailyReturn()
    for symbol in symbols:
        df_normalized_returns = df_normalized_returns.join(
            norm_ret.calculate_ind_series(df_quotes[symbol]))
    df_normalized_returns.dropna(inplace=True)
    df_allocations = df_normalized_returns * allocations
    df_position_value = df_allocations * start_portfolio_value
    df_portfolio_value = df_position_value.sum(axis=1)

    day_ret = DailyReturn()
    day_ret_series = day_ret.calculate_ind_series(df_portfolio_value)
    avg_daily_return = day_ret_series.mean()
    # Risk, Vol
    std_daily_return = day_ret_series.std()
    end_value = df_portfolio_value.iloc[-1]
    cum_return = (end_value / start_portfolio_value) - 1
    rf = 0.
    sharpe = np.sqrt(252) * ((avg_daily_return - rf) / std_daily_return)

    print('Statistics for ' + str(symbols))
    print('avg_daily_return = ' + str(avg_daily_return))
    print('std_daily_return = ' + str(std_daily_return))
    print('end_value = ' + str(end_value))
    print('cum_return = ' + str(cum_return))
    print('sharpe = ' + str(sharpe))

    return df_quotes, df_normalized_returns, df_allocations, df_position_value, df_portfolio_value
Beispiel #9
0
def test_returns_scatter(x_symbol, y_symbol, start_date: datetime,
                         end_date: datetime, ind_return, ax):
    symbols = [x_symbol, y_symbol]
    df_main = pd.DataFrame(index=pd.date_range(start_date, end_date))
    for symbol in symbols:
        df_temp = quotes_manager.get_daily_quotes(start_date, end_date, symbol)
        df_main = df_main.join(df_temp[quotes_manager.COL_ADJ_CLOSE]).rename(
            columns={quotes_manager.COL_ADJ_CLOSE: symbol})

    df_main.dropna(inplace=True)

    for symbol in symbols:
        ind_return.calculate_ind_into_df(df_main, symbol)

    beta_Y, alpha_Y = np.polyfit(df_main[x_symbol], df_main[y_symbol], 1)
    print('Beta ' + y_symbol + ' = ' + str(beta_Y))
    print('Alpha ' + y_symbol + ' = ' + str(alpha_Y))
    ax.plot(df_main[x_symbol],
            beta_Y * df_main[x_symbol] + alpha_Y,
            '-',
            color='r')
    df_main.plot(kind='scatter', x=x_symbol, y=y_symbol, ax=ax)
Beispiel #10
0
import domain
from domain.order import order
from domain.order_type import order_type
from domain.portfolio import portfolio
from manager import quotes_manager
from datetime import datetime
import pandas as pd

df_quotes: pd.DataFrame
start_date = datetime(2018, 7, 1)
end_date = datetime(2018, 7, 15)
df_quotes = quotes_manager.get_daily_quotes(start_date, end_date, 'AAPL')
print(df_quotes)
# df_quotes['close'].pct_change()

df_quotes['ClosePctChange'] = df_quotes['4. close'].pct_change()

rand_portfolio = portfolio('random')

for index, row in df_quotes.iterrows():
    if not pd.isna(row['ClosePctChange']):
        if row['ClosePctChange'] > 0:
            type = order_type.SELL
        else:
            type = order_type.BUY

        rand_portfolio.add_order(
            order(type, 'AAPL', 1000, row['4. close'],
                  datetime.strptime(row.name, '%Y-%m-%d')))

df_positions = rand_portfolio.calculate_positions_df(start_date, end_date)