Example #1
0
# df = pd.read_csv("tests/resources/stock_prices.csv", parse_dates=True, index_col="date")
df = pd.read_csv(os.path.join(path, 'stock_prices.csv'),
                 parse_dates=True,
                 index_col="Date")

returns = df.pct_change().dropna()
# Calculate expected returns and sample covariance
mu = expected_returns.mean_historical_return(df)
S = risk_models.sample_cov(df)

# Optimise for maximal Sharpe ratio
ef = EfficientFrontier(mu, S)
raw_weights = ef.max_sharpe()
cleaned_weights = ef.clean_weights()
ef.save_weights_to_file("weights.csv")  # saves to file
print(cleaned_weights)
ef.portfolio_performance(verbose=True)

latest_prices = get_latest_prices(df)

da = DiscreteAllocation(cleaned_weights,
                        latest_prices,
                        total_portfolio_value=600)
allocation, leftover = da.lp_portfolio()
print("Discrete allocation:", allocation)
print("Funds remaining: ${:.2f}".format(leftover))
cla = CLA(mu, S)
plotting.plot_efficient_frontier(cla)
plotting.plot_covariance(S)
plotting.plot_weights(cleaned_weights)
plt.xlabel('Volatility')
plt.ylabel('Return')
# plt.scatter(max_sr_vol,max_sr_ret,c='red',s=50,edgecolors='black')
plt.plot(frontier_volatility, frontier_y, 'g--', linewidth=3)
plt.show()

#********************************
#*****PORTFOLIO OPTIMIZATION*****
#********************************

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

#Optimize for max sharpe ratio
ef = EfficientFrontier(mu, s)
weights = ef.max_sharpe()
cleaned_weights = ef.clean_weights()
print(cleaned_weights)
ef.portfolio_performance(verbose=True)

#Get the discrete allocation of each share per stock
latest_prices = get_latest_prices(df)
weights = cleaned_weights
fa = int(input("Enter amount of investable funds: "))
da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=fa)

allocation, leftover = da.lp_portfolio()
print('Discrete allocation: ', allocation)
print('Funds remaining: ${:.2f}'.format(leftover))
print(efficient_portfolio_during.min_volatility())

# Compute the efficient frontier
(ret, vol, weights) = efficient_portfolio_during.efficient_frontier()

# Add the frontier to the plot showing the 'before' and 'after' frontiers
plt.scatter(vol, ret, s=4, c='g', marker='.', label='During')
plt.legend()
plt.show()

# plotting using PyPortfolioOpt
pplot.plot_covariance(cs, plot_correlation=False, show_tickers=True)
pplot.plot_efficient_frontier(efficient_portfolio_during,
                              points=100,
                              show_assets=True)
pplot.plot_weights(cw)

# Dealing with many negligible weights
# efficient portfolio allocation
ef = EfficientFrontier(mu, cs)
ef.add_objective(objective_functions.L2_reg, gamma=0.1)
w = ef.max_sharpe()
print(ef.clean_weights())

# Post-processing weights
# These are the quantities of shares that should be bought to have a $20,000 portfolio
latest_prices = get_latest_prices(assets)
da = DiscreteAllocation(w, latest_prices, total_portfolio_value=20000)
allocation, leftover = da.lp_portfolio()
print2(allocation)
#optimize for max sharpe ratio
#sharpe ratio = measures the performance of an investment compared to a risk-free asset, after adjusting for its risk

ef = EfficientFrontier(mu, S)
weights = ef.max_sharpe() #Maximize the Sharpe ratio, and get the raw weights #effcient frointier weights
cleaned_weights = ef.clean_weights() 
print(cleaned_weights) #Note the weights may have some rounding error, meaning they may not add up exactly to 1 but should be close #for true value remove cleaned_weights
ef.portfolio_performance(verbose=True)

0.1209 + 0.32815 + 0.22299 + 0.32796 + 0.0

#testing to see if it equals 1

