示例#1
0
 def _get_ef(self):
     """If self.ef does not exist, create and return an instance of
     finquant.efficient_frontier.EfficientFrontier, else, return the
     existing instance.
     """
     if self.ef is None:
         # create instance of EfficientFrontier
         self.ef = EfficientFrontier(
             self.comp_mean_returns(freq=1),
             self.comp_cov(),
             risk_free_rate=self.risk_free_rate,
             freq=self.freq,
         )
     return self.ef
# <codecell>

# maximum Sharpe ratio for a given target volatility of 0.22
pf.ef_efficient_volatility(0.22, verbose=True)

# <markdowncell>

# ### Manually creating an instance of EfficientFrontier
# If required, or preferred, the below code shows how the same is achieved by manually creating an instance of EfficientFrontier, passing it the mean returns and covariance matrix of the previously assembled portfolio.

# <codecell>

from finquant.efficient_frontier import EfficientFrontier

# creating an instance of EfficientFrontier
ef = EfficientFrontier(pf.comp_mean_returns(freq=1), pf.comp_cov())
# optimisation for minimum volatility
print(ef.minimum_volatility())

# <codecell>

# printing out relevant quantities of the optimised portfolio
(expected_return, volatility, sharpe) = ef.properties(verbose=True)

# <markdowncell>

# ### Computing and visualising the Efficient Frontier
# `FinQuant` offers several ways to compute the *Efficient Frontier*.
#  1. Through the opject `pf`
#   - with automatically setting limits of the *Efficient Frontier*
#  2. By manually creating an instance of `EfficientFrontier` and providing the data from the portfolio
# performs and plots results of Monte Carlo run (5000 iterations)
opt_w, opt_res = pf.mc_optimisation(num_trials=5000)
# plots the results of the Monte Carlo optimisation
pf.mc_plot_results()
# plots the Efficient Frontier
pf.ef_plot_efrontier()
# plots optimal portfolios based on Efficient Frontier
pf.ef.plot_optimal_portfolios()
# plots individual plots of the portfolio
pf.plot_stocks()
plt.show()

print(' ')
print('optimised portfolio results')
# creating an instance of EfficientFrontier
ef = EfficientFrontier(pf.comp_mean_returns(freq=1), pf.comp_cov())
# optimisation for minimum volatility
print(ef.minimum_volatility())

# printing out relevant quantities of the optimised portfolio
(expected_return, volatility, sharpe) = ef.properties(verbose=True)

results = str(ef.minimum_volatility())

y = input("If you want to save results then say 'y' :" )

if y in  ['y', 'Y', 'yes', 'Yes', 'YES']:
    text_file = open('output.txt', 'w')
    text_file.write(results)
    text_file.close()
    print('saved in output.txt')