Giter VIP home page Giter VIP logo

daveskender / stock.indicators Goto Github PK

View Code? Open in Web Editor NEW
885.0 44.0 220.0 84.56 MB

Stock Indicators for .NET is a C# NuGet package that transforms raw equity, commodity, forex, or cryptocurrency financial market price quotes into technical indicators and trading insights. You'll need this essential data in the investment tools that you're building for algorithmic trading, technical analysis, machine learning, or visual charting.

Home Page: https://dotnet.StockIndicators.dev

License: Apache License 2.0

C# 100.00%
stock-trading stock-market indicators quantitative-finance algorithmic-trading historical-quotes stock-indicators technical-indicators nuget forex

stock.indicators's People

Contributors

balthius avatar chetanku avatar daveskender avatar dependabot[bot] avatar fredrik-c avatar heavymanto avatar imgbot[bot] avatar leedonggeon1996 avatar mihakralj avatar mithrilman avatar myalgomate avatar ooples avatar robertweaver avatar ssathya avatar sshquack avatar tanjera avatar temppus avatar tiger2014 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stock.indicators's Issues

fix Aroon Edge case

In v 0.10.10, Aroon does not pickup an edge case where High High was period + 1 days ago.
This is fixed in #125 and will be available in the next release.

Changing Volume type from long to decimal

Hi

Is it possible to change inside Quote type of Volume from long to decimal? I know that for stocks long is fine, but when you are trading for example with crypto currencies volume is decimal number (as for example you can buy 0,00125 bitcoins).

Thank you
Ivan

Use native culture for dates in main library [exception messages]

