MACD Indicator binance - algorithmic-trading

I am really beginner in programming / python.
I don't have the MACD INDICATOR in python.
for MACD indicator, how to say ' when the 2 lines are crossing (histograms flip from down to up) and vice versa, so buy '
I can do the buy order, but how to write the cross/flip action.
I am trying with python on binance.
Thanks

I have just finished my code for MACD,
MACD done by,
1.Calculate a 12-period EMA of the price for the chosen time period.
raw['EMA12'] = raw.close.ewm(span=12).mean().dropna()
2.Calculate a 26-period EMA of the price for the chosen time period.
raw['EMA26'] = raw.close.ewm(span=26).mean().dropna()
3.Subtract the 26-period EMA from the 12-period EMA.
raw['diffEMA'] = raw.EMA12 - raw.EMA26
4.Calculate a nine-period EMA of the result obtained from step 3.
raw['EMA9diff'] = raw.diffEMA.ewm(span = 9).mean().dropna()
5. histograms / MACD signal line
raw['MACDline'] = raw['diffEMA'] - raw['EMA9diff']

Related

Wrong value from a second time interval in pine script

Good morning,
I have a little problem there.
I would like work with data from two different time interval.
for example, BTC (1 day time interval) and BTC (4 hour time interval) chart.
The main time interval is the 4 hour. The value "HA_C", this is the close value of "BTC 1 Day".
The "close BTC 1 Day time interval" value displayed correct in the 4 hour chart.
But the value "test" with a simple arithmetic problem differs greatly and is wrong.
You can test this as follows:
Loads the strategy in "BTC", time interval "1 Day",
note from one day the "BTC Close" value and the "test" value.
Then switch to "BTC" 4 hour time interval.
You will see, that the "HA_C Close" from the 1 hour time interval is the correct value,
but the "test" value is displayed incorrectly.
Why is the "test" value after a calculation incorrectly, although the "Close" value is correct ???
I have find out, that the problem is the "ta.ema (source, length)" function. Can someone give me a formula, that calculates the same value as the "ta.ema (source, length)" function.
**// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © flashpit
//#version=5
strategy("TEST", process_orders_on_close=true, overlay=true, calc_on_every_tick=true, pyramiding=30)
varip test = 0.0
HA_Symbol = ticker.heikinashi("BINANCE:BTCUSDT")
HA_C = request.security(HA_Symbol, "1D", close)
test:= ta.ema(HA_C, 7) * 1.05
plot (HA_C)
plot (test)**
I have finde the correct code. Here is it:
c2_1D = request.security(ticker.heikinashi('BINANCE:BTCUSDT'), "1D", t3_D (close, T3Length_1D, T3FactorCalc_1D))
It is due to the context you have called the ema function. If your chart is H4 and you perform your test calculation in the global scope, it is using 7 x H4 bars of HA_C. On BTCUSDT, over the last 7 H4 bars, it would have been 7 bars made up of multiples of only 2 daily values, hence the incorrect result.
When you change the chart to D1, it shows the correct result because now the global context of the script is now operating in the same timeframe as the security call.
If you want the correct value from the ema using 7 x 1D bars it has to be done within the context of the security call. For example :
test = request.security(ticker.heikinashi("BINANCE:BTCUSDT"), "D", ta.ema(close, 7))
If you need to perform multiple operations using the same ticker, you can also wrap them in a function and just pass the one function to a single security call. For example, this will return the daily close and the daily ema 7 :
f_ema_and_close(_src, _len) =>
_ema = ta.ema(_src, _len)
[_src, _ema]
[D1_close, D1_ema7] = request.security(ticker.heikinashi("BINANCE:BTCUSDT"), "D", f_ema_and_close(close, 7))
plot(D1_close, color = color.yellow)
plot(D1_ema7, color = color.red)

Neural network - solve a net with time arrays and different sample rate

