Change support and resistance line color in mplfinance - mplfinance

Currently, I'm using this code. How can I change the hlines to red if it's a resistance and blue if it's a support?
mplfinance.plot(df,
type = 'candlestick',
style = 'binance',
hlines=dict(hlines= support_resistance,linestyle='-', linewidths = (1,1)),
volume = True)
I'm getting results like this:

hlines=dict(hlines= support_resistance,linestyle='-',linewidths = (1,1),colors=('b','r')
See for example cell "In [6]" in this tutorial: https://github.com/matplotlib/mplfinance/blob/master/examples/using_lines.ipynb
You may need to include as many colors as you have support_resistance lines. So for example, maybe something like: colors=['b','r','b','r','r','r']
Regarding handling support resistance colors dynamically (per your comment) it is not appropriate for mplfinance to provide algorithms for determining support or resistance, only to provide tools to make it easier for you to visualize them.
Also, each user may have their own specific way of determining support or resistance.
Presumably as you are building the support_resistance list, at the point in your code where you are adding a specific price to that list, you probably know whether that price represents support or resistance. At the same point in your code you should add a color ('b' or 'r') to the colors list. That way you dynamic build two lists: support_resistance, and colors which end up being the same length.

Based on the suggestion from Daniel, I made a list of colors as follows and it worked. support_resistance variable here consists of both support and resistance levels.
colors = []
for lvl in support_resistance:
if lvl > df['Close'][-1]:
colors.append('r')
else:
colors.append('b')

Related

How do I change position offset of wheelnav.js spreader title text

I have failed after several attempts, and massive search attempts (which I may have just failed at), to determine how to move the text in the spreader title to accommodate use of the spreaderStartAngle and spreaderSliceAngle settings, which allow for changing the wheel to smaller sizes (180 or 90 degree versions in my case).
The demo on the site shows the text moving away from the center (starting as a 360 degree circle) down to a quadrant. But in my own use, the re-positioning does not occur automatically, and I see no additional attributes being applied that would cause this.
I have dived into more detail and found that there is apparently something in the Rafael library that may being modified (when looking at the source on the demo page), but it is beyond my understanding on how to approach this via the existing methods.
Anything I have tried makes no change to the text location, which is always centered in what would have been a full circle, regardless of the actual spreader's start and end.
You can position spreader's title via the spreaderPathCustom property.
wheel.spreaderPathCustom = spreaderPath().PieSpreaderCustomization();
wheel.spreaderPathCustom.titleRadiusPercent = 0.58;
wheel.spreaderPathCustom.titleSliceAnglePercent = 0.45;
PieSpreaderCustomization belongs to PieSpreader. The above values of titleRadiusPercent and titleSliceAnglePercent are suitable for 90 degree.

Is there a direct way to set wx.TextCtrl size by characters rather than pixels?

The constructor for wx.TextCtrl takes a wx.Size argument, which is in units of pixels. Usually, I don't want to specify the size of a multiline TextCtrl in pixels, but rather in how many characters it can show without scrolling. I find that multiline TextCtrls are often the dominant component in my windows, thus stretching by Sizer is not an option.
The wxPython Phoenix documentation contains a hint as to how to do this, however this is meant more for short text on single line control.
I have started using this utility method:
def _set_textctrl_size_by_chars(self, tc, w, h):
sz = tc.GetTextExtent('X')
sz = wx.Size(sz.x * w, sz.y * h)
tc.SetInitialSize(tc.GetSizeFromTextSize(sz))
along with code like this:
tc = wx.TextCtrl(self, style=wx.TE_MULTILINE)
self._set_textctrl_size_by_chars(tc, 80, 20)
This works, but I consider it a hack. I have looked over the documentation but have not found any other way to do it.
I understand that fonts are not usually monospaced, and using 'X' as a representative character width is inexact, however it's plenty good enough for my usage. Still, it seems there should be some way to do this directly using the wx library.
Using something like text.GetSizeFromTextSize(text.GetTextExtent("99999").x) is indeed the best way to size the text control to fit exactly 5 digits (e.g. a ZIP code in some localities). Notice that this is slightly better than your code because the width of 80 "X"s is not necessarily quite the same as 80 times the width of a single "X". And I'd also recommend using "M" or "W" which can be noticeably wider than "X" in some fonts, but this is not going to changes matters much.
We thought about adding a helper method doing this and it might indeed be useful, but, again, this still won't make things as simple as you'd like because you really need to specify the characters you want to use: "W" for letters, "9" for digits and maybe something like "x" if you want the control to be wide enough to fit the given number of characters on average instead of being wide enough to guarantee fitting the given number of the widest characters because the difference may be noticeable.
The main place where we could make life simpler would be at XRC level and this would be worth doing ("just" a question of time...), but for the code I really don't think we can make things much simpler than what they're now.

How to change the serie colur and pen in wxFreeChart?

I am using wxFreeChart library in my project. However I am unable to change the colour and line type in XY data series. In the documentation nor in the samples there is no example of such functionality. Also there are not straightforward functions allowsing to do this. Does anyone has experience with this library to say if it is even possible?
Yes, it is possible to set both the serie colour and the pen type for XY line charts.
These attributes are set via the XYLineRenderer class. The documentation does cover this but you have to click on the "List all members" to see them. The current documentation is available under XYLineRenderer Members.
For simple changes, you can access the XYLineRenderer using the XYDataset::GetRenderer() method. This returns an XYRenderer* which you will need to cast to a XYLineRenderer* in order to set the pen type. Of course you can create the XYLineRenderer* first and pass it to the XYDataset::SetRenderer method instead.
Here is an example:
// Set the colour and pen of the first series.
static_cast<XYLineRenderer*>(dataset->GetRenderer())
->SetSeriePen(0, new wxPen(*wxRED, 5, wxPENSTYLE_SHORT_DASH));
// Set the colour and pen of the second series.
static_cast<XYLineRenderer*>(dataset->GetRenderer())
->SetSeriePen(1, new wxPen(*wxBLUE, 1, wxPENSTYLE_DOT_DASH));
SetSeriePen is only available to XYLineRenderer for obvious reasons, but you can set the colour of any renderer with Renderer::SetSerieColour(size_t serie, wxColour *color).
Note: I am not that happy with the way wxFreeChart takes pointers in these functions. This project is not actively maintained, but I would like at some point to fork it and update the API to be more consistent with modern versions of C++ and wxWidgets.

Cannot change polygon 'size' every repeat in Builder

I'm using Builder v1.80.06
I can vary the position of a polygon every repeat easily enough
e.g. I have a Positions list
positions=[[1,1],[1.1,0.9],...]
and in the 'Position field' have :
$positions[0]
and then change it's value in a code block on each repeat.
BUT I want to vary the size in a similar manner with a $sizes list but get an error.
Looking at the generated code, the problem is at the object creation stage. the code generated is:
for a hard coded polygon (ie ok)
polygon_1 = visual.Rect(win=win, name='polygon_1',
width=[1.5, .2][0], height=[1.5, .2][1],
ori=0, pos=[0, -0.6],
lineWidth=1, lineColor=[1,1,1], lineColorSpace=u'rgb',
fillColor=[0,1,0], fillColorSpace=u'rgb',
opacity=1,interpolate=True)
for one populated by a variable (not working):
polygon_2= visual.Rect(win=win, name='polygon_2',
width=1.0[0], height=1.0[1],
ori=0, pos=[0,0],
lineWidth=1, lineColor=[1,1,1], lineColorSpace=u'rgb',
fillColor=[1,0,0], fillColorSpace=u'rgb',
opacity=1,interpolate=True)
It complains (rightly) that 1.0[0] makes no sense on the width and height parameters
Even though I have my sizes list instantiated in a code block right at the beginning of the experiment instead of reading $sizes[0] a default float value of 1.0 is used.
Any other suggestions for how to vary the polygon size dynamically at runtime using builder?
I could just take the generated code and drop it into coder I suppose and fix the problem but I want to hand this over to a researcher so would like for them to be able to maintain it.
thanks,
If you set size to be a tuple/list with a pair values [1.2,1.5] or [1,1] does that not fix it?
When you change attributes at runtime, just change the attribute of an existing stimulus instead of instantiating a full new stimulus. The latter is quite heavy on ressources, causing unreliable timing. So do
stim = visual.Rect(win) # instantiation, ressource heavy
stim.attribute = newValue # change attribute. lighter.
I can think of two ways you could do it in a pretty neat way. The first is to set width and height explicitly instead of the size attribute, but using a size-like value. So (removing all parameters not of interest):
polygon_2 = visual.Rect(win)
# Unpack the x,y-sizes to the stimulus .width and .height attributes
newSize = (1.5, 0.2)
polygon_2.width, polygon_2.height = newSize
The second, if the size attribute is really important to use, is to use the Polygin with edges=4 to make it a rectangle:
polygon_2 = visual.Polygon(win=win, edges=4, size=(1.5, 0.2))
# Setting size
polygon_2.size = (0.8, 0.4)
Do try Jon's suggestion first. But the idea with visual.Rect and visual.Circleis to use substitute Polygon's size and vertices for something more relevant. So size can do unexpected things if width/height etc. are not 1.

How can I compare two NSImages for differences?

I'm attempting to gauge the percentage difference between two images.
Having done a lot of reading I seem to have a number of options but I'm not sure what the best method to follow for:
Ease of coding
Performance.
The methods I've seen are:
Non language specific - academic Image comparison - fast algorithm and Mac specific direct pixel access http://www.markj.net/iphone-uiimage-pixel-color/
Does anyone have any advice about what solutions make most sense for the above two cases and have code samples to show how to apply them?
I've had success calculating the difference between two images using the histogram technique mentioned here. redmoskito's answer in the SO question you linked to was actually my inspiration!
The following is an overview of the algorithm I used:
Convert the images to grayscale—compare one channel instead of three.
Divide each image into an n * n grid of "subimages". Then, for subimage pair:
Calculate their colour composition histograms.
Calculate the absolute difference between the two histograms.
The maximum difference found between two subimages is a measure of the two images' difference. Other metrics could also be used (e.g. the average difference betwen subimages).
As tskuzzy noted in his answer, if your ultimate goal is a binary "yes, these two images are (roughly) the same" or "no, they're not", you need some meaningful threshold value. You could produce such a value by passing images into the algorithm and tweaking the threshold based on its output and how similar you think the images are. A form of machine learning, I suppose.
I recently wrote a blog post on this very topic, albeit as part of a larger goal. I also created a simple iPhone app to demonstrate the algorithm. You can find the source on GitHub; perhaps it will help?
It is really difficult to suggest something when you don't tell us more about the images or the variations. Are they shapes? Are they the different objects and you want to know what class of objects? Are they the same object and you want to distinguish the object instance? Are they faces? Are they fingerprints? Are the objects in the same pose? Under the same illumination?
When you say performance, what exactly do you mean? How large are the images? All in all it really depends. With what you've said if it is only ease of coding and performance I would suggest to just find the absolute value of the difference of pixels. That is super easy to code and about as fast as it gets, but really unlikely to work for anything other than the most synthetic examples.
That being said I would like to point you to: DHOG, GLOH, SURF and SIFT.
You can use fairly basic subtraction technique that the lads above suggested. #carlosdc has hit the nail on the head with regard to the type of image this basic technique can be used for. I have attached an example so you can see the results for yourself.
The first shows a image from a simulation at some time t. A second image was subtracted away from the first which was taken some (simulation) time later t + dt. The subtracted image (in black and white for clarity) then shows how the simulation has changed in that time. This was done as described above and is very powerful and easy to code.
Hope this aids you in some way
This is some old nasty FORTRAN, but should give you the basic approach. It is not that difficult at all. Due to the fact that I am doing it on a two colour pallette you would do this operation for R, G and B. That is compute the intensities or values in each cell/pixal, store them in some array. Do the same for the other image, and subtract one array from the other, this will leave you with some coulorfull subtraction image. My advice would be to do as the lads suggest above, compute the magnitude of the sum of the R, G and B componants so you just get one value. Write that to array, do the same for the other image, then subtract. Then create a new range for either R, G or B and map the resulting subtracted array to this, the will enable a much clearer picture as a result.
* =============================================================
SUBROUTINE SUBTRACT(FNAME1,FNAME2,IOS)
* This routine writes a model to files
* =============================================================
* Common :
INCLUDE 'CONST.CMN'
INCLUDE 'IO.CMN'
INCLUDE 'SYNCH.CMN'
INCLUDE 'PGP.CMN'
* Input :
CHARACTER fname1*(sznam),fname2*(sznam)
* Output :
integer IOS
* Variables:
logical glue
character fullname*(szlin)
character dir*(szlin),ftype*(3)
integer i,j,nxy1,nxy2
real si1(2*maxc,2*maxc),si2(2*maxc,2*maxc)
* =================================================================
IOS = 1
nomap=.true.
ftype='map'
dir='./pictures'
! reading first image
if(.not.glue(dir,fname2,ftype,fullname))then
write(*,31) fullname
return
endif
OPEN(unit2,status='old',name=fullname,form='unformatted',err=10,iostat=ios)
read(unit2,err=11)nxy2
read(unit2,err=11)rad,dxy
do i=1,nxy2
do j=1,nxy2
read(unit2,err=11)si2(i,j)
enddo
enddo
CLOSE(unit2)
! reading second image
if(.not.glue(dir,fname1,ftype,fullname))then
write(*,31) fullname
return
endif
OPEN(unit2,status='old',name=fullname,form='unformatted',err=10,iostat=ios)
read(unit2,err=11)nxy1
read(unit2,err=11)rad,dxy
do i=1,nxy1
do j=1,nxy1
read(unit2,err=11)si1(i,j)
enddo
enddo
CLOSE(unit2)
! substracting images
if(nxy1.eq.nxy2)then
nxy=nxy1
do i=1,nxy1
do j=1,nxy1
si(i,j)=si2(i,j)-si1(i,j)
enddo
enddo
else
print *,'SUBSTRACT: Different sizes of image arrays'
IOS=0
return
endif
* normal finishing
IOS=0
nomap=.false.
return
* exceptional finishing
10 write (*,30) fullname
return
11 write (*,32) fullname
return
30 format('Cannot open file ',72A)
31 format('Improper filename ',72A)
32 format('Error reading from file ',72A)
end
! =============================================================
Hope this is of some use. All the best.
Out of the methods described in your first link, the histogram comparison method is by far the simplest to code and the fastest. However key point matching will provide far more accurate results since you want to know a precise number describing the difference between two images.
To implement the histogram method, I would do the following:
Compute the red, green, and blue histograms of each image
Add up the differences between each bucket
If the difference is above a certain threshold, then the percentage is 0%
Otherwise the colors found in the images are similar. So then do a pixel by pixel comparison and convert the difference into a percentage.
I don't know any precise algorithms for finding the key points of an image. However once you find them for each image you can do a pixel by pixel comparison for each of the key points.