-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Some thoughts... #4
Comments
I've been working on a very similar idea to Miletus.jl, based on the same article, and it's turning into a bigger system, built upon a stack of packages that I have contributed over the years (Mongoc.jl, Oracle.jl, BusinessDays.jl, InterestRates.jl, XLSX.jl, JSONWebTokens.jl, Vol.jl), and also non-Julia packages (math-server-docker, hyper-reverse-proxy, bdays). In order to keep things modular and reusable in financial systems, you must put big effort on keeping database data and business logic separated. For instance, should a Concepts in a Financial ToolboxThe way I see concepts organized: CurrencyProvides:
Daycount
BusinessDays
Rates
See InterestRates.jl. Term Structures
See InterestRates.jl. Contract PrimitivesProvides a language for defining a financial contract based on the article. This is the overlap with the work in JuliaComputing's Miletus package. But JuliaComputing should release Miletus code under a liberal license in order to help us contribute these ideas, given the big overlap.
On the use of Fixed Decimals and/or truncation rules for Contracts
Portfolio and Positions (holdings)
At this point, you can see that a Volatility ModelsVolatility estimation techniques. See Vol.jl.
Market Risk Models
Regulatory Reports
Portfolio Optimization
Asset-Liability Management
Algo Trading
ConclusionAs you can see, this is biased to a market risk framework, but may be useful to guide future development in this group. It is the result of years of thinking, so I hope it helps. :D |
Hey! Good to see you here @felipenoris! 😃 (And just before I posted this I noticed you already started moving some of your packages to JuliaFinance. That is awesome! Thanks 💪🎉😃) Thank you for your thoughts 🙌 It is encouraging to see so much alignment in the way we think about things 😊 Some comments below...
I agree we need all this, but one of my points above is we need to think about where to put it. For me, binding a number to a currency is no different than binding a number to any other financial instrument. It is a "holding" and is probably better in a Have you looked into any financial instrument classifications? To me, that has always been a huge challenge, especially with large multinational financial institutions. I like the CFI classification standard https://www.anna-web.org/standards/cfi-iso-10962/. Spot cash is listed as a financial instrument. It makes sense since cash has a bid-ask spread. So I think something like I have similar thoughts about an I see a A
See DayCounts.jl 😊
I was going to provide the link to your own BusinessDays.jl, but see you already moved it to JuliaFinance https://github.com/JuliaFinance/BusinessDays.jl That is awesome. Thank you! 🙌😃🎉
💯
It looks like you've put a lot more thought into this than I have 😅 I am a little hesitate to put too much weight on Miletus and the articles it is based on. Although I have no doubt it is probably appealing from an academic perspective, I don't think it has been adopted by the markets. Maybe it is fine, but I'm not ready to jump into that commitment with both feet yet 😅 I could be convinced otherwise though and interested to hear more of your thoughts on the subject. A lot of what what you described in this section can be broken down into smaller packages. Let's try to map out what those smaller packages might look like 😊🙏
This all sounds good 👍 The only thing I wonder about is if we should move some of this functionality into an
I see we have slight difference of opinion on this 😅 A mentor once told me that the most complicated financial instrument on the market is cash (and I've grown to agree with him) 😅 Although it seems trivial, there is a rabbit hole that can go pretty deep especially with global multicurrency portfolios. I think it makes sense to keep cash on par with other portfolio holdings.
That is awesome. Yeah. Would be awesome to build these reports in Julia. Not only for banking, but insurance as well 😊 We could probably even get support from a few regulators. Well, welcome to JuliaFinance @felipenoris! It is great to see you here and I'm excited about what we can do here 🚀😊 |
Nice! Just a note on what I meant on my comments about Later on the stack of packages, the So, what I meant is that when you define it in the currencies package, you're just providing a syntax sugar, and it is not a holding yet. And this gives my opinion on the answer for your initial question about how to define holdings. |
It is late where you are 💤😃 (PS: I'm on Slack. Might be easier to discuss there 😊) |
This is very exciting! On and off, I have been thinking about building a Julia library that blows quantlib away. I have fixed income asset management background so I can possibly contribute in various aspects of pricing, analytics, etc. |
That's awesome @tk3369. Welcome! 😃 |
I just created two new repos: These are embarassingly boring and could probably be implemented much better than what I did. Feedback / PRs welcome 😅🙏 I found a good data source for countries here so included more data than I was initially planning to include. So a Country instance contains the following fields: struct Country
name::String
code::Int
currency::Currencies.Currency
capital::String
continent::String
developed::Bool
region::String
subregion::String
end |
This was actually my plan for the next iteration of Miletus: my idea was that you specify everything in terms of "basic assets" (e.g. currencies, stocks, commodities), and then the "price" is simply the relative value of one asset compared to another. The nice thing is that a forex derivative is the same as a stock market derivative. |
Cash makes a good numeraire 😊 But keep in mind that each market, e.g. HK, SG, US, UK, will have it's own local numeraire. Any more thoughts on when / if parts of Miletus can be open sourced? 😊 @felipenoris and I have been discussing it here and elsewhere and agree that contracts are of fundamental importance to JuliaFinance. We are both working on other priorities right now though, so there is time to think about it, but at some point, we'll need contracts to make further progress 🙏😊 |
Both currency and country are common reference data for financial instruments. For space efficiency reasons, I would prefer that we define an enum type (USD/EUR/etc and US/EU/etc) for general reference. Then, a dictionary can be used to look up detailed information about that currency or country. From a user perspective:
|
Hi @tk3369 👋 I've seen this handled various ways and happy to discuss to find the best way forward 😊 I did it this way because I didn't think space would be an issue, but I can see your point. It could be done with For example, abstract type Currency end
struct USD <: Currency end I did think about enums, but they felt a little clumsy to me, but maybe I am exposing ignorance 😅 Singleton types would allow us to dispatch on countries and currencies. Not sure of the pros and cons though. Open to ideas 😊 |
Two other points re currencies
|
Hi Eric, I'm unsure if there's any reason to dispatch on specific currency/country. I'm good with either enum or symbol -- leaning more on enum since it's typed. Regarding:
A Now that's where things become hairy. When you have multiple lots in a portfolio, a sell trade against that position may relieve the lots based upon a specific accounting treatment - e.g. FIFO, LIFO, average, etc. A portfolio accounting system would take it seriously and make sure that the right lots are relieved. However, a general-purpose portfolio management system would ignore that effect and just look at the portfolio at the position level (after all, the remaining number of shares is the same). P/L calculation requires proper lot accounting. Typically a portfolio would have a default lot relief convention but the investor has the ability to select specific lots (e.g. I can do that on E*Trade). A Fixed income instruments are more complex. One of the issues is that bonds may have embedded options. So a Generally, a portfolio's holdings can be constructed from a trade log. It would be convenient to have a "replay" function that takes a portfolio from point A in time, and bring it to a different state at point B by executing a series of trades. |
Perhaps we should add another type for I would imagine having a framework where one can add various kinds of calculators for these analytics. Each calculator should cover a number of financial instruments e.g. I would not calculate duration for stocks, nor would I calculate P/E for bonds. Having said that, it would be nice to define a set of traits for each financial instruments so these functions can operate on them only if the traits are satisfied. (Speaking of which, I would be very happy when traits becomes officially supported in Julia.) |
This is great insight @tk3369 👍 We're definitely on the same page. I think we agree that some early thinking on how to handle accounting of trades (and lots) makes sense and that is kind of what I'm doing now, but I got distracted looking into AbstractTrees.jl. I think it could be useful for us, but maybe needs some enhancements / modifications. I know @felipenoris 's priority is yield curve stuff (Rates and TermStructures). All of this eventually links back to Contracts 😊 |
Hey @felipenoris , @simonbyrne 👋 @tk3369 made this comment about
Do you have any thoughts? |
Any thoughts on renaming Currencies.jl to CurrencyBaskets.jl or something? This would leave Currencies.jl to be similar to Countries.jl which are likely going to be just enums with some table lookups. |
Regarding dispatch on currency, that is useful for dispatch on parametric types down the road. We could dispatch on values also, like For instance, the algebra around monetary values uses dispatch to guarante that 1USD + 2EUR cannot be summed (related to the comment on Unitful.jl). Exchange rates could be modeled using dispatch on currency types like so: function exch(p::AbstractExchangeRateProvider, from::C, to::C) :: Float64 where {C<:Currencies.Currency}
# same currency
return 1.0
end
function exch(p::AbstractExchangeRateProvider, from::C1, to::C2) :: Float64 where {C1<:Currencies.Currency, C2<:Currencies.Currency}
if !haskey(p, from) # ex.: BRL -> USD
@assert haskey(p, to)
@assert cashcurrency(p[to]) == from
return 1.0 / cashvalue(p[to])
elseif cashcurrency(p[from]) == to # ex.: USD -> BRL
return cashvalue(p[from])
else
@assert haskey(p, to)
@assert cashcurrency(p[from]) == cashcurrency(p[to]) # same functional currency
return cashvalue(p[from]) / cashvalue(p[to])
end
end Dispatch on countries is something less required, in my mind. One could also dispatch on values for countries anyway. |
Regarding @simonbyrne comment on Fixed Decimals, that's something I've been thinking about in the last few weeks. What I think about it for now is this:
|
Thanks for the input @felipenoris 🙌 That is a good point about dispatching on currencies. It looks like we could either
Between the two, I am slightly inclined to go with singleton types for currencies 🤔 Now, I also think it could come in handy if we could dispatch on countries, e.g. different countries have different laws, different tax regimes, different regulatory reporting requirements, etc. On regulatory reporting, sometimes you might want to look at what a Malaysian company would look like under Hong Kong capital adequacy. Maybe the Malaysian company has a Hong Kong parent or someone in Hong Kong is considering an acquisition. On a more technical note, I've been looking at traits lately and it feels like I'm looking at the future. It is starting to shift the way I think about coding in Julia. I think having concrete singleton types for both currency and country could come in handy if we start implementing traits. Then we could do things like: subregion(::US) = NorthAmerica()
subregion(::HK) = EastAsia()
subregion(::GB) = NorthernEurope()
subregionanalysis(x) = subregionanalysis(x,subregion(x))
subregionanalysis(x,::NorthAmerica) = ...
subregionanalysis(x,::EastAsia) = ...
subregionanalysis(x,::NorthEurope) = ... At first, the advantage of traits over usual subtyping of abstract types wasn't very obvious to me, but if you think about extensibility of interfaces, it starts to make sense. See the discussion starting here: JuliaLang/julia#2345 (comment) From timholy:
|
I like the pragmatic approach where you don't do things until you need them. If that's something important for you, go ahead. If there's no clear vision, don't do it until you need it. I'm sure Currency would be just an enum if someone didn't get yet to the implementation on algebra around cash values. But this is somewhat subjective. So if you're the guy coding Countries, go for what you think is the best design. If down the road it is not, an issue will be opened on that repo. |
Sounds good. Let me put it this way... Singleton subtypes are simple to implement, efficient, and appear future proof to me. I don't see a downside to making currencies and countries (and regions and subregions etc) singleton subtypes. Before I go ahead and implement singleton subtypes, can you guys think of a downside? Edit: Some links with some interesting related discussions: https://discourse.julialang.org/t/singleton-types-vs-instances-as-type-parameters/2802 https://discourse.julialang.org/t/naming-of-singleton-types-and-their-instance/8399 http://www.stochasticlifestyle.com/type-dispatch-design-post-object-oriented-programming-julia |
Downsides that come to my mind are minor stuff:
|
Yeah. Agree. I'd never
This is actually where traits could come in handy. Let's say, you wanted to run a simulation or create your own country. In your package, you could define struct MyCountry <: Country end
subregion(::MyCountry) = EastAsia() Now, subregionanalysis(x) = subregionanalysis(x,subregion(x)) This is a decent illustration of how traits help with extensibility 😊 You could do the same with value types though, but I think we agree that feels a little clumsier. |
Which means that, whatever solution is given, enum or type, we could add an abstract type. This will integrate nicely with future traits, I guess. |
Very good discussions here. I appreciate the thoughtfulness of the comments and the desire to do it right from the beginning. I can't think of a reason why singleton subtypes wouldn't work. It may be good to just do it and battle test with real use cases e.g. defining a type for cash instruments, a currency forward contract, etc. and any possible issues would surface as part of the exercise. |
Sounds good. I will give it a shot, but I'm still spinning my wheels a bit with my ledger stuff and trying to incorporate AbstractTrees 😅 I should just push out something still under construction for feedback 🤔 |
Just added a few more insights on the use of Fixed Decimals in my first post (the 2nd post of this thread). |
Hi everyone, one thought that I had as I read some of the discussions going on.... Regarding rates, ie interest rates, when applied in a valuation context, could be more generalized to be a type of Looking at InterestRates.jl, it seems like that's more focused on just mechanics of yield curves and such, not on valuation so I'm not exactly sure where to point my feedback to yet. |
Hi @alecloudenback 👋 Funny you mention that, I was thinking the exact same thing this morning (Manila time which is a few hours ago). In the same context too! 😃 Lots of things can create a term structure of spreads: From an actuarial perspective, as you note, you have things like
You can also have things like
In fact, when I was at Countrywide structuring MBS, we were using mortality models for prepayment risk because the mechanics are similar 😊 I had in mind a general package for I love this thinking! 😃 |
Hey, I am new to Julia but know Python pretty well. My background is in structured finance, high yield bonds and leveraged loans mostly. I am interested in contributing as this gets going. One area that has been mentioned is around a Ledger for tracking cashflows or account balances or as @tk3369 said an Analytic to describe cash flows. I believe these are related and useful primitives. |
@felipenoris I was wondering about what you felt about using IEEE Decimal Floats (i.e. as in DecFP.jl) instead of relying on |
@EricForgy brought this up over at #8 but I thought I would just clarify by what I mean by abstracting interest rates to be a form of more generic "decrements". I think that the design decision needs to depend partly on how contracts/assets/cashflows are designed because when I think about how decrements are applied, it's in valuing those things. Here's a simple example though: function value(notional, decrements,cfs)
sum(notional * (prod(decrements,dims=2) .* cfs))
end
#life insurance
interest_rate = [0.05 for x=1:10]
discount_vector = cumprod((1 ./ (1 .+ interest_rate)))
mortality = [0.01 * x for x=0:9]
survival = cumprod(1 .- mortality,dims=1)
value(100,hcat(discount_vector, survival),q) # 31.678928945567804
#bond
interest_rate = [0.05 for x=1:10]
discount_vector = cumprod(1 .- interest_rate,dims=1)
bond_payments = [x== 10 ? 1.1 : 0.1 for x=1:10]
value(100,discount_vector,bond_payments) # 136.11367546854586 This example separates out the "things that discount the future value" from the "thing that you are valuing" but doesn't really care what the discounting functions are. You could go even further and consider combining the
and change the definition of value to: function value2(notional, decrements)
sum(notional * prod(decrements,dims=2))
end and I think the latter might be going too far and it would be practical to separate the cashflows from the decrements. And like @EricForgy mention, swap out mortality for defaults and you have the workings of a credit model, so this is pretty broad based in application. |
One additional thought is that decrements should have the ability to interact with |
I'd like to try to get some momentum going 🙏
Currencies
I think we need to think about Currencies.jl a little bit.
I recently split out CurrenciesBase.jl from Currencies.jl, but I still think CurrenciesBase does too much 🤔
The issue is that you can speak about USD without talking about 1.0USD. For example, if I want to specify the currency of a bank account, I'd like to have a type
Currency
available for that.Now, if we want to talk about a specific quantity in a certain currency, this is like a position in a stock, e.g. 400 shares of Apple stock. We have 400 units of USD.
Countries
Similar to currency, we need a way to specify countries. Like currencies, there are ISO standards for country codes, etc.
I think we need standard identifiers/codes for both countries and currencies.
Holdings
As mentioned above, I think we should differentiate a currency or financial instrument from a position in that currency or financial instrument.
For example, if
AAPL
is an instance of a financial instrument, i.e. Apple stock, then we should distinguishAAPL
from 400 shares ofAAPL
. In one case, we're talking about a financial instrument itself. In the other, we're talking about ownership or a position in that instrument.Similarly, if
USD
is an instance of a currency, then we should distinguishUSD
from a position of 400 units ofUSD
.One way I've thought of to deal with this is to consider currencies and financial instruments as units so we can write things like
More recently, I've been thinking about this more from an accounting perspective so we can have ledger accounts. Maybe the two ways of thinking about it are compatible. I'm still just starting to think about it now.
Ledgers
I'm working on a ledger package now along similar lines to @TotalVerb's Accounting.jl.
If we can construct a general ledger with chart of accounts, then that could be the foundation to everything from personal finance to corporate financial reporting. I'll try to get something preliminary out soon and welcome more brains helping to think about this stuff.
I know accounting feels boring, but the more I get into modeling it, the more I like it. After all, even sexy things like derivatives trading boils down to P&L at the end of the day, so having a good foundation on which to build more quant stuff makes sense to me.
Interest Rate Models
Interest rate modeling is cool. I'm sure most Julia quants will be drawn to interest rate derivatives etc. However, I am interested in yield curve forecasts for balance sheet projections and capital management.
Interest rate models used for derivative pricing are notoriously poor at forecasting yield curves. Similarly, econometric models use to forecast yield curves are generally poor for derivatives pricing because they tend to not be arbitrage free.
I'm greedy and want both 😊 There are some models I have in mind to implement that should straddle both derivatives pricing and yield curve forecasting. Still early stages for me though and most of the work is handwritten notes so far 😅
Regulatory Reporting
Financial services are regulated and every regulator has a different approach to solvency and capital adequacy. I think there are some good opportunities to implement regulatory capital models in Julia.
Quant Stuff
Then, of course, I think most people looking to Julia for use in finance will be interested in quant work 😊
That is fun. I admit, but I also think it would be good to have quant packages built on some common foundational packages around currencies, countries, accounting treatments, etc.
Everyone can and should at some point build a Black-Scholes solver, but wouldn't it be nicer if your models plugged directly into an accounting system? 😅
Other Stuff?
The above kind of outlines my personal priorities. I'm happy to join forces with others with different priories and would love to hear about them. Maybe I am a dreamer, but I'm hoping there can be some core financial functionality on which various other domains can grow upon rather than having every new package define its own currency module 😅 AND... having accounting treatment thought about from the beginning.
The text was updated successfully, but these errors were encountered: