Skip to content

Commit

Permalink
Chore/pylint improvements (#100)
Browse files Browse the repository at this point in the history
Only code quality changes made
  • Loading branch information
fmilthaler committed Jul 15, 2023
1 parent e90ef79 commit 99d9ca9
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 129 deletions.
19 changes: 10 additions & 9 deletions .pylintrc
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
[MASTER]
# Ignore certain files or directories during analysis
ignore-paths=tests/,docs/,example/

[REPORTS]
# Set the output format for `pylint` messages (text, colorized, json, etc.)
output-format=text

# Ignore certain files or directories during analysis
ignore-patterns=tests/, docs/

[MESSAGES CONTROL]
# Specify the maximum allowed line length
max-line-length=120

# Disable some pylint messages that may be too strict or not relevant for your project
disable=
C0103, # Naming convention violation
# C0114, # Missing module, function, class docstring
C0114, # Missing module docstring
C0116, # Missing function docstring
R0903, # Too few public methods
R0913, # Too many arguments
R0914, # Too many local variables
# R0903, # Too few public methods

# Include additional pylint messages or message categories
enable=
C0114, # Missing module, function, class docstring
R0903, # Too few public methods
#enable=
# C0114, # Missing module, function, class docstring
# R0903, # Too few public methods
28 changes: 16 additions & 12 deletions finquant/efficient_frontier.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from finquant.quants import annualised_portfolio_quantities


class EfficientFrontier(object):
class EfficientFrontier:
"""An object designed to perform optimisations based on minimising a cost/objective function.
It can find parameters for portfolios with
Expand Down Expand Up @@ -126,8 +126,10 @@ def minimum_volatility(self, save_weights=True):
"""
if not isinstance(save_weights, bool):
raise ValueError("save_weights is expected to be a boolean.")

args = (self.mean_returns.values, self.cov_matrix.values)
# optimisation

# Optimization
result = sco.minimize(
min_fun.portfolio_volatility,
args=args,
Expand All @@ -136,9 +138,11 @@ def minimum_volatility(self, save_weights=True):
bounds=self.bounds,
constraints=self.constraints,
)
# if successful, set self.last_optimisation

# Set the last optimization
self.last_optimisation = "Minimum Volatility"
# set optimal weights

# Set optimal weights
if save_weights:
self.weights = result["x"]
self.df_weights = self._dataframe_weights(self.weights)
Expand Down Expand Up @@ -307,7 +311,7 @@ def efficient_frontier(self, targets=None):
"""
if targets is not None and not isinstance(targets, (list, np.ndarray)):
raise ValueError("targets is expected to be a list or numpy.ndarray")
elif targets is None:
if targets is None:
# set range of target returns from the individual expected
# returns of the stocks in the portfolio.
min_return = self.mean_returns.min() * self.freq
Expand Down Expand Up @@ -420,14 +424,14 @@ def properties(self, verbose=False):
)
if verbose:
string = "-" * 70
string += "\nOptimised portfolio for {}".format(self.last_optimisation)
string += "\n\nTime window/frequency: {}".format(self.freq)
string += "\nRisk free rate: {}".format(self.risk_free_rate)
string += "\nExpected annual Return: {:.3f}".format(expected_return)
string += "\nAnnual Volatility: {:.3f}".format(volatility)
string += "\nSharpe Ratio: {:.3f}".format(sharpe)
string += f"\nOptimised portfolio for {self.last_optimisation}"
string += f"\n\nTime window/frequency: {self.freq}"
string += f"\nRisk free rate: {self.risk_free_rate}"
string += f"\nExpected annual Return: {expected_return:.3f}"
string += f"\nAnnual Volatility: {volatility:.3f}"
string += f"\nSharpe Ratio: {sharpe:.3f}"
string += "\n\nOptimal weights:"
string += "\n" + str(self.df_weights.transpose())
string += f"\n{str(self.df_weights.transpose())}"
string += "\n"
string += "-" * 70
print(string)
Expand Down
12 changes: 6 additions & 6 deletions finquant/market.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from finquant.returns import daily_returns, historical_mean_return


class Market(object):
class Market:
"""Object that contains information about a market index.
To initialise the object, it requires a name and information about
the index given as ``pandas.Series`` data structure.
Expand Down Expand Up @@ -72,11 +72,11 @@ def properties(self):
"""
# nicely printing out information and quantities of market index
string = "-" * 50
string += "\Market index: {}".format(self.name)
string += "\nExpected Return:{:0.3f}".format(self.expected_return)
string += "\nVolatility: {:0.3f}".format(self.volatility)
string += "\nSkewness: {:0.5f}".format(self.skew)
string += "\nKurtosis: {:0.5f}".format(self.kurtosis)
string += f"\nMarket index: {self.name}"
string += f"\nExpected Return:{self.expected_return:0.3f}"
string += f"\nVolatility: {self.volatility:0.3f}"
string += f"\nSkewness: {self.skew:0.5f}"
string += f"\nKurtosis: {self.kurtosis:0.5f}"
string += "-" * 50
print(string)

Expand Down
34 changes: 14 additions & 20 deletions finquant/monte_carlo.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from finquant.quants import annualised_portfolio_quantities


class MonteCarlo(object):
class MonteCarlo:
"""An object to perform a Monte Carlo run/simulation."""

def __init__(self, num_trials=1000):
Expand All @@ -32,7 +32,7 @@ def run(self, fun, **kwargs):
:result: List of quantities returned from `fun` at each iteration.
"""
result = []
for i in range(self.num_trials):
for _ in range(self.num_trials):
res = fun(**kwargs)
result.append(res)
return np.asarray(result, dtype=object)
Expand Down Expand Up @@ -93,7 +93,7 @@ def __init__(
self.freq = freq
self.initial_weights = initial_weights
# initiate super class
super(MonteCarloOpt, self).__init__(num_trials=self.num_trials)
super().__init__(num_trials=self.num_trials)
# setting additional variables
self.num_stocks = len(self.returns.columns)
self.return_means = self.returns.mean()
Expand All @@ -113,14 +113,14 @@ def _random_weights(self):
list of [expected return, volatility, sharpe ratio].
"""
# select random weights for portfolio
w = np.array(np.random.random(self.num_stocks))
weights = np.array(np.random.random(self.num_stocks))
# rebalance weights
w = w / np.sum(w)
weights = weights / np.sum(weights)
# compute portfolio return and volatility
portfolio_values = annualised_portfolio_quantities(
w, self.return_means, self.cov_matrix, self.risk_free_rate, self.freq
weights, self.return_means, self.cov_matrix, self.risk_free_rate, self.freq
)
return (w, np.array(portfolio_values))
return (weights, np.array(portfolio_values))

def _random_portfolios(self):
"""Performs a Monte Carlo run and gets a list of random portfolios
Expand Down Expand Up @@ -186,7 +186,7 @@ def plot_results(self):
or self.opt_weights is None
or self.opt_results is None
):
raise Exception(
raise ValueError(
"Error: Cannot plot, run the Monte Carlo " + "optimisation first."
)
# create scatter plot coloured by Sharpe Ratio
Expand Down Expand Up @@ -253,18 +253,12 @@ def properties(self):
string = ""
for val in opt_vals:
string += "-" * 70
string += "\nOptimised portfolio for {}".format(
val.replace("Min", "Minimum").replace("Max", "Maximum")
)
string += "\n\nTime period: {} days".format(self.freq)
string += "\nExpected return: {0:0.3f}".format(
self.opt_results.loc[val]["Expected Return"]
)
string += "\nVolatility: {:0.3f}".format(
self.opt_results.loc[val]["Volatility"]
)
string += "\nSharpe Ratio: {:0.3f}".format(
self.opt_results.loc[val]["Sharpe Ratio"]
string += f"\nOptimised portfolio for {val.replace('Min', 'Minimum').replace('Max', 'Maximum')}"
string += f"\n\nTime period: {self.freq} days"
string += f"\nExpected return: {self.opt_results.loc[val]['Expected Return']:0.3f}"
string += f"\nVolatility: {self.opt_results.loc[val]['Volatility']:0.3f}"
string += (
f"\nSharpe Ratio: {self.opt_results.loc[val]['Sharpe Ratio']:0.3f}"
)
string += "\n\nOptimal weights:"
string += "\n" + str(
Expand Down
Loading

0 comments on commit 99d9ca9

Please sign in to comment.