Coder Social home page Coder Social logo

jean-michel-gonet / angular-backtest Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 2.0 7.45 MB

A simple backtest framework written in typescript, to test investing strategies and considering trading costs

License: MIT License

JavaScript 0.17% TypeScript 94.97% HTML 4.77% CSS 0.09%

angular-backtest's People

Contributors

dependabot[bot] avatar fblumet avatar jean-michel-gonet avatar

Stargazers

 avatar

Watchers

 avatar  avatar

angular-backtest's Issues

Systematize the configuration of quote services

Why?

  • Because a person new to the project has no way to know what sources of financial data she can use.
  • Because browsing the different quotes-from-xxx.service.ts classes gives no hint about what data they actually process.

Condition of satisfaction

  • Redact the concerned section of the README.md so that the potential user understands how to list the financial sources he can use.
  • Avoid listing the financial sources in README.md, because they'll change, and we'll never remember to update the documentation.
  • Improve the code in src/app/services/quotes to match the README.md in a satisfactory way.

Additional notes

  • This is not about adding new features.
  • This is about making the code more readable by someone who has very superficial programming skills.

Implement the Superthon Market Time

Why?

  • Because it is mentioned in the book I am reading.
  • Because I can compare the results in my simulation with those of the book.

Condition of satisfaction

  • Obtain same results as in the book.
  • Or invalidate the book.

Add in ``README.md`` an explanation on how to start using the project

Why?

  • So anyone can start using the project.
  • To acquire a critical point of view about the project.

Condition of satisfaction

  • Anyone, with very superficial programming knowledge, can download financial data, add them to the project, and launch a simulation based on an existing example.
  • Write a reusable example of a simulation.

Have local data instead of online

Why?

Fetching online data is nice because you always have it fresh, but there are some shortcomings:

  • Online data are usually not meant to be consumed externally, so the format can change without notice, and your application will stop working.
  • Most of online data requires that you login to a banking system, and those are heavily defended against data retrieval from third party applications.
  • Typescript, Javascript and Internet security are very worried when they see a script from one website trying to access data from another website.

The bottom line is, fetching online data has too many disadvantages.

Condition of satisfaction

  • Keep data in separate folders, using the name of the provider and the instrument ISIN, so they can be found easily.
  • Keep the data untouched, just saved from the provider.
  • Implement the mapping so the data can be used as native Stock and StockData.

Calculate bid-ask spread based on Farshid Abdi, Angelo Ranaldo 2017

Why?

  • Because trading costs have an impact of the return of any strategy.
  • An important trading cost is the bid-ask spread.
  • The bid-ask spread is not generally available from quote providers.
  • Therefore they need to be estimated.

Condition of satisfaction

  • quote services are able to include an estimation of the bid-ask spread while loading the data.
  • Big-ask spread is used in all order simulations.
  • Use the Farshid Abdi, Angelo Ranaldo 2017 paper:

Use Apex Charts instead of NG Charts

Why?

  • Because they offer more options.
  • In particular, Apex makes easy to have two parallel charts.
  • And also Apex is stronger on markers.

Condition of satisfaction

  • Use Apex Charts.
  • Implement an options for two charts.
  • Use a marker to signal the Bull / Bear changes

Apply exchange rate to instruments

Why?

  • Because it is a simple way of including currency risk to any instrument.

Condition of satisfaction

  • In asset configuration, add a exchangeRate, pointing to exchange rate data.

Superthon - Compare using CHF instead of AGG in Bear market

Why?

Where to invest when market goes bearish?

We want to compare these two options:

  • AGG with dividends and the risk of adverse USD / CHF exchange rate
  • CHF without any dividends but also without any risk.

Condition of satisfaction

Make a simulation comparing the USD/CHF exchange rate and the following two strategies:

  • Superthon / Candle Filter with SPY for bull market and and AGG for bear market.
  • Superthon / Candle Filter with SPY for bull market and and CHF for bear market.

Improve Stop Loss Filter by using Average True Ratio

Why?

  • Because ATR is the measure for detecting that something is not normal in the price evolution.
  • Because, right now, Stop Loss Market Timing is useless.

Condition of satisfaction

  • Specify the start of BEAR by a multiple of ATR.
  • Specify the end of BEAR by a moving linear regression.

Transform 'Reinvest Dividends' into 'Transfer Dividends'

Why?

Because reinvesting dividends happens inevitably if you use market timing. Consider a strategy set with reinvestDividends=false in the following scenario:

  • In BULL period, as dividends are not reinvested, they're accumulated in cash.
  • At the beginning of the BEAR period, all assets are sold and more cash is added to the account.
  • At the beginning of the next BULL period, all cash is invested in the targeted asset.

So the dividends are reinvested, independently of the value of reinvestDividends, and there is no fix, as the cash from dividends is mixed with the cash from selling the assets.

Condition of satisfaction

  • Expand the RegularTransfer class so we can have a Transfer that considers the regular withdrawal (as of now) plus transferring the dividends when there are any.
  • Also add the possibility of specifying a % of dividends that would be lost in charges or taxes.