I have 3 measurements for a machine. Each measurement is trigged every time its value changes by a certain delta.
I have these 3 data sets, represented as Matlab objects: T1, T2 and O. Each of them has a obj.t containing the timestamp values and obj.y containing the measurement values.
I will measure T1 and T2 for a long time, but O only for a short period. The task is to reconstruct O_future from T1 and T2, using the existing values for O for training and validation.
Note that T1.t, T2.t and O.t are not equal, not even their frequency (I might call it 'variable sample rate', but not sure if this name applies).
Is it possible to solve this problem using Matlab or other software? Do I need to resample all data to a common time vector?
Concerning the common time. Below some basic code which does this. (I guess you might know how to do it but just in case). However, the second option might bring you further...
% creating test signals
t1 = 1:2:100;
t2 = 1:3:200;
to = [5 6 100 140];
s1 = round (unifrnd(0,1,size(t1)));
s2 = round (unifrnd(0,1,size(t2)));
o = ones(size(to));
maxt = max([t1 t2 to]);
mint = min([t1 t2 to]);
% determining minimum frequency
frequ = min([t1(2:length(t1)) - t1(1:length(t1)-1) t2(2:length(t2)) - t2(1:length(t2)-1) to(2:length(to)) - to(1:length(to)-1)] );
% create a time vector with highest resolution
tinterp = linspace(mint,maxt,(maxt-mint)/frequ+1);
s1_interp = zeros(size(tinterp));
s2_interp = zeros(size(tinterp));
o_interp = zeros(size(tinterp));
for i = 1: length(t1)
s1_interp(ceil(t1(i))==floor(tinterp)) =s1(i);
end
for i = 1: length(t2)
s2_interp(ceil(t2(i))==floor(tinterp)) =s2(i);
end
for i = 1: length(to)
o_interp(ceil(to(i))==floor(tinterp)) = o(i);
end
figure,
subplot 311
hold on, plot(t1,s1,'ro'), plot(tinterp,s1_interp,'k-')
legend('observation','interpolation')
title ('signal 1')
subplot 312
hold on, plot(t2,s2,'ro'), plot(tinterp,s2_interp,'k-')
legend('observation','interpolation')
title ('signal 2')
subplot 313
hold on, plot(to,o,'ro'), plot(tinterp,o_interp,'k-')
legend('observation','interpolation')
title ('O')
Its not ideal as for large vectors this might become ineffective as soon as you have small sampling frequencies in one of the signals which will determine the lowest resolution.
Another option would be to define a coarser time vector and look at the number of events that happend in a certain period which might have some predictive power as well (not sure about your setup).
The structure would be something like
coarse_t = 1:5:100;
s1_coarse = zeros(size(coarse_t));
s2_coarse = zeros(size(coarse_t));
o_coarse = zeros(size(coarse_t));
for i = 2:length(coarse_t)
s1_coarse(i) = sum(nonzeros(s1(t1<coarse_t(i) & t1>coarse_t(i-1))));
s2_coarse(i) = sum(nonzeros(s2(t2<coarse_t(i) & t2>coarse_t(i-1))));
o_coarse(i) = sum(nonzeros(o(to<coarse_t(i) & to>coarse_t(i-1))));
end

How do I calculate the probable success rate in a game: x + random(12) => y

I'm trying to program a line of Ruby code that calculates the probable success rate of a simple skill test in a text adventure game. The test is "if x + random(12) => y then". How do I calculate the probable rate of success of this statement being true in Ruby?
In the game the player has certain skills and will occasionally have to test those skills plus a random number to get greater or equal to a given difficulty number. I want to calculate the success rate percentage of being able to win that skill test.
As an example in the adventure game your trying to track some animal through the jungle. To do this you must test your skill at tracking. If for example you have a tracking skill of 3 and you add a random number between 1-12 to that, you need to score at least a 9 or greater to succeed. Basically: Skill + random(12) => Difficulty_Number. I want to show a Success Rate percentage before they play to see what their chance of succeeding will be.
So in Ruby, what would be the algorithm to figure out the chance of success with my current Skill score? Thanks!
You could do this.
def success_rate(skill, success_level, random_range=12)
delta = success_level - skill
return [100 - (delta.to_f / random_range * 100), 100].min.round(2)
end