# 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 #double check [34]l6 for weight change 
da = DiscreteAllocation(weights, latest_prices, total_portfolio_value = 150000) #the amount of money willing to invest 

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

"""the above shows how many shares can be bought with a given set of funds in dollars US. In a weighted optimized format to optimize the purchase using sharpes ratio .

while giving you the remaining funds 



"""
def main():

  etfs_meta = { 'SPY': 'SPDR S&P 500 ETF Trust'
        , 'XLF': 'Financial Select Sector SPDR Fund'
        , 'QQQ': 'Invesco QQQ Trust' 
        , 'XLE': 'Energy Select Sector SPDR Fund'
        , 'IAU': 'iShares Gold Trust'
        , 'KRE': 'SPDR S&P Regional Banking ETF'
        , 'XLI': 'Industrial Select Sector SPDR Fund'
        , 'IYR': 'iShares U.S. Real Estate ETF'
        , 'IEFA': 'iShares Core MSCI EAFE ETF'
        , 'XLP': 'Consumer Staples Select Sector SPDR Fund'}


  etfs_options = list(etfs_meta.keys())

  start_date = "2015-01-01"
  # t-1
  yesterday = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d") 
  end_date = yesterday

  @st.cache
  def load_data(etfs, start, end):
      df = yf.download(" ".join(etfs), start=start, end=end)['Adj Close']
      return df

  df = load_data(etfs_options, start_date, end_date)
  returns = df.pct_change().dropna()
  
  st.markdown("---")
  st.subheader("ETF list")

  etfs_metadata_df = pd.DataFrame.from_dict(etfs_meta, orient='index').reset_index().rename(columns={"index": "Ticker", 0: "Short description"})
  st.table(etfs_metadata_df)

  st.markdown("---")
  st.subheader("Historical prices")

  df_temp = df.copy()
  df_temp['Date'] = df_temp.index
  df_plot = pd.melt(df_temp, id_vars='Date', value_vars=df_temp.columns[:-1]).rename(columns={'variable': 'Asset', 'value': 'Price ($)'})
  fig = px.line(df_plot, x='Date', y='Price ($)', color='Asset')
  st.plotly_chart(fig)


  st.subheader("Parameters")

  etfs_chosen = st.multiselect(
  'Which ETFs would you like to potentially add into your portfolio? (recommended to include all)',
  etfs_options, default=etfs_options)

  investment_amount = st.slider('Investment amount (between 1000 and 10000)', 1000, 10000, 1000)
  st.write('Your chosen amount is', '$' + str(investment_amount))


  if st.checkbox("All set, let's run the model!"):

      df = df[etfs_chosen]

      # calculate expected returns
      mu = expected_returns.mean_historical_return(df)

      mu_df = pd.DataFrame(mu).reset_index().rename(columns={"index": "Ticker", 0: "Expected Return (%)"}).sort_values(by="Expected Return (%)", ascending=False)
      mu_df['Expected Return (%)'] = round(mu_df['Expected Return (%)']*100,2)

      st.subheader("Expected returns")
      st.markdown("Showing returns that we could expect when taking into account historical data.")
      fig = px.bar(mu_df, x='Ticker', y='Expected Return (%)', width=300, height=200)
      st.plotly_chart(fig)

      # calculate estimated covariance matrix (risk model) using Ledoit-Wolf shrinkage
      # reduces the extreme values in the covariance matrix 
      S = risk_models.CovarianceShrinkage(df).ledoit_wolf()

      st.subheader("Covariance matrix")
      st.markdown("Showing relationship in price movement between different ETFs.")
      sns.heatmap(S.corr())
      st.pyplot()

      # Optimize the portfolio performance
      # Sharpe ratio: portfolio's return less risk-free rate, per unit of risk (volatility)

      ef = EfficientFrontier(mu, S, weight_bounds=(0.01, 1))

      weights = ef.max_sharpe()
      cleaned_weights = ef.clean_weights()

      portfolio_performance = ef.portfolio_performance()
      st.markdown("---")
      st.subheader("Portfolio performance")
      st.markdown('Summary metrics:')
      st.markdown('Expected annual return: {:.2f}%'.format(portfolio_performance[0]*100))
      st.markdown('Annual volatility: {:.2f}%'.format(portfolio_performance[1]*100))
      st.markdown('Sharpe Ratio: {:.2f}'.format(portfolio_performance[2]))

      latest_prices = get_latest_prices(df)
      da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=investment_amount)

      latest_prices_column = pd.DataFrame(latest_prices).columns[0]
      latest_prices_df = pd.DataFrame(latest_prices).reset_index().rename(columns={"index": "Ticker", latest_prices_column: "Latest Price"}).sort_values(by='Ticker')

      allocation, leftover = da.lp_portfolio()

      st.subheader("Portfolio allocation")

      allocation_df = pd.DataFrame.from_dict(allocation, orient='index').reset_index().rename(columns={"index": "Ticker", 0: "Shares"}).sort_values(by='Ticker')
      allocation_df = pd.merge(allocation_df, latest_prices_df, on='Ticker', how='left')
      allocation_df['Amount'] = allocation_df['Shares'] * allocation_df['Latest Price']
      allocation_df.sort_values(by='Amount', inplace=True, ascending=False)

      allocation_df['Allocation percentage'] = ((allocation_df['Amount'] / allocation_df['Amount'].sum())*100).round(2)
      allocation_df['Amount'] = ['$' + str(round(item,2)) for item in allocation_df['Amount']]
      allocation_df['Latest Price'] = ['$' + str(round(item,2)) for item in allocation_df['Latest Price']]
      
      allocation_df.reset_index(inplace=True, drop=True)

      st.table(allocation_df)

      title = "Allocation visualization (# of shares)"
      fig = px.bar(allocation_df, x='Ticker', y='Shares', width=600, height=400,title=title)
      st.plotly_chart(fig)

      title = "Allocation visualization (% invested)"
      fig = px.bar(allocation_df, x='Ticker', y='Allocation percentage', width=600, height=400,title=title)
      st.plotly_chart(fig)

      invested_amount = investment_amount - leftover
      st.markdown('Funds invested: ${:.2f}'.format(invested_amount))
      st.markdown('Funds remaining: ${:.2f}'.format(leftover))
