Esempio n. 1
0
def calculateInvestment(limit=10,
                        count=10,
                        write_to_file=True,
                        show_cla=False,
                        tpv=20000):
    symbols = getSymbolsFromDatabase()
    prices = createDataFrame(symbols[:limit], count)
    mu = expected_returns.mean_historical_return(prices)
    S = risk_models.CovarianceShrinkage(prices).ledoit_wolf()
    ef = EfficientFrontier(mu, S, weight_bounds=(-1, 1))
    ef.add_objective(objective_functions.L2_reg)
    ef.min_volatility()
    c_weights = ef.clean_weights()
    if write_to_file == True:
        ef.save_weights_to_file("weights.txt")
    if show_cla == True:
        cla = CLA(mu, S)
        ef_plot(cla)
    ef.portfolio_performance(verbose=True)
    latest_prices = disc_alloc.get_latest_prices(prices)
    allocation_minv, leftover = disc_alloc.DiscreteAllocation(
        c_weights, latest_prices, total_portfolio_value=tpv).lp_portfolio()
    return allocation_minv, leftover
Esempio n. 2
0
cov_matrix_annual

from pypfopt.efficient_frontier import EfficientFrontier
from pypfopt import risk_models
from pypfopt import expected_returns

# Portfolio Optimization

# Calculate the expected returns and annualized sample covariance matrix of asset returns
mu = expected_returns.mean_historical_return(df, compounding=True)
S = risk_models.sample_cov(df)

# Optimize for maximum Sharpe Ratio
ef = EfficientFrontier(mu, S, weight_bounds=(0.05, 0.2))
# weights = ef.max_sharpe(risk_free_rate=0.01)
weights = ef.min_volatility()
ef.save_weights_to_file('weights.csv')
cleaned_weights = ef.clean_weights()
print(cleaned_weights)
ef.portfolio_performance(verbose=True)

# Get the discrete allocation of each share per stock
from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices

latest_prices = get_latest_prices(df)
weights = cleaned_weights
da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=15000)

allocation, leftover = da.lp_portfolio()
print('Discrete allocation:', allocation)
print('Funds remaining: ${:.2f}'.format(leftover))
cs = CovarianceShrinkage(assets).ledoit_wolf()

# Compute the sample covariance matrix of returns
sample_covariance = assets.pct_change().cov() * 252

# Create the EfficientFrontier instance variable
ef = EfficientFrontier(mu, cs)

# Compute the Weights portfolio that maximises the Sharpe ratio
weights = ef.max_sharpe()

# clean_weights() method truncates tiny weights to zero and rounds others
cw = ef.clean_weights()

with changepath(path):
    ef.save_weights_to_file("weights.txt")  # saves to file

print2(cw)

# Evaluate performance of optimal portfolio
ef.portfolio_performance(verbose=True)

# Create a dictionary of time periods (or 'epochs')
epochs = {
    'before': {
        'start': starttime,
        'end': '31-12-2006'
    },
    'during': {
        'start': '1-1-2007',
        'end': '31-12-2008'
Esempio n. 4
0
from pypfopt.risk_models import fix_nonpositive_semidefinite

dataTable = None # The raw input from file, contains the whole data table.
exp_return = None
cov_matrix = None # The covariance matrix
corr_matrix = None # The correlation coefficient matrix
assetsList = None # in the Same order in summary file
asset_to_num = None # a dictionary for the reverse index of assetsList


if __name__ == "__main__":

    # Step1: get expected return and cov matrix from data
    # This step will takes about 10-20s
    dataTable, summaryTable = init.read_CSV()
    assetsList, asset_to_num = init.getAssetsList()
    init.preprocess()
    exp_return = init.calcExpectedReturn_1()
    cov_matrix, corr_matrix = init.calcCovMatrix()

    # Step2: ...

    # Step3:
    cov_matrix = fix_nonpositive_semidefinite(cov_matrix)

    ef = EfficientFrontier(exp_return, cov_matrix)
    raw_weights = ef.max_sharpe(risk_free_rate=0.008674) #shibor O/N 2020-05-15
    cleaned_weights = ef.clean_weights()
    ef.save_weights_to_file("weights.csv")
    print(cleaned_weights)
    ef.portfolio_performance(verbose=True)