Code Monkey home page Code Monkey logo

finquant's Introduction

pypi pypi GitHub Actions docs contributors contributions license

FinQuant

FinQuant is a program for financial portfolio management, analysis and optimisation.

This README only gives a brief overview of FinQuant. The interested reader should refer to its documentation.

Table of contents

Motivation

Within a few lines of code, FinQuant can generate an object that holds your stock prices of your desired financial portfolio, analyses it, and can create plots of different kinds of Returns, Moving Averages, Moving Average Bands with buy/sell signals, and Bollinger Bands. It also allows for the optimisation based on the Efficient Frontier or a Monte Carlo run of the financial portfolio within a few lines of code. Some of the results are shown here.

Automatically generating an instance of Portfolio

finquant.portfolio.build_portfolio is a function that eases the creating of your portfolio. See below for one of several ways of using build_portfolio.

from finquant.portfolio import build_portfolio
names = ['GOOG', 'AMZN', 'MCD', 'DIS']
start_date = '2015-01-01'
end_date = '2017-12-31'
pf = build_portfolio(names=names,
                    start_date=start_date,
                    end_date=end_date)

pf is an instance of finquant.portfolio.Portfolio, which contains the prices of the stocks in your portfolio. Then...

pf.data.head(3)

yields

              GOOG    AMZN        MCD        DIS
Date
2015-01-02  524.81  308.52  85.783317  90.586146
2015-01-05  513.87  302.19  84.835892  89.262380
2015-01-06  501.96  295.29  84.992263  88.788916

Portfolio properties

Nicely printing out the portfolio's properties

pf.properties()

Depending on the stocks within your portfolio, the output looks something like the below.

----------------------------------------------------------------------
Stocks: GOOG, AMZN, MCD, DIS
Time window/frequency: 252
Risk free rate: 0.005
Portfolio expected return: 0.266
Portfolio volatility: 0.156
Portfolio Sharpe ratio: 1.674

Skewness:
       GOOG      AMZN      MCD       DIS
0  0.124184  0.087516  0.58698  0.040569

Kurtosis:
       GOOG      AMZN       MCD       DIS
0 -0.751818 -0.856101 -0.602008 -0.892666

Information:
   Allocation  Name
0        0.25  GOOG
1        0.25  AMZN
2        0.25   MCD
3        0.25   DIS
----------------------------------------------------------------------

Cumulative Return

pf.comp_cumulative_returns().plot().axhline(y = 0, color = "black", lw = 3)

yields

Band Moving Average (Buy/Sell Signals)

from finquant.moving_average import compute_ma, ema
# get stock data for disney
dis = pf.get_stock("DIS").data.copy(deep=True)
spans = [10, 50, 100, 150, 200]
ma = compute_ma(dis, ema, spans, plot=True)

yields

Bollinger Band

from finquant.moving_average import plot_bollinger_band, sma
# get stock data for disney
dis = pf.get_stock("DIS").data.copy(deep=True)
span=20
plot_bollinger_band(dis, sma, span)

yields

Portfolio Optimisation

# 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()

Installation

As it is common for open-source projects, there are several ways to get hold of the code. Choose whichever suits you and your purposes best.

Dependencies

FinQuant depends on the following Python packages:

  • python>=3.10
  • numpy>=1.15
  • pandas>=2.0
  • matplotlib>=3.0
  • quandl>=3.4.5
  • yfinance>=0.1.43
  • scipy>=1.2.0
  • scikit-learn>=1.3.0

From PyPI

FinQuant can be obtained from PyPI

pip install FinQuant

From GitHub

Get the code from GitHub:

git clone https://github.com/fmilthaler/FinQuant.git

Then inside FinQuant run:

python setup.py install

Alternatively, if you do not wish to install FinQuant, you can also download/clone it as stated above, and then make sure to add it to your PYTHONPATH.

Portfolio Management

This is the core of FinQuant. finquant.portfolio.Portfolio provides an object that holds prices of all stocks in your portfolio, and automatically computes the most common quantities for you. To make FinQuant an user-friendly program, that combines data analysis, visualisation and optimisation, the object provides interfaces to the main features that are provided in the modules in ./finquant/.