Here also one small suggestion: on couple of places you are using CultureInfo("en-US", false) - is it possible to make those properties public in order to adjust to local needs? I noticed it when I was cleaning history data and exception was thrown and had to figure out what was date behind exception text (as I'm from country where usual notation is dd.MM.yyyy). It's just cosmetic as it does not influence calculations.

From #110

Implement IQuote interface to expand utility of quote class

I'm not going to criticize you work at all, it's cool that you put lot of effort in this project, I'm just offering some help if you want to talk about the design of the library and possible improvements both in memory and performance.

An example is about your Quote class, I think it's not a good idea to require a specific class because that way an user has to convert it's own models to Quote with problems both at performance level and design

A proper solution would be to use a IQuote interface, so that it's easy to adapt our own model because it's a matter of implementing that interface in our model without having to convert any object (most of the time our source model already contains close, high, low, date etc... so it's a no brainer to adapt)

Of course Quote class can still be there in the library for those that want to use that model.

Also the Index property is something not needed as I pointed out in a comment here #170 (comment)

but even if needed, having a different interface like IIndexedQuote required only by indicators that need to manage an index would be enough (and if we want to adapt our model adding the index property, we can do that with explicit interface declaration so that our model will not be polluted externally)

If you are open to changes I can try to find some time to contribute and do some benchmark too

Performance Problems with Stochastic Oscillator

Hi,
i realy like your library, it works as described.

But i have a problem: when using the Stochastic Oscillator it upps my execution time by a lot. Going through 1000 stocks using other means of measurement takes 0.9 seconds (pretty fast machine and optimized code). Going through the same stocks using only the Stochastic Oscilator increases the time to 76 seconds.

This is how i call it:

 static public IEnumerable<StochResult> GetStochasticHistory(IEnumerable<Quote> history)
        {
            IEnumerable<StochResult> results = null;
            if (history.Count() > 8)
            {
                results = Indicator.GetStoch(history, 5, 3, 3);
            }
            return results;
        }

Measured with resharper, the "GetStoch" takes the time:
image

Is there any way to optimize the runtime? Is there maybe a light version?

Add AROON Indicators?

Would it be possible to add the AROON indicators (upper and lower) as a function in this library?
I would very much appreciate it :)

Bug: Kama indicator definition not found

I love your highly useful indicators project -- thank you for developing and sharing this. Amazing.

In any event, I'm running into this issue with both v1.2 and v1.3 NuGet packages:

I'm using a number of indicators such as GetStoch(), GetRsi(), etc. without issue. However, GetKama() is not present.

Brief example:

using Skender.Stock.Indicators;
...
... blah blah etc. etc.
...
... {
                var quoteHistory = tradeRepo.FindAllAsQuotes($"{stockName}_historic");
                
                var stoResults = Indicator.GetStoch(quoteHistory);   // works no issues
                var rsiResults = Indicator.GetRsi(quoteHistory); // works no issues
                var kemaResults = Indicator.GetKama(quoteHistory); // GetKama() not found
... }

Build result:

Error CS0117 'Indicator' does not contain a definition for 'GetKama'

MACD - slow calculation

Hi

I'm playing and testing this great library and so far I'm very pleased with it. I did noticed one thing dough - MACD calculation is rather slow. Here is an example:

  • I'm using history of nearly 26000 quotes
    EMA: 30ms
    RSI: 70ms
    MACD: 11,3 sec
    BolingerBands: 10 sec

Are those expected times?

Ivan

performance tuning (general)

Before the first major release (see #104), I wanted to take some time to optimize the performance of the various indicators. I'm opening this issue to track and communicate the progress. This topic has come up in a couple of issues lately for people doing larger-scale operations (#88, #111).

As a baseline, here is the starting point on the performance of the current indicators using two years of historical daily stock quotes (e.g. 502 periods) and default or typical parameters.

I'm using BenchmarkDotNet as my performance benchmarking tool. I'll work on improving these numbers over the next few minor releases. Any help or feedback, as always, is appreciated.

For the latest results, see
https://dotnet.stockindicators.dev/performance

original baseline results

BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19041.450 (2004/?/20H1)
Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.1.401
  [Host]     : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT
  DefaultJob : .NET Core 3.1.7 (CoreCLR 4.700.20.36602, CoreFX 4.700.20.37001), X64 RyuJIT
Method Mean Error StdDev
GetAdl 335.2 μs 3.92 μs 3.27 μs
GetAroon 24,933.9 μs 363.25 μs 303.33 μs
GetAdx 2,311.2 μs 42.90 μs 35.83 μs
GetAtr 380.2 μs 7.38 μs 9.59 μs
GetBollingerBands 23,738.6 μs 310.69 μs 290.62 μs
GetCci 2,587.7 μs 27.05 μs 23.98 μs
GetCmf 1,987.9 μs 21.33 μs 19.95 μs
GetChaikinOsc 2,701.4 μs 11.66 μs 10.91 μs
GetChandelier 26,071.7 μs 153.06 μs 135.68 μs
GetConnorsRsi 5,362.2 μs 47.29 μs 39.49 μs
GetDonchian 25,198.0 μs 144.92 μs 135.55 μs
GetEma 387.5 μs 2.85 μs 2.53 μs
GetHeikinAshi 374.2 μs 3.81 μs 3.38 μs
GetHma 60,646.3 μs 1,209.50 μs 2,359.03 μs
GetIchimoku 99,853.4 μs 2,407.53 μs 6,750.96 μs
GetKeltner 3,105.3 μs 18.69 μs 16.57 μs
GetMacd 3,584.8 μs 67.56 μs 63.20 μs
GetMfi 8,464.6 μs 125.72 μs 117.60 μs
GetObv 235.0 μs 2.70 μs 2.53 μs
GetParabolicSar 22,322.4 μs 184.00 μs 143.66 μs
GetPmo 24,433.4 μs 245.61 μs 229.74 μs
GetRoc 21,636.6 μs 145.37 μs 128.87 μs
GetRsi 682.6 μs 9.08 μs 8.49 μs
GetSma 26,592.6 μs 290.79 μs 257.78 μs
GetStdDev 2,147.0 μs 29.63 μs 26.26 μs
GetStoch 26,191.8 μs 184.06 μs 163.17 μs
GetStochRsi 4,671.5 μs 31.04 μs 27.51 μs
GetUlcerIndex 28,494.0 μs 442.06 μs 391.87 μs
GetWilliamR 25,799.3 μs 281.23 μs 219.56 μs
GetWma 26,955.1 μs 182.45 μs 161.74 μs
GetZigZag 1,599.9 μs 31.77 μs 69.74 μs

See 20-year-benchmarks-v0.10.6.xlsx for benchmarks using 20 years of daily history (5280 periods).

Poll: What kind of flourishes should we include in the library?

Before going to v1.0.0, I want to address a question that's been bothering me for a while. It has to do with the separation of concerns and how pure this library is regarding what it is and does. Early in development, I started adding additional fields to the output that I thought might be helpful, but am considering removing these additional fields. Some indicators (e.g. MACD, RSI, Heikin-Ashi) have basic analysis outputs, like IsBullish or IsIncreasing.

What kind of flourishes should we include in the library?

Take the Poll

For sure, I have no intention of turning this library into a trading system, so going so far as adding buy/sell signals is crossing the line (pun intended). Please also add additional comments below.

Attempted to divide by zero with Bollinger Bands.

Yesterday I switched (for a brief moment) from TA-LIB to your approach, but in I'm getting divide errors. I'm using version version 1.1.2, is this anything familiar?

I think it seems to happen on coins with a low price (like viteusdt=0.0016), but I'm not yet sure that is actually the cause. I'll try to give you some test data soon (today i hope).

System.DivideByZeroException: Attempted to divide by zero.
at System.Decimal.FCallDivide(Decimal& d1, Decimal& d2)
at Skender.Stock.Indicators.Indicator.GetBollingerBands(IEnumerable`1 history, Int32 lookbackPeriod, Decimal standardDeviations)

List resultsbb = (List)Indicator.GetBollingerBands(history);

PSAR initialization produces incorrect first reversal

Investigate the initialization values for the first reversal. Due to the "guess" on the initial trend, it may produce invalid initial results until the true trend emerges. This might be unavoidable; in that case, consider removing the first trend period (make values null).

SuperTrends on TradingView is not correct?

Hi team.
I find SuperTrends result is not correct.
I tested it by "bitcoin 1 day candle 2017-2020" and compared with tradingview indicator result but not matched. (bollingerbands result is correct! good!)

can you check? thanks!

Donchian Channel uses current period price

Donchian Channel should evaluate the N periods prior to the current period, not including the current period, for high/low levels. It is currently using the current period, so no break-out would be identifiable.

Question to users: keep or cut initialization period values?

In a recent issue (#173) a user correctly identified that an indicator had less precision in an initialization phase for an indicator. Some indicators, like ADX, EMA, or others that use smoothing techniques require a runway of about 150-250 periods before the algorithm produces precision to 2 or more decimal places. Early initialization values can be imprecise to small 0.x to 0.0x decimals. This is not unusual for some indicators and precision to 0.00x is not always required for most use cases, especially when the user understands what is happening and can design around it by not using the first 150-250 values. Indicators that require a runway have this mentioned in the documentation.

Question: would you prefer that the library exclude values that don't meet a certain higher precision threshold or keep them? Excluding them would force users to use more history (and I'd probably update the Exception rules to enforce).

Thumbs up = enforce greater precision / exclude initialization values / require more history in Exception rules
Thumbs down = allow 0.x and 0.0x decimal imprecision in early periods and let me decide what to do

Feedback appreciated. Comment below with other ideas.

money flow index

Hi,
First of all thanks for this awesome library.
Do you have any plan to create MFI indicator?

State of Stock.Indicators v1.0.0

As many of you know, we're working towards a v1.0.0 version of this library. I've recently released v0.10.10 with a number of changes based on feedback from a poll (#92). While we will continue to add indicators before and after the v1.0.0 release, I'd like to consider this a major release candidate. At this point, I do not expect to add any significant breaking changes and view the currently published package (v0.11.5) as production-ready.

With that said, I have a few things I'd like to do before flipping the version number:

  • Dogfood in my own trading system for a few weeks or more (in-progress)
  • Add performance benchmarking - AB#727
  • Further optimize performance of slower indicators (#114)
  • Add indicator chart images to documentation - AB#717
  • Incorporate any additional user concerns or ideas
  • Maybe add a few more indicators

Feedback appreciated. Please comment below with your thoughts or submit issues for any problems. And if you want to help, let me know.

Cannot reuse same history list with different slices on different indicators

Hello
I'm trying your library (thanks for the effort so far) and I've found a bug regarding the usage of the quotes to generate different indicators using the same set of historical quotes but taking a different slice of them

Debug was hard on my side, so I took a look at your code and I see that your model classes have an internal Index that you use and I think that's the problem.

Suppose I get historical data from my POCO classes and convert them to your Quote model
suppose I've a list List<Quote> history of 100 Quotes

Now if I call

Indicator.GetBollingerBands(history.TakeLast(20), 20);
Indicator.GetRsi(history.TakeLast(14), 14);

I get a
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.'

I think the problem is that if I reuse Quote objects taking a different slice of the array, the bugs pops out because there is the Index field inconsistence inside your model classes

This means that historical quotes cannot be reused this way but I must always use the same set and I think it's not good because of performance (I'm not interested in applying indicators on the whole historical set in my scenario

Thanks

Error: Insufficient history provided for EMA

Hi guys
I want to use EMA with lookbackPeriod=101 but I got an error that says
"
$exception | {"Insufficient history provided for EMA. You provided 101 periods of history when at least 202 is required. Since this uses a smoothing technique, for a lookback period of 101, we recommend you use at least 351 data points prior to the intended usage date for maximum precision."} | Skender.Stock.Indicators.BadHistoryException
"
P.S: If I set any lookbackPeriod but I got a similar error

update CMF scaling

In v0.10.10 the CMF output is not on the latest scaling model.
This was fixed in #126 and will be available in the next release.

Average Directional Index seems to be slightly off

Hi Dave,

First, thank you for your contribution to this project. I am excited to find this time-saving project a couple of weeks ago.
The issue I am submitting has to do with Average Directional Index (ADX). I notice that it is somewhat off when I compare it with tradingview's ADX/DMI indicator.

For example, on 2000-11-27, the Skender ADX indicator shows
ADX=30.1245
+DI=16.898
-DI=30.579

On the same day, TradingView indicator shows
ADX=30.4113
+DI=16.9263
-DI=30.6871

Could you check if this is a bug?

Thank you,

MACD with insufficient quote history is wrong

I'm getting my historical data from yahoo finance, I have ensured everything is present in the Quote class, and then I pass the data into

int fastPeriod = 12; int slowPeriod = 26; int signalPeriod = 9; IEnumerable<MacdResult> results = Indicator.GetMacd(history, fastPeriod, slowPeriod, signalPeriod);
But it gives me an exception on this line, every time saying "No historical quote provided".

I also have a stack trace for you if that's helpful:

at Skender.Stock.Indicators.Cleaners.PrepareHistory(IEnumerable1 history)\r\n at Skender.Stock.Indicators.Indicator.GetEma(IEnumerable1 history, Int32 lookbackPeriod)\r\n at Skender.Stock.Indicators.Indicator.GetMacd(IEnumerable1 history, Int32 fastPeriod, Int32 slowPeriod, Int32 signalPeriod)\r\n at PT.Middleware.Indicators.GetIndicatorComposite(String symbol, String function, IEnumerable1 history, Int32 daysToCalculate) in C:\\Users\\linki\\Dev\\Pro-Trades\\Middleware\\Indicators.cs:line 55

I tried preparing it with the Cleaners class but it is still giving me the same exception. Please tell me what the fix is or otherwise fix this bug?

Thanks a bunch!

ADl, OBV values are not correct?

I'm using your nuget package from a month , it's been really good. I have the following issues with the package.

  1. OnBalanceVolume Indicator.GetObv(history) is not match with stockcharts/tradingview obv value
  2. Accumulation Distribution (ADL) Indicator.GetAdl(history) also not matching with the stockcharts/tradingview Adl value

Suggestions:

Earlier we have properties IsReversal, Isrising, Isdiverging in MAcd, Rsi, PsarIsrising etc... can you please add those back if possible? can you please apply the same for aaron and others?

Include MAD, MSE and MAPE

Hi Dave!

Good work on the library. I am finding it very useful in my own project and I would be glad to contribute to this library once I am finished with my project. Until then, I would like to suggest adding these results in the output of SMA.

  • Mean Absolute Deviation
  • Mean Square Error
  • Mean Absolute Percentage Error

RSI, AROON the output does not match with the BINANCE exchange

image

GetKlinesBefore_300(DateTime.Now);
private void GetKlinesBefore_300(DateTime dateTime)
{
init_quote_300_Tick_For_Signals.AddRange(BiClient.Spot.Market.GetKlines(pair, KlineInterval.ThreeMinutes, endTime: dateTime)
.Data.Select(u => new Quote
{
Open = u.Open,
Close = u.Close,
Low = u.Low,
High = u.High,
Volume = u.QuoteVolume,
Date = u.CloseTime
}).ToList());
}
decimal? RSI = Indicator.GetRsi(init_quote_300_Tick_For_Signals, 4).LastOrDefault().Rsi;
decimal? RSI_24 = Indicator.GetRsi(init_quote_300_Tick_For_Signals, 6).LastOrDefault().Rsi;
var AROON = Indicator.GetAroon(init_quote_300_Tick_For_Signals,23).LastOrDefault();

GetHistoryFromFeed("MSFT"); isn't being recognized

using System;
using System.Collections.Generic;
using System.Linq;
using Skender.Stock.Indicators;

namespace Stock_API_Core.Calculations
{
public class Rsi
{
public void sample()
{
// fetch historical quotes from your favorite feed, in Quote format
IEnumerable history = GetHistoryFromFeed("MSFT");

        // calculate 20-period SMA
        IEnumerable<SmaResult> results = Indicator.GetSma(history,20);

        // use results as needed
        SmaResult result = results.LastOrDefault();
        Console.WriteLine("SMA on {0} was ${1}", result.Date, result.Sma);
    }
}

}

The GetHistoryFromFeed("MSFT"); isn't being recognized despite importing Skender.Stock.Indicators

I don't understand why this is happening

Remove Index from public classes

Based on feedback from the poll (#92), remove the Index value from Quote and various xxxResult classes. Since these are used by the library, we need to keep them; however, make them internal only for simplification and to make it easier for users to extend classes without having to deal with protection level on that property. We'll need to verify that pre-cleaning still works as intended to improve performance for users who are doing bulk operations on the same history.

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.