Giter Club home page Giter Club logo

okama's Introduction

Documentation Status Python PyPI Latest Release Coverage License Open In Collab Code style: black

Okama

okama is a library with investment portfolio analyzing & optimization tools. CFA recommendations are used in quantitative finance.

okama goes with free «end of day» historical stock markets data and macroeconomic indicators through API.

...entities should not be multiplied without necessity

-- William of Ockham (c. 1287–1347)

Table of contents

Okama main features

  • Investment portfolio constrained Markowitz Mean-Variance Analysis (MVA) and optimization
  • Rebalanced portfolio optimization with constraints (multi-period Efficient Frontier)
  • Investment portfolios with contributions / withdrawals cash flows (DCF)
  • Monte Carlo Simulations for financial assets and investment portfolios
  • Popular risk metrics: VAR, CVaR, semi-deviation, variance and drawdowns
  • Different financial ratios: CAPE10, Sharpe ratio, Sortino ratio, Diversification ratio
  • Forecasting models according to normal, lognormal and other popular distributions
  • Testing distribution on historical data
  • Dividend yield and other dividend indicators for stocks
  • Backtesting and comparing historical performance of broad range of assets and indexes in multiple currencies
  • Methods to track the performance of index funds (ETF) and compare them with benchmarks
  • Main macroeconomic indicators: inflation, central banks rates
  • Matplotlib visualization scripts for the Efficient Frontier, Transition map and assets risk / return performance

Financial data and macroeconomic indicators

End of day historical data

  • Stocks and ETF for main world markets
  • Mutual funds
  • Commodities
  • Stock indexes

Currencies

  • FX currencies
  • Crypto currencies
  • Central bank exchange rates

Macroeconomic indicators

For many countries (China, USA, United Kingdom, European Union, Russia, Israel etc.):

  • Inflation
  • Central bank rates
  • CAPE10 (Shiller P/E) Cyclically adjusted price-to-earnings ratios

Other historical data

  • Real estate prices
  • Top bank rates

Installation

pip install okama

The latest development version can be installed directly from GitHub: git clone https://github.com/mbk-dev/okama@dev

poetry install

Getting started

1. Compare several assets from different stock markets. Get USD-adjusted performance

import okama as ok

x = ok.AssetList(['SPY.US', 'BND.US', 'DBXD.XFRA'], ccy='USD')
x  # all examples are for Jupyter Notebook/iPython. For raw Python interpreter use 'print(x)' instead.

Get the main parameters for the set:

x.describe()

Get the assets accumulated return, plot it and compare with the USD inflation:

x.wealth_indexes.plot()

2. Create a dividend stocks portfolio with base currency EUR

weights = [0.3, 0.2, 0.2, 0.2, 0.1]
assets = ['T.US', 'XOM.US', 'FRE.XFRA', 'SNW.XFRA', 'LKOH.MOEX']
pf = ok.Portfolio(assets, weights=weights, ccy='EUR')
pf.table

Plot the dividend yield of the portfolio (adjusted to the base currency).

pf.dividend_yield.plot()

3. Draw an Efficient Frontier for 2 popular ETF: SPY and GLD

ls = ['SPY.US', 'GLD.US']
curr = 'USD'
last_date='2020-10'
# Rebalancing periods is one year (default value)
frontier = ok.EfficientFrontierReb(ls, last_date=last_date, ccy=curr, rebalancing_period='year')
frontier.names

Get the Efficient Frontier points for rebalanced portfolios and plot the chart with the assets risk/CAGR points:

import matplotlib.pyplot as plt

points = frontier.ef_points

fig = plt.figure(figsize=(12,6))
fig.subplots_adjust(bottom=0.2, top=1.5)
frontier.plot_assets(kind='cagr')  # plots the assets points on the chart
ax = plt.gca()
ax.plot(points.Risk, points.CAGR) 


* - rebalancing period is one year.

4. Get a Transition Map for allocations

ls = ['SPY.US', 'GLD.US', 'BND.US']
map = ok.EfficientFrontier(ls, ccy='USD').plot_transition_map(x_axe='risk')

More examples are available in form of Jupyter Notebooks.

Documentation

The official documentation is hosted on readthedocs.org: https://okama.readthedocs.io/

Financial Widgets

okama-dash repository has interactive financial widgets (multi-page web application) build with okama package and Dash (plotly) framework. Working example is available at okama.io.

RoadMap