To learn more about the object, please read through the documentation, docstring of the module/class, and/or have a look at the examples.

finquant.portfolio.Portfolio also provides a function build_portfolio which is designed to automatically generate an instance of Portfolio for the user's convenience. For more information on how to use build_portfolio, please refer to the documentation, its docstring and/or have a look at the examples.

Returns

Daily returns of stocks are often computed in different ways. FinQuant provides three different ways of computing the daily returns in finquant.returns:

  1. The cumulative return:
  2. Percentage change of daily returns:
  3. Log Return:

In addition to those, the module provides the function historical_mean_return(data, freq=252), which computes the historical mean of the daily returns over a time period freq.

Moving Averages

The module finquant.moving_average allows the computation and visualisation of Moving Averages of the stocks listed in the portfolio is also provided. It entails functions to compute and visualise the

  • sma: Simple Moving Average, and
  • ema: Exponential Moving Average.
  • compute_ma: a Band of Moving Averages (of different time windows/spans) including Buy/Sell signals
  • plot_bollinger_band: a Bollinger Band for
    • sma,
    • ema.

Portfolio Optimisation

Efficient Frontier

An implementation of the Efficient Frontier (finquant.efficient_frontier.EfficientFrontier) allows for the optimisation of the portfolio for

  • minimum_volatility Minimum Volatility,
  • maximum_sharpe_ratio Maximum Sharpe Ratio
  • efficient_return Minimum Volatility for a given expected return
  • efficient_volatility Maximum Sharpe Ratio for a given target volatility

by performing a numerical solve to minimise/maximise an objective function.

Often it is useful to visualise the Efficient Frontier as well as the optimal solution. This can be achieved with the following methods:

  • plot_efrontier: Plots the Efficient Frontier. If no minimum/maximum Return values are provided, the algorithm automatically chooses those limits for the Efficient Frontier based on the minimum/maximum Return values of all stocks within the given portfolio.
  • plot_optimal_portfolios: Plots markers of the portfolios with the Minimum Volatility and Maximum Sharpe Ratio.

For reasons of user-friendliness, interfaces to these functions are provided in finquant.portfolio.Portfolio. Please have a look at the documentation.

Monte Carlo

Alternatively a Monte Carlo run of n trials can be performed to find the optimal portfolios for

  • minimum volatility,
  • maximum Sharpe ratio

The approach branded as Efficient Frontier should be the preferred method for reasons of computational effort and accuracy. The latter approach is only included for the sake of completeness, and creation of beautiful plots.

Examples

For more information about the project and details on how to use it, please look at the examples provided in ./example.

Note: In the below examples, pf refers to an instance of finquant.portfolio.Portfolio, the object that holds all stock prices and computes its most common quantities automatically. To make FinQuant a user-friendly program, that combines data analysis, visualisation and optimisation, the object also provides interfaces to the main features that are provided in the modules in ./finquant/ and are discussed throughout this README.

Building a portfolio with data from web

./example/Example-Build-Portfolio-from-web.py: Shows how to use FinQuant to build a financial portfolio by downloading stock price data through the Python package quandl/yfinance.

Building a portfolio with preset data

./example/Example-Build-Portfolio-from-file.py: Shows how to use FinQuant to build a financial portfolio by providing stock price data yourself, e.g. by reading data from disk/file.

Analysis of a portfolio

./example/Example-Analysis.py: This example shows how to use an instance of finquant.portfolio.Portfolio, get the portfolio's quantities, such as

  • Expected Returns,
  • Volatility,
  • Downside Risk,
  • Value at Risk,
  • Sharpe Ratio,
  • Sortino Ratio,
  • Treynor Ratio,
  • Beta parameter,
  • R squared coefficient.

It also shows how to extract individual stocks from the given portfolio. Moreover it shows how to compute and visualise:

  • the different Returns provided by the module finquant.returns,
  • Moving Averages, a band of Moving Averages, and a Bollinger Band.

Optimisation of a portfolio