calculate standard deviation of daily data within a year

I have a question,
In Matlab, I have a vector of 20 years of daily data (X) and a vector of the relevant dates (DATES). In order to find the mean value of the daily data per year, I use the following script:
A = fints(DATES,X); %convert to financial time series
B = toannual(A,'CalcMethod', 'SimpAvg'); %calculate average value per year
C = fts2mat(B); %Convert fts object to vector
C is a vector of 20 values. showing the average value of the daily data for each of the 20 years. So far, so good.. Now I am trying to do the same thing but instead of calculating mean values annually, i need to calculate std annually but it seems there is not such an option with function "toannual".
Any ideas on how to do this?
THANK YOU IN ADVANCE
I'm assuming that X is the financial information and it is an even distribution across each year. You'll have to modify this if that isn't the case. Just to clarify, by even distribution, I mean that if there are 20 years and X has 200 values, each year has 10 values to it.
You should be able to do something like this:
num_years = length(C);
span_size = length(X)/num_years;
for n = 0:num_years-1
std_dev(n+1,1) = std(X(1+(n*span_size):(n+1)*span_size));
end
The idea is that you simply pass the date for the given year (the day to day values) into matlab's standard deviation function. That will return the std-dev for that year. std_dev should be a column vector that correlates 1:1 with your C vector of yearly averages.
unique_Dates = unique(DATES) %This should return a vector of 20 elements since you have 20 years.
std_dev = zeros(size(unique_Dates)); %Just pre allocating the standard deviation vector.
for n = 1:length(unique_Dates)
std_dev(n) = std(X(DATES==unique_Dates(n)));
end
Now this is assuming that your DATES matrix is passable to the unique function and that it will return the expected list of dates. If you have the dates in a numeric form I know this will work, I'm just concerned about the dates being in a string form.
In the event they are in a string form you can look at using regexp to parse the information and replace matching dates with a numeric identifier and use the above code. Or you can take the basic theory behind this and adapt it to what works best for you!

Calculating IRR in ruby

