Ejemplo n.º 1
0
def test_draw_portfolio_ref_compare():
    symbols = ['AAPL', 'GOOG', 'IBM', 'MSFT']
    ref_symbol = '^GSPC'
    basic_portfolio = BasicPortfolio(symbols, dt.datetime(2014, 1, 1),
                                     dt.datetime(2014, 12, 31))
    basic_portfolio.plot_with_reference([0.4, 0.4, 0.0, 0.2],
                                        ref_symbol,
                                        source='yahoo')
Ejemplo n.º 2
0
def test_small_portfolio():
    symbols = ["AIR.PA", "LG.PA", "GLE.PA", "DG.PA"]
    ref_symbol = '^FCHI'
    end_date = dt.datetime.today()
    start_date = end_date - dt.timedelta(days=365)
    basic_portfolio = BasicPortfolio(symbols, start_date, end_date)
    optimize(basic_portfolio, ref_symbol, filename=None, target_return=0.012)
def main():
    """main function"""

    # Construct the two symbol lists SP 500 of 2008 and 2012
    dataobj = da.DataAccess('Yahoo')

    symbols12 = dataobj.get_symbols_from_list("sp5002012")
    symbols12.append('SPY')

    lookbackdates = 20
    basic_portfolio = BasicPortfolio(symbols12, dt.datetime(2008, 1, 1),
                                     dt.datetime(2009, 12, 31))

    print 'Start Looking for the events'
    df_events = BollingerEventTest(basic_portfolio, lookbackdates)

    print 'Start retrieving data from local Yahoo'
    d_data = load_local_data_from_yahoo(basic_portfolio.start_date,
                                        basic_portfolio.end_date,
                                        basic_portfolio.tickers)

    filename = "BollingerEventStudy12.9.pdf"

    ep.eventprofiler(df_events,
                     d_data,
                     i_lookback=20,
                     i_lookforward=20,
                     s_filename=filename,
                     b_market_neutral=True,
                     b_errorbars=True,
                     s_market_sym='SPY')

    print 'Generate orders with the events'
    df_event_trading = GenerateTradingWithEvents(df_events)
    df_event_trading.to_csv("ordersbollinger5d.csv", index=False, header=False)
Ejemplo n.º 4
0
def test_cac40_portfolio():
    ref_symbol = '^FCHI'
    end_date = dt.datetime.today()
    start_date = end_date - dt.timedelta(days=365)
    cac40 = load_valid_cac40_names()
    basic_portfolio = BasicPortfolio(cac40.index, start_date, end_date,
                                     cac40.values)

    optimize(basic_portfolio, ref_symbol, filename="EquitiesvFrontier2015.pdf")
Ejemplo n.º 5
0
def test():
    """Main Function"""
    ls_symbols = ['AAPL', 'GOOG', 'IBM', 'MSFT']
    start_date = dt.datetime(2010, 1, 1)
    end_date = dt.datetime(2010, 12, 31)
    basic_portfolio = BasicPortfolio(ls_symbols, start_date, end_date)
    period = 20

    compute_bollinger_band(basic_portfolio, period, source='local')
Ejemplo n.º 6
0
def get_correlations_cac40(filename='result/correlationCAC40.csv', target_ticker=None):
    symbols = load_valid_cac40_names()
    end_date = dt.datetime.today()
    start_date = end_date - dt.timedelta(days=365)
    basic_portfolio = BasicPortfolio(symbols.index, start_date, end_date, symbols.values)
    correlations = basic_portfolio.get_correlations()

    if isinstance(correlations, pd.DataFrame):
        print 'Write the correlation matrix into file: ', filename
        correlations.to_csv(filename)

    if target_ticker is not None and target_ticker in symbols.index:
        ticker_name = symbols[target_ticker]
        target_correlation = correlations[ticker_name]
        target_correlation = target_correlation.drop(ticker_name)
        print 'The stock %s is least correlated to %s with correlation %f' % \
              (ticker_name, target_correlation.argmin(), target_correlation.min())
        print 'The stock %s is most correlated to %s with correlation %f' % \
              (ticker_name, target_correlation.argmax(), target_correlation.max())