./example/Example-Optimisation.py: This example focusses on the optimisation of a portfolio. To achieve this, the example shows the usage of finquant.efficient_frontier.EfficientFrontier for optimising the portfolio, for the

  • Minimum Volatility
  • Maximum Sharpe Ratio
  • Minimum Volatility for a given target Return
  • Maximum Sharpe Ratio for a given target Volatility.

Furthermore, it is also shown how the entire Efficient Frontier and the optimal portfolios can be computed and visualised. If needed, it also gives an example of plotting the individual stocks of the given portfolio within the computed Efficient Frontier.

Also, the optimisation of a portfolio and its visualisation based on a Monte Carlo is shown.

Finally, FinQuant's visualisation methods allow for overlays, if this is desired. Thus, with only the following few lines of code, one can create an overlay of the Monte Carlo run, the Efficient Frontier, its optimised portfolios for Minimum Volatility and Maximum Sharpe Ratio, as well as the portfolio's individual stocks.

finquant's People

Contributors

drcsturm avatar fmilthaler avatar herrfz avatar noxan avatar pietropaolofrisoni avatar slpenn13 avatar texify[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

finquant's Issues

Benchmarking Performance

Hi @fmilthaler and @PietropaoloFrisoni

Is there a way to compare the effectiveness of this program to a benchmarked or baseline run?

What I mean to say is, how can we see or quantify how well FinQuant is performing against no optimisation / a random-search optimisation? Currently, I'm not sure if there's such a way to evaluate how "well" the program is working, if you understand me correctly.

Thanks and I've been having a blast learning from FinQuant!

Update documentation

Some of the new classes, e.g. market and asset are currently not in the documentation
When you are bored... Redo documentation to include proper support for type hints (after type hints are consistently implemented and tested with mypy).

Naive question regarding Allocation

Hello Frank,

Awesome job on Finquant. I was trying to use however, I myself am new to finance. I had a question.
The allocation column in a portfolio. Are they number of units of stocks? or are they weighted?
also. How do I input what is my average price for which i bought these stocks?

Sorry had to ask you via issues since there was not other way to contact. you.

Thanks for your help

Regards

Sriram

Error on data download

getting error when i run the commend
pf = build_portfolio(names=['GOOG', 'AMZN'],
start_date=start_date,
end_date=end_date)

Exception: Error during download of stock data from Quandl.
Make sure all the requested stock names/tickers are supported by Quandl.

Kindly solve the issue

Question about plotting EF

Hey thanks so much for all your work here! It is really useful for me.

The plots look particularly great. My question is, is there a way to get the EF plot to also show the "black line" that defines the efficient frontier? It shows that in your example picture in ReadMe but not in the plot that is actually generated. Very minor, really for aesthetics sake. Thank you so much! :)

Error when trying build_portfolio example

I noticed that this repo hasn't been updated since June 2023, I am getting an error with DataFrame append, this is the code:

from finquant.portfolio import build_portfolio
names = ['GOOG', 'AMZN']
start_date = '2020-01-01'
end_date = '2021-12-31'
pf = build_portfolio(names=names,
start_date=start_date,
end_date=end_date,
data_api='yfinance')

And this is the error I am getting:


AttributeError Traceback (most recent call last)
/tmp/ipykernel_124653/843295701.py in ?()
----> 5 from finquant.portfolio import build_portfolio
6 names = ['GOOG', 'AMZN']
7 start_date = '2020-01-01'
8 end_date = '2021-12-31'

~/finquant/portfolio.py in ?(**kwargs)
1166 raise ValueError(
1167 input_comb_error.format(complement_input_args, allowed_mandatory_args)
1168 )
1169 # get portfolio:
-> 1170 pf = _build_portfolio_from_api(**kwargs)
1171
1172 # 2. pf_allocation, data
1173 allowed_mandatory_args = ["data"]

~/finquant/portfolio.py in ?(names, pf_allocation, start_date, end_date, data_api)
935 # check pf_allocation:
936 if pf_allocation is None:
937 pf_allocation = _generate_pf_allocation(names=names)
938 # build portfolio:
--> 939 pf = _build_portfolio_from_df(data, pf_allocation)
940 return pf