Can anyone help me with a method that calculates the IRR of a series of stock trades?
Let's say the scenario is:
$10,000 of stock #1 purchased 1/1 and sold 1/7 for $11,000 (+10%)
$20,000 of stock #2 purchased 1/1 and sold 1/20 for $21,000 (+5%)
$15,000 of stock #3 purchased on 1/5 and sold 1/18 for $14,000 (-6.7%)
This should be helpful: http://www.rubyquiz.com/quiz156.html
But I couldn't figure out how to adapt any of the solutions since they assume the period of each return is over a consistent period (1 year).
I finally found exactly what I was looking for: http://rubydoc.info/gems/finance/1.1.0/Finance/Cashflow
gem install finance
To solve the scenario I posted originally:
include Finance
trans = []
trans << Transaction.new( -10000, date: Time.new(2012,1,1) )
trans << Transaction.new( 11000, date: Time.new(2012,1,7) )
trans << Transaction.new( -20000, date: Time.new(2012,1,1) )
trans << Transaction.new( 21000, date: Time.new(2012,1,20) )
trans << Transaction.new( -15000, date: Time.new(2012,1,5) )
trans << Transaction.new( 14000, date: Time.new(2012,1,18) )
trans.xirr.apr.to_f.round(2)
I also found this simple method: https://gist.github.com/1364990
However, it gave me some trouble. I tried a half dozen different test cases and one of them would raise an exception that I was never able to debug. But the xirr() method in this Finance gem worked for every test case I could throw at it.
For an investment that has an initial value and final value, as is the case with your example data that includes purchase price, sell price and a holding period, you only need to find holding period yield.
Holding period yield is calculated by subtracting 1 from holding period return
HPY = HPR - 1
HPR = final value/initial value
HPY = 11,000/10,000 - 1 = 1.1 - 1 = 0.10 = 10%
HPY = 21,000/20,000 - 1 = 1.05 - 1 = 0.05 = 5%
HPY = 14,000/15,000 - 1 = 0.9333 - 1 = -0.0667 = -6.7%
This article explains holding period return and yield
You can also annualize the holding period return and holding period yield using following formula
AHPR = HPR^(1/n)
AHPY = AHPR - 1
The above formulas only apply if you have a single period return as is the case with your example stock purchase and sale.
Yet if you had multiple returns, for example, you purchased a stock A on 1/1 for 100 and it's closing price over the next week climbed and fell to 98, 103, 101, 100, 99, 104
Then you will have to look beyond what HPR and HPY for multiple returns. In this case you can calculate ARR and GRR. Try out these online calculators for arithmetic rate of return and geometric rate of return.
But then if you had a date schedule for your investments then none of these would apply. You would then have to resort to finding IRR for irregular cash flows. IRR is the internal rate of return for periodic cash flows. For irregular cash flows such as for stock trade, the term XIRR is used. XIRR is an Excel function that calculates internal rate of return for irregular cash flows. To find XIRR you would need a series of cash flows and a date schedule for the cash flows.
Finance.ThinkAndDone.com explains IRR in much more detail than the articles you cited on RubyQuiz and Wiki. The IRR article on Think & Done explains IRR calculation with Newton Raphson method and Secant method using either the NPV equation set to 0 or the profitability index equation set to 1. The site also provides online IRR and XIRR calculators
I don't know anything about finance, but it makes sense to me that if you want to know the rate of return over 6 months, it should be the rate which equals the yearly rate when compounded twice. If you want to know the rate for 3 months, it should be the rate which equals the yearly rate when compounded 4 times, etc. This implies that converting from a yearly return rate to a rate for an arbitrary period is closely related to calculating roots. If you express the yearly return rate as a proportion of the original amount (i.e. express 20% return as 1.2, 100% return as 2.0, etc), then you can get the 6-month return rate by taking the square root of that number.
Ruby has a very handy way to calculate all kinds of complex roots: the exponentiation operator, **.
n ** 0.5 # square root
n ** (1.0/3.0) # 3rd root
...and so on.
So I think you should be able to convert a yearly rate of return to one for an arbitrary period by:
yearly_return ** (days.to_f / 365)
Likewise to convert a daily, weekly, or monthly rate or return to a yearly rate:
yearly_return = daily_return ** 365
yearly_return = weekly_return ** 52
yearly_return = monthly_return ** 12
...and so on.
As far as I can see (from reading the Wikipedia article), the IRR calculation is not actually dependent on the time period used. If you give a series of yearly cash flows as input, you get a yearly rate. If you give a series of daily cash flows as input, you get a daily rate, and so on.
I suggest you use one of the solutions you linked to to calculate IRR for daily or weekly cash flows (whatever is convenient), and convert that to a yearly rate using exponentiation. You will have to add 1 to the output of the irr() method (so that 10% return will be 1.1 rather than 0.1, etc).
Using the daily cash flows for the example you gave, you could do this to get daily IRR:
irr([-30000,0,0,0,-15000,0,11000,0,0,0,0,0,0,0,0,0,0,14000,0,21000])
You can use the Exonio library:
https://github.com/Noverde/exonio
and use it like this:
Exonio.irr([-100, 39, 59, 55, 20]) # ==> 0.28095
I believe that the main problem in order to be able to understand your scenario is the lack of a cash flow for each of the stocks, which is an essential ingredient for computing any type of IRR, without these, none of the formulas can be used. If you clarify this I can help you solve your problem
Heberto del Rio
There is new gem 'finance_math' that solves this problem very easy
https://github.com/kolosek/finance_math

Resources