Ejemplo n.º 7
0
    def testing(self, target_return=0.011):
        """
        The method of back testing
        @param target_return: target return of the portfolio
        """
        best_allocation = get_frontier(BasicPortfolio(self.symbols,
                                                      self.start_date,
                                                      self.mid_date,
                                                      self.symbol_names),
                                       self.reference_symbol,
                                       filename=None,
                                       target_return=target_return)

        BasicPortfolio(self.symbols, self.start_date, self.mid_date, self.symbol_names)\
            .plot_with_reference(best_allocation, self.reference_symbol,
                                 filename='result/portvCAC40-target.before.pdf')

        BasicPortfolio(self.symbols, self.mid_date, self.end_date, self.symbol_names)\
            .plot_with_reference(best_allocation, self.reference_symbol,
                                 filename='result/portvCAC40-target.forecast.pdf')
Ejemplo n.º 8
0
def get_correlations_cac40(filename='result/correlationCAC40.csv',
                           target_ticker=None):
    symbols = load_valid_cac40_names()
    end_date = dt.datetime.today()
    start_date = end_date - dt.timedelta(days=365)
    basic_portfolio = BasicPortfolio(symbols.index, start_date, end_date,
                                     symbols.values)
    correlations = basic_portfolio.get_correlations()

    if isinstance(correlations, pd.DataFrame):
        print 'Write the correlation matrix into file: ', filename
        correlations.to_csv(filename)

    if target_ticker is not None and target_ticker in symbols.index:
        ticker_name = symbols[target_ticker]
        target_correlation = correlations[ticker_name]
        target_correlation = target_correlation.drop(ticker_name)
        print 'The stock %s is least correlated to %s with correlation %f' % \
              (ticker_name, target_correlation.argmin(), target_correlation.min())
        print 'The stock %s is most correlated to %s with correlation %f' % \
              (ticker_name, target_correlation.argmax(), target_correlation.max())
Ejemplo n.º 9
0
def test_best_allocation():
    """
    This function is to remove
    Test that it is possible to find the best portfolio (highest sharpe ratio)
    given a list of symbols using the methods above.
    """

    # symbols = ['BRCM', 'TXN', 'IBM', 'HNZ']
    symbols = ['AAPL', 'GOOG', 'IBM', 'MSFT']
    # ['GOOG','AAPL','GLD','XOM']
    basic_portfolio = BasicPortfolio(symbols, dt.datetime(2014, 1, 1),
                                     dt.datetime(2014, 12, 31))

    alloc = range(4)

    sharpe_max = 0
    alloc_max = alloc[:]

    for i in range(11):
        alloc[0] = i * 0.1
        for j in range(11 - i):
            alloc[1] = j * 0.1
            for k in range(11 - i - j):
                alloc[2] = k * 0.1
                alloc[3] = (10 - i - j - k) * 0.1

                vol, daily_ret, sharpe, cum_ret = \
                    basic_portfolio.analyze(alloc)

                if sharpe > sharpe_max:
                    sharpe_max = sharpe
                    alloc_max = alloc[:]

    print 'Best sharpe ratio is ', sharpe_max
    print 'Best allocation is', alloc_max

    ref_symbol = '$SPX'

    basic_portfolio.plot_with_reference(alloc_max, ref_symbol, source='local')
Ejemplo n.º 10
0
def test_best_allocation():
    """
    This function is to remove
    Test that it is possible to find the best portfolio (highest sharpe ratio)
    given a list of symbols using the methods above.
    """

    # symbols = ['BRCM', 'TXN', 'IBM', 'HNZ'] 
    symbols = ['AAPL', 'GOOG', 'IBM', 'MSFT']
    # ['GOOG','AAPL','GLD','XOM']
    basic_portfolio = BasicPortfolio(symbols, dt.datetime(2014, 1, 1), dt.datetime(2014, 12, 31))

    alloc = range(4)

    sharpe_max = 0
    alloc_max = alloc[:]

    for i in range(11):
        alloc[0] = i * 0.1
        for j in range(11 - i):
            alloc[1] = j * 0.1
            for k in range(11 - i - j):
                alloc[2] = k * 0.1
                alloc[3] = (10 - i - j - k) * 0.1

                vol, daily_ret, sharpe, cum_ret = \
                    basic_portfolio.analyze(alloc)

                if sharpe > sharpe_max:
                    sharpe_max = sharpe
                    alloc_max = alloc[:]

    print 'Best sharpe ratio is ', sharpe_max
    print 'Best allocation is', alloc_max

    ref_symbol = '$SPX'

    basic_portfolio.plot_with_reference(alloc_max, ref_symbol, source='local')
Ejemplo n.º 11
0
def main():
    """Main Function"""

    # Construct the two symbol lists SP 500 of 2008 and 2012
    dataobj = da.DataAccess('Yahoo')
    symbols08 = dataobj.get_symbols_from_list("sp5002008")
    symbols08.append('SPY')

    symbols12 = dataobj.get_symbols_from_list("sp5002012")
    symbols12.append('SPY')

    start_date = dt.datetime(2008, 1, 1)
    end_date = dt.datetime(2009, 12, 31)

    basic_portfolio08 = BasicPortfolio(symbols08, start_date, end_date)
    basic_portfolio08.event_profiler(source='local',
                                     filename="MyEventStudy08.9.chg.pdf")
    basic_portfolio12 = BasicPortfolio(symbols12, start_date, end_date)
    basic_portfolio12.event_profiler(source='local',
                                     filename="MyEventStudy12.9.chg.pdf")
Ejemplo n.º 12
0
def main():
    """Main Function"""

    # Construct the two symbol lists SP 500 of 2008 and 2012
    dataobj = da.DataAccess('Yahoo')
    symbols08 = dataobj.get_symbols_from_list("sp5002008")
    symbols08.append('SPY')

    symbols12 = dataobj.get_symbols_from_list("sp5002012")
    symbols12.append('SPY')

    start_date = dt.datetime(2008, 1, 1)
    end_date = dt.datetime(2009, 12, 31)

    basic_portfolio08 = BasicPortfolio(symbols08, start_date, end_date)
    basic_portfolio08.event_profiler(source='local', filename="MyEventStudy08.9.chg.pdf")
    basic_portfolio12 = BasicPortfolio(symbols12, start_date, end_date)
    basic_portfolio12.event_profiler(source='local', filename="MyEventStudy12.9.chg.pdf")
Ejemplo n.º 13
0
"""
Thi file contains test for the portfolio analysis.
"""

import datetime as dt
import pandas as pd
from portfolio import BasicPortfolio

basic_portfolio = BasicPortfolio(['AAPL', 'IBM', 'MSFT'], dt.datetime(2011, 12, 1),
                                 dt.datetime(2011, 12, 31))


def test_get_correlations():
    correlations = basic_portfolio.get_correlations()
    assert isinstance(correlations, pd.DataFrame)
    assert correlations.shape == (3, 3)


def test_analyze():
    vol, ave_daily_ret, sharpe, cum_ret = \
        basic_portfolio.analyze([0.1, 0.4, 0.5], source='local', debug=True)
    eps = 0.0001
    assert abs(vol - 0.00941707081886) * 100 < eps
    assert abs(sharpe - 0.561924531129) * 100 < eps
    assert abs(ave_daily_ret - 0.000333344702654) * 10000 < eps
    assert abs(cum_ret - 0.00608928693) * 10000 < eps


if __name__ == '__main__':
    test_get_correlations()
    test_analyze()
Ejemplo n.º 14
0
def test_draw_portfolio_ref_compare():
    symbols = ['AAPL', 'GOOG', 'IBM', 'MSFT']
    ref_symbol = '^GSPC'
    basic_portfolio = BasicPortfolio(symbols, dt.datetime(2014, 1, 1), dt.datetime(2014, 12, 31))
    basic_portfolio.plot_with_reference([0.4, 0.4, 0.0, 0.2], ref_symbol, source='yahoo')