Example #6
0
            def get_momentum_stocks(df, date, portfolio_size, cash):
                # Filter the df to get the top 10 momentum stocks for the latest day
                df_top_m = df.loc[df['date'] == pd.to_datetime(date)]
                df_top_m = df_top_m.sort_values(by='momentum', ascending=False).head(portfolio_size)

                # Set the universe to the top momentum stocks for the period
                universe = df_top_m['symbol'].tolist()

                # Create a df with just the stocks from the universe
                df_u = df.loc[df['symbol'].isin(universe)]

                # Create the portfolio
                # Pivot to format for the optimization library
                df_u = df_u.pivot_table(
                    index='date', 
                    columns='symbol',
                    values='close',
                    aggfunc='sum'
                    )

                # Calculate expected returns and sample covariance
                mu = expected_returns.mean_historical_return(df_u)
                S = risk_models.sample_cov(df_u)

                # Optimise the portfolio for maximal Sharpe ratio
                ef = EfficientFrontier(mu, S, gamma=1) # Use regularization (gamma=1)
                weights = ef.max_sharpe()
                cleaned_weights = ef.clean_weights()

                # Allocate
                latest_prices = get_latest_prices(df_u)

                da = DiscreteAllocation(
                    cleaned_weights,
                    latest_prices,
                    total_portfolio_value=cash
                    )

                allocation = da.lp_portfolio()[0]

                # Put the stocks and the number of shares from the portfolio into a df
                symbol_list = []
                num_shares_list = []

                for symbol, num_shares in allocation.items():
                    symbol_list.append(symbol)
                    num_shares_list.append(num_shares)

                # Now that we have the stocks we want to buy we filter the df for those ones
                df_buy = df.loc[df['symbol'].isin(symbol_list)]

                # Filter for the period to get the closing price
                df_buy = df_buy.loc[df_buy['date'] == date].sort_values(by='symbol')

                # Add in the qty that was allocated to each stock
                df_buy['qty'] = num_shares_list

                # Calculate the amount we own for each stock
                df_buy['amount_held'] = df_buy['close'] * df_buy['qty']
                df_buy = df_buy.loc[df_buy['qty'] != 0]
                return df_buy