The plan for okama is to add more functions that will be useful to investors and asset managers.

  • Add Omega ratio to EfficientFrontier, EfficientFrontierReb and Portfolio classes.
  • Make complex withdrawals / contributions strategies in Portfolio class.
  • Make complex portfolio rebalancing strategies.
  • Add Black-Litterman asset allocation
  • Accelerate optimization for multi-period Efficient Frontier: minimize_risk and maximize_risk methods of EfficientFrontierReb class.
  • Make a single EfficientFrontier class for all optimizations: single-period or multu-period with rebalancing period as a parameter.
  • Add different utility functions for optimizers: IRR, portfolio survival period, semi-deviation, VaR, CVaR, drawdowns etc.
  • Add more functions based on suggestion of users.

Contributing to okama

Contributions are most welcome. Have a look at the Contribution Guide for more.
Feel free to ask questions on Discussuions.
As contributors and maintainers to this project, you are expected to abide by okama' code of conduct. More information can be found at: Contributor Code of Conduct

Communication

For basic usage questions (e.g., "Is XXX currency supported by okama?") and for sharing ideas please use GitHub Discussions. Russian language community is available at okama.io forums.

License

MIT

okama's People

Contributors

alexander-myltsev avatar chilango74 avatar dependabot[bot] avatar mathii0402 avatar nenkoru avatar vkhomyakov 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

okama's Issues

avoid running the module namespaces.py when importing okama

__init__.py has imports from namespaces.py which forces http request to API during import okama.

Redefine as functions following:

namespaces = get_namespaces()
assets_namespaces = get_assets_namespaces()
macro_namespaces = get_macro_namespaces()\

index_rolling_corr error

При вызове AssetList.index_rolling_corr ошибка:
TypeError: check_rolling_window() missing 1 required positional argument: 'ror'

Moving to Poetry as a dependency management tool

I have been thinking that Poetry would be a great way to control dependencies.

  • It would eliminate having different files for development dependencies, and production ones
  • It would automatically control and update dependencies when possible, without collisions(which currently happen on nbmake and pytest package)
  • It would automatically create a virtual environment for developers to develop with
  • It would allow for easier publishing of the package to PyPI

As of by writing this Issue, Poetry's version is 1.1.12 and it doesn't allow to have testing dependencies yet, but in version 1.2 they would make it possible. For now, I think it would be best to keep testing dependencies in the development section of poetry.

Look for a correct low limit of the multi-period EF (right part)

Right part of the multi-period Efficient frontier now uses a limit defined as:
“The asset with max CAGR lying to the right of the global max CAGR point (risk should be more than self.max_return['Risk']).”
This definition is realized in _max_cagr_asset_right_to_max_cagr() method.

However, this definition sometimes fails:
image

Correct algorithm should look for points in the outer space (to the right) of line Global Max CAGR – Max Risk Asset. In this set it should look for an asset with highest CAGR. If there are no assets to right of the line the right part of EF should be skipped.

Junk data

When loading certain assets it shows false data.
assets = ok.AssetList(["VTBA.MOEX", "VTBH.MOEX", "SBGB.MOEX"]) assets.wealth_indexes

The result is this:

`
VTBA.MOEX VTBH.MOEX SBGB.MOEX USD.INFL

2021-04 1369.766402 1062.898065 946.963297 1040.959324
2021-05 137.244019 106.279943 966.626194 1049.286999
2021-06 140.203804 107.462560 9.702027 1059.045368
2021-07 143.120043 107.870918 9.866962 1064.128786
2021-08 148.166985 108.334191 9.850195 1066.363456`

Data starting from 2021-06 is junk - those assets did not drop 100 times.
Looks like a bug with formatting/floating point/type conversion.

API description

So as I saw there is an API from which this beautiful tool gets information. However, I was unable to find any info or source code for the API.
Is it private? Is it going to be open-sourced as well?
If it's private, then is it possible to have swagger documentation of endpoints?
I am asking due to having an idea of making an abstract class for API so that there could be other implementations in the project, apart from this private API!

No module named 'okama.api'

Начиная с версии 0.93, импорт библиотеки завершается с ошибкой:
ModuleNotFoundError: No module named 'okama.api'

Library not fetching new data

Recently I started writing a telegram bot using this library for getting stock data, yesterday it worked just fine but today the data is not updating, what is the cause of this? The data is way past 20 minutes old, I've checked TradingView for the ticker that I use and it seems that the ticker data hasn't updated from yesterday.
(RU) Здравствуйте, недавно я начал писать бота в телеграмм с этой библиотекой, и со вчеращнего вечера я заметил что акции не изменяются, что может быть причиной этого и часто ли так проиходит, а то хотелось бы стабильности в такой хорошей библиотеке как эта.

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.