In chart tooltips, display the real value, not the normalized one

Why?

  • Because the normalized value is visible anyway against the vertical axis.
  • Because the normalized value is only useful to visually compare performances, but it is not a real value.

Condition of satisfaction

  • The tooltip displays the real reported value, not the normalized one.

Have some kind of navigation, so it is possible to simulate different scenarios

Why?

  • Until now, you can create a scenario, change the simulation component, and see it. It is simple and satisfactory of a single individual, just wanting to test something.
  • But what if I want to keep track of my scenarios to show to someone else? Or just not forget about them?
  • What if there are several people committing to the same repository?

Condition of satisfaction

  • Add some kind of navigation, so it is possible to group scenarios in different pages.
  • Run only scenarios when the become visible, so as to avoid a long start up time.

Calculate dividends based on normal index and 'Total Return' index

Why?

Because sometimes it is impossible to find the historical data for dividends (the SP500 is a special case). Just using the 'total return' index would suit a simulation where we reinvest all dividends, however this is hardly convenient because of several reasons:

  • Often dividends have tax impositions that depend on your tax residence, so you can't reinvest all dividends.
  • If you want to obtain a revenue from your portfolio, you may want to use the dividends when possible, to reduce operational costs.

Condition of satisfaction

  • Implement a source of dividends that would accept the total return index.
  • For testing, use the SP500, as all required data is available: normal index quotation, total return quotation and dividends.

Technical details

Implement a momentum based market timing

Why?

  • To verify if it works.
  • As a prior step, before implementing the investment strategy by Andreas Clenow in his book "Stock on the move".
  • In particular, to implement the exponential regression and getting familiar with its behavior.

Condition of satisfaction

Implement a market timing based on the following strategy:

  • Buy when the exponential regression x correlation is above a value.
  • Sell when asset value moves beyond a number of times its ATR? Or maybe when exponential regression is below a value? Explore possibilities.

Add a second security to the modified Buy & Hold strategy for BEAR periods

Why?

  • Because this is how lots of investors do: invest in stock indexes during BULL periods, and switch to bonds indexes during BEAR period.

Condition of satisfaction

  • B&H with market timing will have not one, but two securities: A, and B
  • During Bull periods, the strategy invests everything in security A.
  • During Bear periods, the strategy sells position on A, and invests everything in B.

Additional indications

  • Write unit tests for B&H with market timing.
  • Remove the older B&H, as all functionality still works with the new one.

Simulate several accounts at once

Why?

  • So it is possible to compare different strategies.

Condition of satisfaction

  • It is possible to simulate two different setups on the same graph.

Improve the Stop Loss market timing by using RSI to re-enter market.

Why?

  • Current implementation of stop loss protects against heavy losses.
  • However, it also prevents to make nice profits.
  • And this is because, on average, re-entering the market is not that easy.

Condition of satisfaction

  • Explore the advantages of using RSI for reentering.

Verify Momentum Backtest

Why?

  • It is a nice scenario to verify
  • We've read that book, "Stocks On The Move", by Andreas Clenow

Condition of satisfaction

  • Follow the description of the scenario, to back test 1 year.
  • Define an universe
  • Download data:
  • Implement all the selection rules described in the book:
    • Momentum (as CAGR corrected with R2)
    • 15% gap.
    • Market timing to the index.
    • ATR to distribute risk.

Additional details:

Use adjusted closing price for calculating the dividends.

Why?

  • Because this is what the information is meant for.
  • Because this information is provided by Yahoo and Market stack.

Condition of satisfaction

  • Use the adjusted price to calculate dividends and splits.
  • When downloading newer data from yahoo or market stack, correct the previous adjusted price, so the whole series is correctly held.

Implement a strategic strategy

Why?

  • Because it is a very common strategy.

Condition of satisfaction

The strategy has the following properties:

  • X% cash.
  • Y1% asset 1
  • Y2% asset 2
  • etc.
  • Where X% + Y1% +Y2% + ... = 100%

Use PE Ratio as market timing

Why?

Because it looks reasonable to buy when the P/E ratio is low, and sell when it is high.
Or is it?

Condition of satisfaction

  • Add the SP500 P/E Ratio to the assets.
  • Create a market timing indicator based on it.
  • Verify the hypothesis.

Make a nicer navigation

Why?

  • #14 implemented a navigation
  • But... it is ugly

Condition of satisfaction

  • Use bootstrap
  • Make it usable and functional, but don't waste time on design

Accounts have a base currency

Why?

  • Because this reflects reality.
  • Otherwise it is impossible to compare the return on different indexes.

Condition of satisfaction

  • Assets have a domestic currency.
  • Accounts have a base currency.
    • NAV is always expressed in base currency.
  • When buying or selling an asset, execute the change between:
    • Account's base currency.
    • Asset's domestic currency.
  • Import currency quotes.
    • In the model, allow for a spread.

Implement LOWESS Calculation

Why?

  • I want to test the Superthon and RSI filters using a smoothed version of the instrument quotes.
  • LOESS and LOWESS are very widely used smoothing algorithms.
  • LOWESS is the simplest of the two.