Example #7
0
# In[15]:
"""
We could have a portfolio with annual vol of 11.4% and expected annual return of 22.3%. 
It is possible to obtain a positive SR by defining portfolios with stocks that are part of the ibovespa index.
This output, despite interesting, is not useful in itself. Let's then convert it into an allocation that 
an investor could use to weight her own portfolio
"""

# In[18]:

from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices

latest_prices = get_latest_prices(df)

da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=100000)
allocation, leftover = da.lp_portfolio()
print("Discrete allocation", allocation)
print("Funds remaining: ${:.2f}".format(leftover))

# In[20]:

import pandas as pd

pd.Series(weights).plot.pie(figsize=(10, 10))

# In[21]:
"""
As we may check from the output, only part of the stocks compounding the Ibovespa index were selected to
be part of our SP maximised portfolio. Let's now conduct some exercises, obtaining other portfolios
for different risks. Let's remember that, according to the model for a long-only portfolio, the investor
ef.portfolio_performance()

c1.subheader('Χαρτοφυλάκιο Νο1')
c1.write(
    'Το προτινόμενο χαρτοφυλάκιο από τις ιστορικές τιμές των επιλεγμένων μετοχών έχει τα παρακάτω χαρακτηριστικά'
)
c1.write('Αρχική Αξία Χαρτοφυλακίου : ' + str(port_value) + '€')
c1.write('Sharpe Ratio: ' + str(round(ef.portfolio_performance()[2], 2)))
c1.write('Απόδοση Χαρτοφυλακίο: ' +
         str(round(ef.portfolio_performance()[0] * 100, 2)) + '%')
c1.write('Μεταβλητότητα Χαρτοφυλακίου: ' +
         str(round(ef.portfolio_performance()[1] * 100, 2)) + '%')
# Allocate
latest_prices = get_latest_prices(df_t)
da = DiscreteAllocation(cleaned_weights,
                        latest_prices,
                        total_portfolio_value=port_value)
if allocmo:
    allocation = da.greedy_portfolio()[0]
    non_trading_cash = da.greedy_portfolio()[1]
else:
    allocation = da.lp_portfolio()[0]
    non_trading_cash = da.lp_portfolio()[1]
# Put the stocks and the number of shares from the portfolio into a df
symbol_list = []
cw = []
num_shares_list = []
l_price = []
tot_cash = []
for symbol, num_shares in allocation.items():
    symbol_list.append(symbol)
def rebalnce_portfolios():

    p = abspath(getsourcefile(lambda: 0))
    p = p.rsplit('/', 1)[0]
    os.chdir(p)
    print('Working Directory is: %s' % os.getcwd())

    file_path = p + '/results_2015-2019/'  # !!! Editable Folder with files with weights
    start_time = '2015-01-01'  # !!! start date, editable
    end_time = (datetime.today() - timedelta(days=1)).strftime(
        '%Y-%m-%d')  # last day = day before today

    # Lists of files with portfolio weights
    files = [f for f in listdir(file_path) if isfile(join(file_path, f))]
    files = [f for f in files if f.startswith('portfolio_investment')]
    files = [file_path + f for f in files]
    files = sorted(files)

    weight_bounds_tuple = (
        (0.0, 0.1), (0.0, 0.1), (0.0, 0.15), (0.0, 0.05), (0.0, 0.05), (0.01,
                                                                        0.1)
    )  # !!! Weights to be adjusted for every iteration by arbitrary value
    gamma = 0.05

    total_portfolio_value = 20000

    for i in range(0, len(files)):

        portfolio = pd.read_csv(files[i], index_col=0).iloc[:, 0:6]

        tickers = portfolio.iloc[:, 2].tolist(
        )  # tickers inside portfolio (they will be updated)

        # Getting stock data (maybe re-do to for loop, if there be problems with memory)
        temp = pdr.DataReader(tickers, 'yahoo', start_time, end_time)['Close']

        current_weights = portfolio['allocation_weight'].to_list()

        risk_free_rate = 0.0085  # !!! Risk-free rate, 10Y US treasury bond, could be adjusted
        weight_bounds = weight_bounds_tuple[
            i]  # taken from the tuple each iteration, defined at the beginning

        # !!! Different approaches could be taken from here
        mu = mean_historical_return(temp)  # Getting returns
        S = CovarianceShrinkage(temp).ledoit_wolf()  # Getting cov matrix

        # Main function to find optimal portfolio, determining optimal weights
        ef = EfficientFrontier(mu, S, weight_bounds=weight_bounds)
        ef.add_objective(objective_functions.transaction_cost,
                         w_prev=current_weights,
                         k=0.005)
        ef.add_objective(objective_functions.L2_reg, gamma=gamma)
        weights = ef.max_sharpe(
            risk_free_rate=risk_free_rate)  # using max sharpe optimization
        cleaned_weights = ef.clean_weights()  # weights with pretty formatting
        print(cleaned_weights)

        # Printing info on returns, variance & sharpe
        ef.portfolio_performance(verbose=True)

        ### This function would change the weights to a number of shares based on the last price in the observable interval
        latest_prices = get_latest_prices(temp)
        da = DiscreteAllocation(weights,
                                latest_prices,
                                total_portfolio_value=total_portfolio_value)
        allocation, leftover = da.lp_portfolio()
        print(allocation)
        print("Money left: " + str(leftover))
        print(da._allocation_rmse_error())

        allocation = pd.DataFrame.from_dict(allocation, orient='index')
        allocation.columns = ['allocation_discrete']

        weights = pd.DataFrame.from_dict(weights, orient='index')
        weights.columns = ['allocation_weight']

        latest_prices = pd.DataFrame(latest_prices)
        latest_prices.columns = ['buy_price']

        tickers = pd.DataFrame(tickers)
        tickers.columns = ['ticker']
        tickers.index = tickers['ticker']

        result = pd.concat([weights, allocation, tickers, latest_prices],
                           axis=1)

        result['buy_investment'] = result['allocation_discrete'] * result[
            'buy_price']
        result['actual_allocation'] = result['buy_investment'] / result[
            'buy_investment'].sum()

        # Get paths & filenames for saving with replacing old csv files
        n = files[i].split('_')[-1]
        s = file_path + 'portfolio_ticker_' + n

        result.to_csv(s)
Example #10
0
from pypfopt import black_litterman
from pypfopt.black_litterman import BlackLittermanModel

# Reading in the data; preparing expected returns and a risk model
df = pd.read_csv("tests/stock_prices.csv", parse_dates=True, index_col="date")
returns = df.pct_change().dropna()
mu = expected_returns.mean_historical_return(df)
S = risk_models.sample_cov(df)

# Long-only Maximum Sharpe portfolio, with discretised weights
ef = EfficientFrontier(mu, S)
weights = ef.max_sharpe()
ef.portfolio_performance(verbose=True)
latest_prices = get_latest_prices(df)

da = DiscreteAllocation(weights, latest_prices)
allocation, leftover = da.lp_portfolio()
print("Discrete allocation:", allocation)
print("Funds remaining: ${:.2f}".format(leftover))
"""
Expected annual return: 33.0%
Annual volatility: 21.7%
Sharpe Ratio: 1.43

