Beispiel #1
0
def get_portfolio_by_id(id: str):
    portfolios = list()
    connect()
    portfolio = Portfolio.objects(_id=id).first()
    portfolios.append(portfolio)
    close()
    LOG.info('Loading %d portfolios' % len(portfolios))
    return portfolios
Beispiel #2
0
def process_result_of_ga(results_frame, stocks, gmean):
    try:
        id_sharpe = results_frame['sharpe'].idxmax()
    except TypeError as exc:
        id_sharpe = maxId(results_frame, 'sharpe')

    try:
        max_sharpe_port = results_frame.iloc[id_sharpe]
    except TypeError as exc:
        id_sharpe = maxId(results_frame, 'sharpe')
        max_sharpe_port = results_frame.iloc[id_sharpe]

    try:
        id_stdev = results_frame['stdev'].idxmin()
    except TypeError as exc:
        id_stdev = minId(results_frame, 'stdev')

    if id_stdev == np.NaN:
        id_stdev = minId(results_frame, 'stdev')

    try:
        min_vol_port = results_frame.iloc[id_stdev]
    except TypeError as exc:
        id_stdev = minId(results_frame, 'stdev')
        min_vol_port = results_frame.iloc[id_stdev]

    LOG.info('Max Sharpe ratio: \n%s' % str(max_sharpe_port))
    LOG.info('Min standard deviation: \n%s' % str(min_vol_port))
    db.connect()
    solved = Portfolio()
    max_item = parse_solved_portfolio(max_sharpe_port, stocks)
    min_item = parse_solved_portfolio(min_vol_port, stocks)
    solved.max_item = max_item
    solved.min_item = min_item
    solved.date = datetime.datetime.today()
    solved.total_sum = 0
    for stock in max_item.stocks:
        solved.total_sum += stock.value
    if gmean is None:
        solved.gmean = 0.0
    else:
        solved.gmean = gmean
    solved.save()
    db.close()
    return max_item.sharpe_ratio, solved._id
Beispiel #3
0
def get_n_first_portfolios(count: int):
    portfolios = list()
    connect()
    today = datetime.today() - timedelta(hours=12)
    for p in Portfolio.objects(date__gt=today).order_by('-max_item.sharpe_ratio')[:count]:
        portfolios.append(p)
    close()
    LOG.info('Loading %d portfolios' % len(portfolios))
    return portfolios
Beispiel #4
0
def parallel_solve(all_stocks, type_ga, curr, count):
    LOG.info('Start parallel solve in %s' % str(threading.get_ident()))
    range_stock = len(all_stocks)
    number = list()
    stocks = []

    for position in range(15):
        pos = random.randint(0, range_stock)
        while pos in number:
            pos = random.randint(0, range_stock)
        stock = all_stocks[pos - 1]
        while len(stock.day_history) < 66:
            pos = random.randint(0, range_stock)
            stock = all_stocks[pos - 1]
        stocks.append(stock)

    # download daily price data for each of the stocks in the portfolio
    data = get_stock_price(stocks)
    returns = data.pct_change()

    # calculate mean daily return and covariance of daily returns
    mean_daily_returns = returns.mean()
    cov_matrix = returns.cov()
    days = len(stocks[0].day_history)
    iterations = 50000

    start = time.time()
    if type_ga == GA_SIMPLE:
        results_frame = simple.solve(stocks, iterations, mean_daily_returns,
                                     cov_matrix, days)
    if type_ga == GA_NSGAII:
        results_frame = NSGAII.solve(stocks, iterations, mean_daily_returns,
                                     cov_matrix, days)
    if type_ga == GA_NSGAIII:
        results_frame = NSGAII.solve_nsgaiii(stocks, iterations,
                                             mean_daily_returns, cov_matrix,
                                             days)
    duration = time.time() - start
    LOG.info('Duration solved: %s' % duration)

    sharpe_id_min = results_frame['sharpe'].idxmin()
    max_sharpe_port = results_frame.iloc[sharpe_id_min]
    stdev_id_min = results_frame['stdev'].idxmax()
    min_vol_port = results_frame.iloc[stdev_id_min]

    LOG.info('Max Sharpe ratio: %s' % str(max_sharpe_port))
    LOG.info('Min standard deviation: %s' % str(min_vol_port))
    db.connect()
    solved = Portfolio()
    max_item = parse_solved_portfolio(max_sharpe_port, stocks)
    min_item = parse_solved_portfolio(min_vol_port, stocks)
    solved.max_item = max_item
    solved.min_item = min_item
    solved.date = datetime.datetime.today()
    solved.save()
    db.close()
    LOG.info('Save %d portfolio from %d in thread %s' %
             (curr + 1, count, str(threading.get_ident())))
    return 'Duration %s' % str(duration)
Beispiel #5
0
def get_n_random_portfolios(number=10):
    portfolios = list()
    connect()
    today = datetime.today() - timedelta(hours=12)
    found_portfolios = Portfolio.objects(date__gt=today).order_by('-max_item.sharpe_ratio')
    all_found = len(found_portfolios)
    for x in range(number):
        position = random.randint(0, all_found - 1)
        portfolios.append(found_portfolios[position])
    close()
    LOG.info('Loading %d portfolios' % len(portfolios))
    return portfolios