Condition of satisfaction

  • Implement the LOWESS algorithm as another of the statistic calculations.
  • Implement a market timing based on the candle filter and the LOWESS algorithm.

Additional indications:

Improve implementation of EMA and MACD filters

Why?

  • As of currently, there is too much aggregated code to effectively unit test the filters.
  • I have doubts about the implementation of EMA, which is the base for MACD.

Condition of satisfaction

  • Be 100% sure that the algorithm works, by comparing a unit test with some official documentation or tutorial.
  • In particular, isolate the EMA calculation from the EMA filter.

Add dividends information based on different file formats

Why?

  • Because often the dividends are not available from the same source as the quotations. This is particularly true for indexes like IBEX35 or SP500

Condition of satisfaction

  • Use the securities configuration file to point to the dividends information.
  • The format of the dividends file is independent from the format with quotations.

Refactor the code to have a better vocabulary

Why?

  • Because current vocabulary has become inconsistent.

Condition of satisfaction

  • Don't change functionalities.
  • Only change the name of main classes

Some ideas

  • Data retrieved from http://finance.yahoo.com, or http://six-group.com, are Quotes. Some of the quotes represent indexes, other represent securities like funds, bonds or stocks.
  • Therefore, the Stock class should be Quote, and the StockData should be QuoteHistory.
  • Quotes have a name, but as not all quotes are securities, not all quotes have a ISIN (International Security Identification Number), therefore the isin property that is ubiquitous through the code should be name.
  • The services that return quotes are all placed in the services/stock folder. It should be services/quotes.

Use the «candlestick» model in all Quotes

Why?

  • Because the Candlestick contains the open, close, highest and lowest price, that are provided by almost all quote providers.
  • Because when you have stocks from different stock exchange sites and the bank holidays are not the same, then candlestick make it easier to merge, concatenate or extrapolate.
  • Because Candlestick make easier to compute the dividends comparing the PR and TR versions of the same index, which is wanted for #13.
  • Because sometimes the historical quotes are available only on weekly basis. A candlestick better represents what happened during the week that a single closing price value.

Condition of satisfaction

  • Have a domain class called the Candlestick, containing the open, close, highest, lowest prices.
  • Populate those values in all quote services.
  • In HistoricalQuotes, fill all the gaps, so all instruments are present at all instants.
  • Use the candles in the Superthon filter, and others.
  • Keep all functions the same.

Have a market timing based on EMA differences

Why?

  • According to some authors, it is more efficient than MACD for indexes.
  • Because it contains the same initial steps as the MACD, that is already implemented, so there is good opportunity of reusing code.

Condition of satisfaction

  • Implement a Market Timing based on long EMA and short EMA.

Include simulations in Wordpress

Why?

My goal is to write a back-testing blog with plenty of simulation examples:

  • Editing the pages as part of an application is long and painful, and it only makes sense if pages are dynamic.
  • All pages are completely static, what is dynamic is only the simulation component.
  • WordPress is the most widely used framework for blogs.

Condition of satisfaction

  • Package the angular-backtest application as a WordPress pluging that enables using the <simulation> tags.
  • Devise a simple way to make the quotes available.
  • Devise a simple way to update.
  • Write a short user manual to include the plugin.

Technical details

Make a connector to marketstack

Why?

Until now we've been downloading stock data from SIX, YAHOO and INVESTING but, besides being a time consuming process, they only offer historical data of currently listed stock:

  • Until now we've been simulating on indexes or ETF tracking indexes, so it was not an important shortcoming.
  • As soon as we simulate individual stock, we will incur into "survivor bias".
  • To back test momentum strategy, we'll need hundreds of tickers, and downloading them individually is not practicable.

Condition of satisfaction

The idea is not to directly use data from Marketstack during simulation, because there is a limit of the monthly requests.

Instead, it is better to have the downloaded data stored locally:

  • Having a file with all the tickers to be downloaded
  • The script downloads the data for all tickers, and saves it into a folder:
    • If the file doesn't exist yet, create it for the ticker.
    • If the file exists, then append the new data.
  • Use yahoo formatting, so it is directly possible to use the data in simulation.

Technical details

Establish the best market timing

Why?

We've implemented so far: the Candle filter, the EMA filter and the MACD filter:

  • But are they any good?
  • Which one is the best:

Also, we want to use the application, so we can see how handy it is.

Condition of satsifaction

Compare the three filters with the following indexes:

  • Europe:
    • DAX
    • CAC40
    • IBEX
  • Overseas:
    • FTSE
    • SP500
    • ASX
  • Asia:
    • NASDAQ

Establish:

  • The best configuration for each filter
  • The best filter, overall.

Keep:

  • Pages to record the work.

Have a Market Timing based on two Market Timings

Why?

  • Because it is said that a good entry indicator is not a good exit indicator, and vice versa.
  • Because it looks like the MACD indicator is a good entry indicator.

Condition of satisfaction

  • Make a Market Indicator that is the composition of two other market indicators.

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.