11 out of 20 tickers were removed
Discrete allocation: {'GOOG': 0, 'AAPL': 5, 'FB': 11, 'BABA': 5, 'AMZN': 1,
                      'BBY': 7, 'MA': 14, 'PFE': 50, 'SBUX': 5}
Funds remaining: $8.42
"""

# Long-only minimum volatility portfolio, with a weight cap and regularisation
Example #11
0
def optimise_portfolio(stocks,
                       timeframe: Timeframe,
                       algo="ef-minvol",
                       max_stocks=80,
                       total_portfolio_value=100 * 1000,
                       exclude_price=None):
    assert len(stocks) >= 1
    assert timeframe is not None
    assert total_portfolio_value > 0
    assert max_stocks >= 5

    messages = set()
    all_returns, stock_prices, latest_prices, first_prices = setup_optimisation_matrices(
        stocks, timeframe, messages, exclude_price)
    for t in ((10, 0.0001), (20, 0.0005), (30, 0.001), (40, 0.005), (50,
                                                                     0.01)):
        filtered_stocks, n_stocks = select_suitable_stocks(
            all_returns, stock_prices, max_stocks, *t)
        strategy, title, kwargs, mu, s = assign_strategy(
            filtered_stocks, algo, n_stocks)

        try:
            weights, performance_dict, _ = strategy(**kwargs)
            allocator = DiscreteAllocation(
                weights,
                first_prices,
                total_portfolio_value=total_portfolio_value)
            fig, ax = plt.subplots()
            portfolio, leftover_funds = allocator.greedy_portfolio()
            #print(portfolio)
            cleaned_weights = clean_weights(weights, portfolio, first_prices,
                                            latest_prices)

            # disabled due to TypeError during deepcopy of OSQP results object
            #if algo.startswith("ef"): # HRP doesnt support frontier plotting atm
            #    plot_efficient_frontier(ef, ax=ax, show_assets=False)
            volatility = performance_dict.get('volatility')
            expected_return = performance_dict.get('expected return')
            ax.scatter(volatility,
                       expected_return,
                       marker="*",
                       s=100,
                       c="r",
                       label="Portfolio")
            ax.set_xlabel("Volatility")
            ax.set_ylabel("Returns (%)")

            # Generate random portfolios
            n_samples = 10000
            w = np.random.dirichlet(np.ones(n_stocks), n_samples)
            rets = w.dot(mu)
            stds = np.sqrt(np.diag(w @ s @ w.T))
            sharpes = rets / stds
            ax.scatter(stds, rets, marker=".", c=sharpes, cmap="viridis_r")

            # Output
            ax.set_title(title)
            ax.legend()
            plt.tight_layout()
            fig = plt.gcf()
            efficient_frontier_plot = plot_as_base64(fig)
            plt.close(fig)

            # only plot covmatrix/corr for significant holdings to ensure readability
            m = CovarianceShrinkage(filtered_stocks[list(
                cleaned_weights.keys())[:30]]).ledoit_wolf()
            #print(m)
            ax = plot_covariance(m, plot_correlation=True)
            correlation_plot = plot_as_base64(ax.figure)
            plt.close(ax.figure)
            assert isinstance(cleaned_weights, OrderedDict)
            return cleaned_weights, performance_dict, \
                   efficient_frontier_plot, correlation_plot, messages, \
                   title, total_portfolio_value, leftover_funds, len(latest_prices)
        except ValueError as ve:
            messages.add(
                "Unable to optimise stocks with min_unique={} and var_min={}: n_stocks={} - {}"
                .format(t[0], t[1], n_stocks, str(ve)))
            # try next iteration

    print("*** WARNING: unable to optimise portolio!")
    return (None, None, None, None, messages, title, total_portfolio_value,
            0.0, len(latest_prices))
print('Expected Annual Volitility:'+ percent_vols)
print('Expected Annual Varriance:'+ percent_var)

pip install PyPortfolioOpt

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

#portfolio Optimization!
#calculate expected returns annualize sample matrix of asset returns
mu = expected_returns.mean_historical_return(df)
S = risk_models.sample_cov(df)

#max sharp ratio
ef = EfficientFrontier(mu, S)
weightage = ef.max_sharpe()
clean_weights = ef.clean_weights() 
print(clean_weights)
ef.portfolio_performance(verbose = True)

#Get the discret alloation of stocks
from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices

latest_prices = get_latest_prices(df)
weightage = clean_weights
da = DiscreteAllocation(weightage, latest_prices, total_portfolio_value = 7200000)

allocation, leftover = da.lp_portfolio()
print('Discrete allocation:', allocation)
print('Funds Remaining $:'.format(leftover))
    def create_portfolio(self):
        if len(self.all_tickers) == 0:
            return
        self.ui.progressBar.setVisible(True)
        self.ui.progressBar.setValue(0)
        df = pd.DataFrame()

        all_tickers = list(self.all_tickers)
        num_all_tickers = len(all_tickers)
        part_each_ticker_progressBar = 90 / num_all_tickers
        for idx, symbol in enumerate(all_tickers):
            try:
                df[symbol] = pdr.get_data_yahoo(
                    symbol,
                    start=datetime.datetime(2006, 1, 1),
                    end=datetime.datetime.now())["Adj Close"]
            except Exception as e:
                print(e)
                continue
            self.ui.progressBar.setValue(
                (idx + 1) * part_each_ticker_progressBar)

        mu = expected_returns.mean_historical_return(df)
        S = risk_models.sample_cov(df)

        ef = EfficientFrontier(mu, S)
        ef.max_sharpe()
        cleaned_weights = ef.clean_weights()
        mu, sigma, sharpe = ef.portfolio_performance(verbose=False)

        portfolio_val = self.ui.spinBox.value()
        latest_prices = get_latest_prices(df)
        self.weights = cleaned_weights
        da = DiscreteAllocation(self.weights,
                                latest_prices,
                                total_portfolio_value=portfolio_val)
        allocation, leftover = da.greedy_portfolio()

        self.ui.progressBar.setValue(100)

        ##-- Page 2 <Parameters>
        from Pick_up_portfolio_class import pandasModel
        self.ui.stackedWidget.setCurrentWidget(self.ui.page_2)

        self.btn_page_2_visible()

        self.ui.progressBar.setVisible(False)
        self.ui.label_2.setText("Ожидаемая годовая доходность: {:.1f}%\n"
                                "Годовая волатильность: {:.1f}%\n"
                                "Коэффициент Шарпа: {:.2f}\n"
                                "Остаток средств: {:.2f}$".format(
                                    100 * mu, 100 * sigma, sharpe, leftover))

        company_name = []
        for symbol in allocation:
            company_name.append(get_company_name(symbol))
        discrete_allocation_list = []
        for symbol in allocation:
            discrete_allocation_list.append(allocation.get(symbol))
        portfolio_df = pd.DataFrame(columns=[
            'Название компании', 'Тикер компании', 'Количество',
            'Последняя цена, $', 'Сумма в портфеле, $'
        ])
        portfolio_df['Название компании'] = company_name
        portfolio_df['Тикер компании'] = allocation
        portfolio_df['Количество'] = discrete_allocation_list
        portfolio_df['Последняя цена, $'] = np.round(
            get_latest_prices(df)[allocation].values, 2)
        portfolio_df['Сумма в портфеле, $'] = np.round(
            portfolio_df['Последняя цена, $'] * portfolio_df['Количество'], 2)
        portfolio_df = portfolio_df.sort_values(by='Количество',
                                                ascending=False)

        model = pandasModel(portfolio_df)
        self.ui.tableView.verticalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.ui.tableView.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.ui.tableView.setModel(model)