~/finquant/portfolio.py in ?(data, pf_allocation, datacolumns)
1047 # if only one data column per stock exists, give dataframe a name
1048 if len(datacolumns) == 1:
1049 stock_data.name = datacolumns[0]
1050 # create Stock instance and add it to portfolio
-> 1051 pf.add_stock(Stock(pf_allocation.loc[i], data=stock_data))
1052 return pf

~/finquant/portfolio.py in ?(self, stock)
256 """
257 # adding stock to dictionary containing all stocks provided
258 self.stocks.update({stock.name: stock})
259 # adding information of stock to the portfolio
--> 260 self.portfolio = self.portfolio.append(stock.investmentinfo, ignore_index=True)
261 # setting an appropriate name for the portfolio
262 self.portfolio.name = "Allocation of stocks"
263 # also add stock data of stock to the dataframe

~/dev/lib/python3.9/site-packages/pandas/core/generic.py in ?(self, name)
6292 and name not in self._accessors
6293 and self._info_axis._can_hold_identifiers_and_holds_name(name)
6294 ):
6295 return self[name]
-> 6296 return object.getattribute(self, name)

AttributeError: 'DataFrame' object has no attribute 'append'

pf._udpate() called numerous times when adding stocks in bulk.

I noticed when adding a number of stocks to a portfolio the time to add them takes longer and longer. Adding a deferment to the pf._update() call seems to resolve this and makes adding bulk stocks much faster. Pull request to follow for your consideration.

'Index' object has no attribute 'tz_localize'

Hi there,

Tried to download the stock price from yfinance, used the code snippest in documentation.

from finquant.portfolio import build_portfolio
names = ['GOOG', 'AMZN', 'MCD', 'DIS']
pf = build_portfolio(names=names, data_api="yfinance")

But once I run it, it says 'AttributeError: 'Index' object has no attribute 'tz_localize''

Thanks in advance.

Depreciation pandas

Error while using package

error

-packages\finquant\portfolio.py:260: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
self.portfolio = self.portfolio.append(stock.investmentinfo, ignore_index=True)

Cant this problem be solved.

Regularization Function / Bounds Config

Hello @fmilthaler !

I'm having some dificulty to use ef_maximum_sharpe_ratio with a more "spreaded" allocation... Would it be possible to add some regularization function to avoid the optimizer to concentrate allocation in only 1 or 2 stocks?
Another way to resolve this could be to add some "per stock" or global limit settings (lower and upper). I don't know wich solution is better.... E.g: only allow a maximum of 80% of portfolio allocation for each stock.

Thanks!

Inverted Axis when plotting

When running this code, that was extracted from the examples of the documentation, the plot seems to be inverted and since i simply copied/pasted the code i really dont know what would go wrong.
``#%%
from finquant.portfolio import build_portfolio
names = ['GOOG', 'AMZN', 'MCD', 'DIS']
pf = build_portfolio(names=names, data_api="yfinance")
from finquant.moving_average import compute_ma, ema

get stock data for Disney

dis = pf.get_stock("DIS").data.copy(deep=True)
spans = [10, 50, 100, 150]

computing and visualising a band of moving averages

ma = compute_ma(dis, ema, spans, plot=True)
print(ma.tail())`
plot

`

How to use with lib plotly

Congratulations for the work. Excellent library!

How to use the efficient frontier data to plot in the plotly library the EF Min Volatility and EF Max Sharpe Ratio?

Thanks

Use type hints consistently

As part of that: where a variable could be either pd.Series or pd.DataFrame, do sth like the following:

DataFrameOrSeries = Union[pd.DataFrame, pd.Series]

def compute_ma(
    data: DataFrameOrSeries, fun: Callable, spans: List[int], plot: bool = True
) -> pd.DataFrame:
    # rest of function

While at it, fix pylint issues as well.

Regarding using index as stocks

Hi Sir,
I have just started with Python and cam across the FinQuant documentation. Was successful in replicating the code for stocks, but when i am trying to use S&P, FTSE and Nikkei in place of stocks then i receive an error. So could help me with the issue.

comp_cumulative_returns() weird behaviour

Hi

I do have a portfolio where some of the stocks have data starting at different time (some are more recent). I build my own Dataframe, so it's made to have an index that is date, and then if one stock still has no data when another one has, for that date the value for the stock still not started will be 0.0.

I then use FinQuant, giving it my Dataframe with the stocks and another with the weights, and do all calculations I need.

It works in every aspects I use, and I use pretty much all the functions, but one function, comp_cumulative_returns() fails to deal correctly with the data. If one of the stocks in portfolio starts later than the others, and so in the dataframe the prices for that stock are 0.0 till the 'real' data starts, that function doesn't work and the resulting output has 0.0 for the whole sequence of that specific stock.

Any hint about how to deal with this case?

Unit Test Revamp - Efficient Frontier and Monte Carlo

Hi @fmilthaler / @PietropaoloFrisoni,

When you guys get the time, could you add some unit tests for the monte_carlo and efficient_frontier modules? I feel that these are as essential as the portfolio file. Understanding the effect of changes to preserving the functionality could be made clearer through a few more comprehensive unit tests.

Thanks for your continued hard work.

"Could not find column labels in given dataframe."

When trying to get data from Quandl I get the an error (made sure ticker names are correct beforehand):

`d = {
0: {"Name": "XLON/BP_", "Allocation": 1000000},
1: {"Name": "XLON/III", "Allocation": 1000000},
2: {"Name": "XLON/GSK", "Allocation": 1000000},
3: {"Name": "XLON/OCDO", "Allocation": 1000000},
4: {"Name": "XLON/RBS", "Allocation": 2000000},
5: {"Name": "XLON/SVT", "Allocation": 1000000},
}

pf_allocation = pd.DataFrame.from_dict(d, orient="index")

#set list of names based on names
names = pf_allocation["Name"].values.tolist()`

This is the error message:

`runfile('C:/Users/Joe Shiafa Pierce/.spyder-py3/FinQuant POM project.py', wdir='C:/Users/Joe Shiafa Pierce/.spyder-py3')
Traceback (most recent call last):

File "", line 1, in
runfile('C:/Users/Joe Shiafa Pierce/.spyder-py3/FinQuant POM project.py', wdir='C:/Users/Joe Shiafa Pierce/.spyder-py3')

File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
execfile(filename, namespace)

File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/Joe Shiafa Pierce/.spyder-py3/FinQuant POM project.py", line 40, in
names=names, pf_allocation=pf_allocation, start_date=start, end_date=end

File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\finquant\portfolio.py", line 1153, in build_portfolio
pf = _build_portfolio_from_api(**kwargs)

File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\finquant\portfolio.py", line 935, in _build_portfolio_from_api
pf = _build_portfolio_from_df(data, pf_allocation)

File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\finquant\portfolio.py", line 1035, in _build_portfolio_from_df
data = _get_stocks_data_columns(data, pf_allocation.Name.values, datacolumns)

File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\finquant\portfolio.py", line 869, in _get_stocks_data_columns
raise ValueError("Could not find column labels in given dataframe.")

ValueError: Could not find column labels in given dataframe.`

Thanks for your help,

MCOpt plot: Add "MC" to label

Adding "MC" or "Monte-Carlo" to labels of Monte Carlo optimisation plots. Easier to distinguish it from the Efficient Frontier output.

Limit allocation weights

Thanks for the great work at this library.

How can I set the lower and upper limit for the allocation of shares in the portfolio when calculating EfficientFrontier? E.g. not less than 2% and not more than 15% per title.

Thank you

Mira

example/Example-Build-Portfolio-from-web.py fails

Running the example without edit fails.

(.venv) vagrant@linux:~/dev/FinQuant/example$ python3 Example-Build-Portfolio-from-web.py 
/home/vagrant/dev/FinQuant/.venv/lib/python3.8/site-packages/FinQuant-0.2.2-py3.8.egg/finquant/portfolio.py:260: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
Traceback (most recent call last):
  File "Example-Build-Portfolio-from-web.py", line 85, in <module>
    pf = build_portfolio(
  File "/home/vagrant/dev/FinQuant/.venv/lib/python3.8/site-packages/FinQuant-0.2.2-py3.8.egg/finquant/portfolio.py", line 1170, in build_portfolio
  File "/home/vagrant/dev/FinQuant/.venv/lib/python3.8/site-packages/FinQuant-0.2.2-py3.8.egg/finquant/portfolio.py", line 939, in _build_portfolio_from_api
  File "/home/vagrant/dev/FinQuant/.venv/lib/python3.8/site-packages/FinQuant-0.2.2-py3.8.egg/finquant/portfolio.py", line 1051, in _build_portfolio_from_df
  File "/home/vagrant/dev/FinQuant/.venv/lib/python3.8/site-packages/FinQuant-0.2.2-py3.8.egg/finquant/portfolio.py", line 267, in add_stock
  File "/home/vagrant/dev/FinQuant/.venv/lib/python3.8/site-packages/FinQuant-0.2.2-py3.8.egg/finquant/portfolio.py", line 282, in _update
  File "/home/vagrant/dev/FinQuant/.venv/lib/python3.8/site-packages/FinQuant-0.2.2-py3.8.egg/finquant/portfolio.py", line 202, in totalinvestment
ValueError: Total investment must be a float or integer.

Plotting error

`import os

import numpy as np
import pandas as pd
from finquant.portfolio import build_portfolio
from finquant.moving_average import compute_ma, ema

names = ['GOOG', 'AMZN', 'MCD', 'DIS']
pf = build_portfolio(names=names, data_api="yfinance")

get stock data for Disney

dis = pf.get_stock("DIS").data.copy(deep=True)

dis.index = dis.index.map(str)

np.save("dis_data.npz", dis)

dis.to_csv("dis.csv")

spans = [10, 50, 100, 150, 200]

computing and visualising a band of moving averages

ma = compute_ma(dis, ema, spans, plot=True)
print(ma.tail())
`


`ssh://leef_wsl_u18@localhost:22/home/leef_wsl_u18/miniconda3/envs/py36/bin/python -u /home/leef_wsl_u18/.pycharm_helpers/pydev/pydevd.py --cmd-line --multiproc --qt-support=auto --client 0.0.0.0 --port 55053 --file /tmp/rd_finquant/rd_leef/rd2.py
Connected to pydev debugger (build 211.7142.13)
[100%**] 4 of 4 completed
Traceback (most recent call last):
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/contextlib.py", line 99, in exit
self.gen.throw(type, value, traceback)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_matplotlib/converter.py", line 85, in pandas_converters
yield
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_matplotlib/converter.py", line 65, in wrapper
return func(*args, **kwargs)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_matplotlib/core.py", line 668, in _plot
return ax.plot(*args, **kwds)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/init.py", line 1892, in inner
return func(ax, *args, **kwargs)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_axes.py", line 1407, in plot
self.add_line(line)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 1787, in add_line
self._update_line_limits(line)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 1809, in _update_line_limits
path = line.get_path()
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/lines.py", line 989, in get_path
self.recache()
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/lines.py", line 672, in recache
xconv = self.convert_xunits(self._xorig)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/artist.py", line 199, in convert_xunits
return ax.xaxis.convert_units(x)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/axis.py", line 1472, in convert_units
ret = self.converter.convert(x, self.units, self)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_matplotlib/converter.py", line 256, in convert
values = DatetimeConverter._convert_1d(values, unit, axis)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/pandas/plotting/_matplotlib/converter.py", line 291, in _convert_1d
values = dates.date2num(values)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/dates.py", line 362, in date2num
return _to_ordinalf_np_vectorized(d)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2108, in call
return self._vectorize_call(func=func, args=vargs)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2186, in _vectorize_call
ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2146, in _get_ufunc_and_otypes
outputs = func(*inputs)
File "/home/leef_wsl_u18/miniconda3/envs/py36/lib/python3.6/site-packages/matplotlib/dates.py", line 220, in _to_ordinalf
python-BaseException
base = float(dt.toordinal())
AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'

Process finished with exit code 1
`

yfinance returns no data.

When using yfinance as the data source no data is returned.
In portfolio.py line 791
start_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")

ValueError when optimizing a portfolio with 3 indices

I'm currently having an issue running the demo code when I try to run the mc_optimisation with 3 stocks in the portfolio. I've tried running with 2 stocks as well as portfolios with more than 3 stocks and everything seems to work fine. However, when I setup a portfolio with 3 stocks, I run into the following error.

ValueError: Shape of passed values is (2, 5000), indices imply (2, 3)

Code that produced the error:

from finquant.portfolio import build_portfolio

names = ['MSFT', 'AAPL', 'GOOG']

start_date = '2015-01-01'
end_date = '2020-04-25'
pf = build_portfolio(names=names,
start_date=start_date,
end_date=end_date, data_api="yfinance")

opt_w, opt_res = pf.mc_optimisation(num_trials=5000)

Momentum Indicators - RSI, MACD

First of all thanks for the great work. This package is amazing!

I think apart from moving averages and related bollinger bands, indicators like RSI would add relative strength to the package (pun intended). Let me know what you think.

This issue is about adding a feature for plotting RSI indicators using a 14 day window as suggested using the approach here -> https://www.alpharithms.com/relative-strength-index-rsi-in-python-470209/

Update: Edited the issue and generalized it over a number of momentum indicators. I can go ahead and implement them all or we can discuss it if you have suggestions.

Depciation warning 5.0

Dear hero's

Im using your libary heavly but now there is a problem: this error keeps popping up:
\finquant\monte_carlo.py:37: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
return np.asarray(result)

Are you still alive? Is there a possiblity for you to fix this?
Can I fix it?

ValueError: Could not find column labels in given dataframe.

Hi

I'm exploring Finquant as it seems really the best library out there for quick portfolio optimisation.

I'm testing it following the examples for csv files, it works with the test provided .csv, when I try with my ones I can create a portfolio equally balanced without problems (so without providing the weights from portfolio.csv), but when I try giving custom weights I receive error:

ValueError Traceback (most recent call last)
in
50 print(df_data)
51
---> 52 pf = build_portfolio(data=df_data, pf_allocation=df_pf)
53 #pf = build_portfolio(data=df_data)
54

/usr/local/lib/python3.7/site-packages/finquant/portfolio.py in build_portfolio(**kwargs)
1181 )
1182 # get portfolio:
-> 1183 pf = _build_portfolio_from_df(**kwargs)
1184
1185 # final check

/usr/local/lib/python3.7/site-packages/finquant/portfolio.py in _build_portfolio_from_df(data, pf_allocation, datacolumns)
1037 # extract only "Adjusted Close" price ("Adj. Close" in quandl, "Adj Close" in yfinance)
1038 # column from DataFrame:
-> 1039 data = _get_stocks_data_columns(data, pf_allocation.Name.values, datacolumns)
1040 # building portfolio:
1041 pf = Portfolio()

/usr/local/lib/python3.7/site-packages/finquant/portfolio.py in _get_stocks_data_columns(data, names, cols)
875 # else, error
876 else:
--> 877 raise ValueError("Could not find column labels in given dataframe.")
878 # append correct name to list of correct names
879 reqcolnames.append(colname)

ValueError: Could not find column labels in given dataframe.

I've tried looking into portfolio.py to see why I get the error with my .csv only, but I can't see honestly where is the problem.

This is my stocks file containing the close prices (it works):

EQQQ float64
IWFM float64
IGLT float64
IBTM float64
SGLN float64
STM float64
dtype: object
EQQQ IWFM IGLT IBTM SGLN STM
Date
2015-01-02 6721.0 1694.75 12.44 128.51 1532.5 246.4
2015-01-05 6713.0 1690.25 12.51 130.25 1554.5 242.0
2015-01-06 6670.0 1684.75 12.61 131.75 1579.0 241.5
2015-01-07 6724.0 1706.00 12.58 132.54 1597.5 245.1
2015-01-08 6866.0 1740.00 12.55 131.73 1593.0 252.7

And this is my portfolio.csv containing the weights:

Allocation float64
Name object
dtype: object
Allocation Name
0 20.25 EQQQ
1 10.97 IWFM
2 29.44 IGLT
3 28.56 IBTM
4 9.67 SGLN
5 1.11 SMT

Any idea how can I make it work and what's the problem? As I said it works with test data CSV in your repo...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.