Instruction:
How would you implement a function in Python 3 that
functions to plot a series of objects in the DataFrame.

Response:
def _iplot(self,kind='scatter',data=None,layout=None,filename='',sharing=None,title='',xTitle='',yTitle='',zTitle='',theme=None,colors=None,colorscale=None,fill=False,width=None,
			dash='solid',mode='',interpolation='linear',symbol='circle',size=12,barmode='',sortbars=False,bargap=None,bargroupgap=None,bins=None,histnorm='',
			histfunc='count',orientation='v',boxpoints=False,annotations=None,keys=False,bestfit=False,
			bestfit_colors=None,mean=False,mean_colors=None,categories='',x='',y='',z='',text='',gridcolor=None,
			zerolinecolor=None,margin=None,labels=None,values=None,secondary_y='',secondary_y_title='',subplots=False,shape=None,error_x=None,
			error_y=None,error_type='data',locations=None,lon=None,lat=None,asFrame=False,asDates=False,asFigure=False,
			asImage=False,dimensions=None,asPlot=False,asUrl=False,online=None,**kwargs):
	"""
	Returns a plotly chart either as inline chart, image of Figure object

	Parameters:
	-----------
		kind : string
			Kind of chart
				scatter
				bar
				box
				spread
				ratio
				heatmap
				surface
				histogram
				bubble
				bubble3d
				scatter3d
				scattergeo
				ohlc
				candle
				pie
				choroplet
		data : Data
			Plotly Data Object.
			If not entered then the Data object will be automatically
			generated from the DataFrame.
		layout : Layout
			Plotly layout Object
			If not entered then the Layout objet will be automatically
			generated from the DataFrame.
		filename : string
			Filename to be saved as in plotly account
		sharing : string
			Sets the sharing level permission
				public - anyone can see this chart
				private - only you can see this chart
				secret - only people with the link can see the chart
		title : string
			Chart Title
		xTitle : string
			X Axis Title
		yTitle : string
			Y Axis Title
				zTitle : string
		zTitle : string
			Z Axis Title
			Applicable only for 3d charts
		theme : string
			Layout Theme
				solar
				pearl
				white
			see cufflinks.getThemes() for all
			available themes
		colors : dict, list or string
			{key:color} to specify the color for each column
			[colors] to use the colors in the defined order
		colorscale : string
			Color scale name
			If the color name is preceded by a minus (-)
			then the scale is inversed
			Only valid if 'colors' is null
			See cufflinks.colors.scales() for available scales
		fill : bool
			Filled Traces
		width : dict, list or int
				int : applies to all traces
				list : applies to each trace in the order
						specified
				dict: {column:value} for each column in
						the dataframe
			Line width
		dash : dict, list or string
				string : applies to all traces
				list : applies to each trace in the order
						specified
				dict: {column:value} for each column in
						the dataframe
			Drawing style of lines
				solid
				dash
				dashdot
				dot
		mode : dict, list or string
				string : applies to all traces
				list : applies to each trace in the order
						specified
				dict: {column:value} for each column in
						the dataframe
			Plotting mode for scatter trace
				lines
				markers
				lines+markers
				lines+text
				markers+text
				lines+markers+text
		interpolation : dict, list, or string
				string : applies to all traces
				list : applies to each trace in the order
						specified
				dict: {column:value} for each column in
						the dataframe
			Positioning of the connecting lines
				linear
				spline
				vhv
				hvh
				vh
				hv
		symbol : dict, list or string
				string : applies to all traces
				list : applies to each trace in the order
						specified
				dict: {column:value} for each column in
						the dataframe
			The symbol that is drawn on the plot for each marker
			Valid only when mode includes markers
				circle
				circle-dot
				diamond
				square
				and many more...(see plotly.validators.scatter.marker.SymbolValidator.values)
		size : string or int
			Size of marker
			Valid only if marker in mode
		barmode : string
			Mode when displaying bars
				group
				stack
				overlay
			* Only valid when kind='bar'
		sortbars : bool
			Sort bars in descending order
			* Only valid when kind='bar'
		bargap : float
			Sets the gap between bars
				[0,1)
			* Only valid when kind is 'histogram' or 'bar'
		bargroupgap : float
			Set the gap between groups
				[0,1)
			* Only valid when kind is 'histogram' or 'bar'
		bins : int or tuple
			if int:
				Specifies the number of bins
			if tuple:
				(start, end, size)
				start : starting value
				end: end value
				size: bin size
			* Only valid when kind='histogram'

		histnorm : string
				'' (frequency)
				percent
				probability
				density
				probability density
			Sets the type of normalization for an histogram trace. By default
			the height of each bar displays the frequency of occurrence, i.e.,
			the number of times this value was found in the
			corresponding bin. If set to 'percent', the height of each bar
			displays the percentage of total occurrences found within the
			corresponding bin. If set to 'probability', the height of each bar
			displays the probability that an event will fall into the
			corresponding bin. If set to 'density', the height of each bar is
			equal to the number of occurrences in a bin divided by the size of
			the bin interval such that summing the area of all bins will yield
			the total number of occurrences. If set to 'probability density',
			the height of each bar is equal to the number of probability that an
			event will fall into the corresponding bin divided by the size of
			the bin interval such that summing the area of all bins will yield
			1.
			* Only valid when kind='histogram'
		histfunc : string
				count
				sum
				avg
				min
				max
		   Sets the binning function used for an histogram trace.
			* Only valid when kind='histogram'
		orientation : string
				h
				v
			Sets the orientation of the bars. If set to 'v', the length of each
 |          bar will run vertically. If set to 'h', the length of each bar will
 |          run horizontally
			* Only valid when kind is 'histogram','bar' or 'box'
		boxpoints : string
			Displays data points in a box plot
				outliers
				all
				suspectedoutliers
				False
		annotations : dictionary
			Dictionary of annotations
			{x_point : text}
		keys : list of columns
			List of columns to chart.
			Also can be used for custom sorting.
		bestfit : boolean or list
			If True then a best fit line will be generated for
			all columns.
			If list then a best fit line will be generated for
			each key on the list.
		bestfit_colors : list or dict
			{key:color} to specify the color for each column
			[colors] to use the colors in the defined order
		categories : string
			Name of the column that contains the categories
		x : string
			Name of the column that contains the x axis values
		y : string
			Name of the column that contains the y axis values
		z : string
			Name of the column that contains the z axis values
		text : string
			Name of the column that contains the text values
		gridcolor : string
			Grid color
		zerolinecolor : string
			Zero line color
		margin : dict or tuple
			Dictionary (l,r,b,t) or
			Tuple containing the left,
			right, bottom and top margins
		labels : string
			Name of the column that contains the labels.
			* Only valid when kind='pie'
		values : string
			Name of the column that contains the values.
			* Only valid when kind='pie'
		secondary_y : string or list(string)
			Name(s) of the column to be charted on the
			right hand side axis
		secondary_y_title : string
			Title of the secondary axis
		subplots : bool
			If true then each trace is placed in
			subplot layout
		shape : (rows,cols)
			Tuple indicating the size of rows and columns
			If omitted then the layout is automatically set
			* Only valid when subplots=True
		error_x : int or float or [int or float]
			error values for the x axis
		error_y : int or float or [int or float]
			error values for the y axis
		error_type : string
			type of error bars
				'data'
				'constant'
				'percent'
				'sqrt'
				'continuous'
				'continuous_percent'
		asFrame : bool
			If true then the data component of Figure will
			be of Pandas form (Series) otherwise they will
			be index values
		asDates : bool
			If true it truncates times from a DatetimeIndex
		asFigure : bool
			If True returns plotly Figure
		asImage : bool
			If True it returns an Image (png)
			In ONLINE mode:
				Image file is saved in the working directory
					Accepts:
						filename
						dimensions
						scale
						display_image
			In OFFLINE mode:
				Image file is downloaded (downloads folder) and a
				regular plotly chart is displayed in Jupyter
					Accepts:
						filename
						dimensions
		dimensions : tuple(int,int)
			Dimensions for image / chart
				(width,height)
		asPlot : bool
			If True the chart opens in browser
		asUrl : bool
			If True the chart url/path is returned. No chart is displayed.
				If Online : the URL is returned
				If Offline : the local path is returned
		online : bool
			If True then the chart/image is rendered on the server
			even when running in offline mode.

		Other Kwargs
		============
		Line, Scatter
			connectgaps : bool
				If True, empty values are connected
		Pie charts
			sort : bool
				If True it sorts the labels by value
			pull : float [0-1]
				Pulls the slices from the centre
			hole : float [0-1]
				Sets the size of the inner hole
			linecolor : string
				Sets the color for the contour line of the slices
			linewidth : string
				Sets the width for the contour line of the slices
			textcolor : string
				Sets the color for the text in the slices
			textposition : string
				Sets the position of the legends for each slice
					outside
					inner
			textinfo : string
				Sets the information to be displayed on
				the legends
					label
					percent
					value
					* or ony combination of the above using
					  '+' between each item
					  ie 'label+percent'

		Histogram
			linecolor : string
				specifies the line color of the histogram

		Heatmap and Surface
			center_scale : float
				Centers the colorscale at a specific value
				Automatically sets the (zmin,zmax) values
			zmin : float
				Defines the minimum range for the z values.
				This affects the range for the colorscale
			zmax : float
				Defines the maximum range for the z values.
				This affects the range for the colorscale

		Error Bars
			error_trace : string
				Name of the column for which error should be
				plotted. If omitted then errors apply to all
				traces.
			error_values_minus : int or float or [int or float]
				Values corresponding to the span of the error bars
				below the trace coordinates
			error_color : string
				Color for error bars
			error_thickness : float
				Sets the line thickness of the error bars
			error_width :  float
				Sets the width (in pixels) of the cross-bar at both
				ends of the error bars
			error_opacity : float [0,1]
				Opacity for the error bars

		Subplots
			horizontal_spacing : float [0,1]
				Space between subplot columns.
			vertical_spacing : float [0,1]
				Space between subplot rows.
			subplot_titles : bool
				If True, chart titles are plotted
				at the top of each subplot
			shared_xaxes : bool
				Assign shared x axes.
				If True, subplots in the same grid column have one common
				shared x-axis at the bottom of the grid.
			shared_yaxes : bool
				Assign shared y axes.
				If True, subplots in the same grid row have one common
				shared y-axis on the left-hand side of the grid.

		Shapes
			hline : float, list or dict
				Draws a horizontal line at the
				indicated y position(s)
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			vline : float, list or dict
				Draws a vertical line at the
				indicated x position(s)
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			hpsan : (y0,y1)
				Draws a horizontal rectangle at the
				indicated (y0,y1) positions.
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			vspan : (x0,x1)
				Draws a vertical rectangle at the
				indicated (x0,x1) positions.
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			shapes : dict or list(dict)
				List of dictionaries with the
				specifications of a given shape.
				See help(cufflinks.tools.get_shape)
				for more information

		Axis Ranges
			xrange : [lower_bound,upper_bound]
				Sets the range for the x axis
			yrange : [lower_bound,upper_bound]
				Sets the range for the y axis
			zrange : [lower_bound,upper_bound]
				Sets the range for the z axis

		Explicit Layout Updates
			layout_update : dict
				The layout will be modified with all
				the explicit values stated in the
				dictionary.
				It will not apply if layout is passed
				as parameter.

		Range Selector
			rangeselector : dict
				Defines a rangeselector object
				see help(cf.tools.get_range_selector) for more information
				Example:
					{'steps':['1y','2 months','5 weeks','ytd','2mtd'],
					 'axis':'xaxis', 'bgcolor' : ('blue',.3),
					 'x': 0.2 , 'y' : 0.9}

		Range Slider
			rangeslider : bool or dict
				Defines if a rangeslider is displayed
				If bool:
					True : Makes it visible
				if dict:
					Rangeslider object
				Example:
					{'bgcolor':('blue',.3),'autorange':True}

		Annotations
			fontcolor : str
				Text color for annotations
			fontsize : int
				Text size for annotations
			textangle : int
				Text angle
			See https://plot.ly/python/reference/#layout-annotations
			for a complete list of valid parameters.

		Exports
			display_image : bool
				If True then the image if displayed after being saved
				** only valid if asImage=True
			scale : integer
				Increase the resolution of the image by `scale` amount
				Only valid when asImage=True
	"""

	# Valid Kwargs
	valid_kwargs = ['color','opacity','column','columns','labels','text','world_readable','colorbar']
	BUBBLE_KWARGS = ['abs_size']
	TRACE_KWARGS = ['hoverinfo','connectgaps']
	HEATMAP_SURFACE_KWARGS = ['center_scale','zmin','zmax']
	PIE_KWARGS=['sort','pull','hole','textposition','textinfo','linecolor','linewidth','textcolor']
	OHLC_KWARGS=['up_color','down_color','open','high','low','close','volume','name','decreasing','increasing']
	SUBPLOT_KWARGS=['horizontal_spacing', 'vertical_spacing',
					'specs', 'insets','start_cell','shared_xaxes','shared_yaxes','subplot_titles','shared_xaxis','shared_yaxis']
	GEO_KWARGS=['locationmode','locationsrc','geo','lon','lat']
	ERROR_KWARGS=['error_trace','error_values_minus','error_color','error_thickness',
					'error_width','error_opacity']
	EXPORT_KWARGS=['display_image','scale']
	FF_DISTPLOT=["group_labels", "bin_size", "curve_type", "rug_text", "show_hist", "show_curve", "show_rug"]
	FF_VIOLIN=["data_header","group_header","show_rug","sort"]
	kwargs_list = [tools.__LAYOUT_KWARGS,BUBBLE_KWARGS,TRACE_KWARGS,
				   OHLC_KWARGS,PIE_KWARGS,HEATMAP_SURFACE_KWARGS,SUBPLOT_KWARGS,GEO_KWARGS,ERROR_KWARGS,EXPORT_KWARGS,
				   FF_DISTPLOT,FF_VIOLIN]
	[valid_kwargs.extend(_) for _ in kwargs_list]

	dict_modifiers_keys = ['line']
	dict_modifiers={}

	for k in dict_modifiers_keys:
		dict_modifiers[k]=kwargs_from_keyword(kwargs,{},k,True)

	for key in list(kwargs.keys()):
		if key not in valid_kwargs:
			raise Exception("Invalid keyword : '{0}'".format(key))

	# Setting default values
	if not colors:
		colors=kwargs['color'] if 'color' in kwargs else colors
	if isinstance(colors,str):
		colors=[colors]
	opacity=kwargs['opacity'] if 'opacity' in kwargs else 0.8
	if not dimensions:
		dimensions=auth.get_config_file()['dimensions']

	# Get values from config theme
	if theme is None:
		theme = auth.get_config_file()['theme']
	theme_config=tools.getTheme(theme)
	if colorscale is None:
		config_colorscale=auth.get_config_file()['colorscale']
		if config_colorscale in ('dflt',None):
			colorscale=theme_config['colorscale'] if 'colorscale' in theme_config else 'original'
		else:
			colorscale=config_colorscale
	if width is None:
		if kind != 'pie':
			width=theme_config['linewidth'] if 'linewidth' in theme_config else 2
	if margin is None:
		margin=auth.get_config_file().get('margin',None)

	# In case column was used instead of keys
	if 'column' in kwargs:
		keys=[kwargs['column']] if isinstance(kwargs['column'],str) else kwargs['column']
	if 'columns' in kwargs:
		keys=[kwargs['columns']] if isinstance(kwargs['columns'],str) else kwargs['columns']
	kind='line' if kind=='lines' else kind

	# Figure generators
	def get_marker(marker={}):
		if 'line' in dict_modifiers:
			if 'color' not in dict_modifiers['line']:
				if 'linecolor' in kwargs:
					linecolor=kwargs.get('linecolor')
				else:
					if 'linecolor' in tools.getTheme(theme=theme):
						linecolor=normalize(tools.getTheme(theme=theme)['linecolor'])
					else:
						linecolor=tools.getLayout(theme=theme)['xaxis']['titlefont']['color']
				dict_modifiers['line']['color']=linecolor
			dict_modifiers['line']=tools.updateColors(dict_modifiers['line'])
			marker['line']=deep_update(marker['line'],dict_modifiers['line'])
		return marker

	# We assume we are good citizens
	validate=True

	if not layout:
		l_kwargs=dict([(k,kwargs[k]) for k in tools.__LAYOUT_KWARGS if k in kwargs])
		if annotations:
			ann_kwargs=check_kwargs(kwargs,tools.__ANN_KWARGS,clean_origin=True)
			annotations=tools.get_annotations(self.copy(),annotations,kind=kind,theme=theme,**ann_kwargs)

		layout=tools.getLayout(kind=kind,theme=theme,xTitle=xTitle,yTitle=yTitle,zTitle=zTitle,title=title,barmode=barmode,
								bargap=bargap,bargroupgap=bargroupgap,annotations=annotations,gridcolor=gridcolor,
							   dimensions=dimensions,
								zerolinecolor=zerolinecolor,margin=margin,is3d='3d' in kind,**l_kwargs)
	elif isinstance(layout, Layout):
		layout = layout.to_plotly_json()

	if not data:
		if categories and kind not in ('violin'):
			data=[]
			if 'bar' in kind:
				df=self.copy()
				df=df.set_index(categories)
				fig=df.figure(kind=kind,colors=colors,colorscale=colorscale,fill=fill,width=width,sortbars=sortbars,opacity=opacity,
						asDates=asDates,mode=mode,symbol=symbol,size=size,text=text,barmode=barmode,orientation=orientation)
				data=fig['data']
			else:
				_keys=pd.unique(self[categories])
				colors=get_colors(colors,colorscale,_keys)
				mode='markers' if not mode else mode
				for _ in _keys:
					__=self[self[categories]==_].copy()
					if text:
						_text=__[text] if asFrame else __[text].values
					_x=__[x] if asFrame else __[x].values
					_y=__[y] if asFrame else __[y].values
					if z:
						_z=__[z] if asFrame else __[z].values
					if 'bubble' in kind:
						rg=__[size].values
						rgo=self[size].values
						if not kwargs.get('abs_size',False):
							if len(rgo)>1:
								_size=[int(100*(float(i)-rgo.min( ))/(rgo.max()-rgo.min()))+12 for i in rg]
							else:
								_size=[12] if len(rgo) else []
						else:
							_size=rgo
					else:
						_size=size
					_data=Scatter3d(x=_x,y=_y,mode=mode,name=_,
								marker=dict(color=colors[_],symbol=symbol,size=_size,opacity=opacity,
												line=dict(width=width)),textfont=tools.getLayout(theme=theme)['xaxis']['titlefont'])
					if '3d' in kind:
						_data=Scatter3d(x=_x,y=_y,z=_z,mode=mode,name=_,
								marker=dict(color=colors[_],symbol=symbol,size=_size,opacity=opacity,
												line=dict(width=width)),textfont=tools.getLayout(theme=theme)['xaxis']['titlefont'])
					else:
						#see error 168
						if type(_x)==pd.np.ndarray:
							if '[ns]' in _x.dtype.str:
								_x=_x.astype(str)
						if type(_y)==pd.np.ndarray:
							if '[ns]' in _y.dtype.str:
								_y=_y.astype(str)

						_data=Scatter(x=_x,y=_y,mode=mode,name=_,
								marker=dict(color=colors[_],symbol=symbol,size=_size,opacity=opacity,
												line=dict(width=width)),textfont=tools.getLayout(theme=theme)['xaxis']['titlefont'])
					if text:
						_data.update(text=_text)
					data.append(_data)
		else:
			if kind in ('scatter','spread','ratio','bar','barh','area','line'):
				df=self.copy()
				if type(df)==pd.core.series.Series:
					df=pd.DataFrame({df.name:df})
				if x:
					df=df.set_index(x)
				if y and secondary_y:
					if isinstance(secondary_y, str):
						df=df[[y, secondary_y]]
					else:
						df=df[[y] + secondary_y]
				elif y:
					df=df[y]
				if kind=='area':
					df=df.transpose().fillna(0).cumsum().transpose()
				mode='lines' if not mode else mode
				if text:
					if not isinstance(text,list):
						text=self[text].values
				data=df.to_iplot(colors=colors,colorscale=colorscale,kind=kind,interpolation=interpolation,fill=fill,width=width,dash=dash,sortbars=sortbars,keys=keys,
						bestfit=bestfit,bestfit_colors=bestfit_colors,mean=mean,mean_colors=mean_colors,asDates=asDates,mode=mode,symbol=symbol,size=size,
						text=text,**kwargs)
				trace_kw=check_kwargs(kwargs,TRACE_KWARGS)
				for trace in data:
					trace.update(**trace_kw)

				if kind in ('spread','ratio'):
						if kind=='spread':
							trace=self.apply(lambda x:x[0]-x[1],axis=1)
							positive=trace.apply(lambda x:x if x>=0 else pd.np.nan)
							negative=trace.apply(lambda x:x if x<0 else pd.np.nan)
							trace=pd.DataFrame({'positive':positive,'negative':negative})
							trace=trace.to_iplot(colors={'positive':'green','negative':'red'},width=0.5)
						else:
							trace=self.apply(lambda x:x[0]*1.0/x[1],axis=1).to_iplot(colors=['green'],width=1)
						for t in trace:
							t.update({'xaxis':'x2','yaxis':'y2','fill':'tozeroy',
											'name':kind.capitalize(),'connectgaps':False,'showlegend':False})
						data.append(trace[0])
						if kind=='spread':
							data.append(trace[1])
						layout['yaxis'].update({'domain':[.3,1]})
						layout['yaxis2']=copy.deepcopy(layout['yaxis'])
						layout['xaxis2']=copy.deepcopy(layout['xaxis'])
						layout['yaxis2'].update(domain=[0,.25],title=kind.capitalize())
						layout['xaxis2'].update(anchor='y2',showticklabels=False)
						layout['hovermode']='x'
				if 'bar' in kind:
					if 'stack' in barmode:
						layout['legend'].update(traceorder='normal')
					orientation = 'h' if kind=='barh' else orientation
					for trace in data:
						trace.update(orientation=orientation)
						if orientation=='h':
							trace['x'],trace['y']=trace['y'],trace['x']

			elif kind=='bubble':
				mode='markers' if 'markers' not in mode else mode
				x=self[x].values.tolist()
				y=self[y].values.tolist()
				z=size if size else z
				rg=self[z].values
				if not kwargs.get('abs_size',False):
					if len(rg) > 1:
						z=[int(100*(float(_)-rg.min())/(rg.max()-rg.min()))+12 for _ in rg]
					else:
						z=[12] if len(rg) else []
				else:
					z=rg
				text=kwargs['labels'] if 'labels' in kwargs else text
				labels=self[text].values.tolist() if text else ''
				clrs=colors if colors else get_scales(colorscale)
				clrs=[clrs] if not isinstance(clrs,list) else clrs
				clrs=[clrs[0]]*len(x) if len(clrs)==1 else clrs
				marker=dict(color=clrs,size=z,symbol=symbol,
								line=dict(width=width))
				trace=Scatter(x=x,y=y,marker=marker,mode='markers',text=labels)
				data=[trace]
			elif kind in ('box','histogram','hist'):
				if isinstance(self,pd.core.series.Series):
					df=pd.DataFrame({self.name:self})
				else:
					df=self.copy()
				data=[]
				clrs=get_colors(colors,colorscale,df.columns)
				if 'hist' in kind:
					barmode = 'overlay' if barmode=='' else	 barmode
					layout.update(barmode=barmode)
				columns=keys if keys else df.columns
				for _ in columns:
					if kind=='box':
						__=Box(y=df[_].values.tolist(),marker=dict(color=clrs[_]),name=_,
								line=dict(width=width),boxpoints=boxpoints)
						# 114 - Horizontal Box
						__['orientation']=orientation
						if orientation=='h':
							__['x'],__['y']=__['y'],__['x']

					else:
						__=dict(x=df[_].values.tolist(),name=_,
								marker=dict(color=clrs[_], line=dict(width=width)),
								orientation=orientation,
								opacity=kwargs['opacity'] if 'opacity' in kwargs else .8, histfunc=histfunc,
								histnorm=histnorm)

						__['marker']=get_marker(__['marker'])

						if orientation=='h':
							__['y']=__['x']
							del __['x']
						__ = Histogram(__)
						if bins:
							if type(bins) in (tuple,list):
								try:
									_bins={'start':bins[0],'end':bins[1],'size':bins[2]}
									if orientation=='h':
										__.update(ybins=_bins,autobiny=False)
									else:
										__.update(xbins=_bins,autobinx=False)
								except:
									print("Invalid format for bins generation")
							else:
								if orientation=='h':
									__.update(nbinsy=bins)
								else:
									__.update(nbinsx=bins)
					data.append(__)

			elif kind in ('heatmap','surface'):
				if x:
					x=self[x].values.tolist()
				else:
					if self.index.__class__.__name__ in ('PeriodIndex','DatetimeIndex'):
						x=self.index.format()
					else:
						x=self.index.values.tolist()
				y=self[y].values.tolist() if y else self.columns.values.tolist()
				z=self[z].values.tolist() if z else self.values.transpose()
				scale=get_scales('rdbu') if not colorscale else get_scales(colorscale)
				colorscale=[[float(_)/(len(scale)-1),scale[_]] for _ in range(len(scale))]
				center_scale = kwargs.get('center_scale',None)

				if is_list(z):
					zmin=min(z)
					zmax=max(z)
				else:
					zmin=z.min()
					zmax=z.max()

				if center_scale is not None:
					if center_scale<=zmin+(zmax-zmin)/2:
						zmin=center_scale*2-zmax
					else:
						zmax=center_scale*2-zmin
				zmin=kwargs.get('zmin',zmin)
				zmax=kwargs.get('zmax',zmax)
				if kind=='heatmap':
					data=[Heatmap(z=z,x=x,y=y,zmin=zmin,zmax=zmax,colorscale=colorscale)]
				else:
					data=[Surface(z=z,x=x,y=y,colorscale=colorscale)]

			elif kind in ('scatter3d','bubble3d'):
				data=[]
				keys=self[text].values if text else list(range(len(self)))
				colors=get_colors(colors,colorscale,keys,asList=True)
				mode='markers' if 'markers' not in mode else mode
				df=self.copy()
				df['index']=keys
				if kind=='bubble3d':
					rg=self[size].values
					if not kwargs.get('abs_size',False):
						size=[int(100*(float(_)-rg.min())/(rg.max()-rg.min()))+12 for _ in rg]
					else:
						size=rg
				else:
					size=[size for _ in range(len(keys))]

				_data=Scatter3d(x=df[x].values.tolist(),y=df[y].values.tolist(),z=df[z].values.tolist(),mode=mode,text=keys,
									marker=dict(color=colors,symbol=symbol,size=size,opacity=.8))
				if text:
					_data.update(text=keys)
				data.append(_data)

			elif kind=='pie':
				if not labels:
					raise CufflinksError('Missing: labels')
				if not values:
					raise CufflinksError('Missing: values')
				labels=self[labels].values.tolist()
				values=self[values].values.tolist()
				marker=dict(colors=get_colors(colors,colorscale,labels,asList=True))
				marker.update(line=dict(color=kwargs.pop('linecolor',None),width=kwargs.pop('linewidth',width)))
				pie=dict(values=values,labels=labels,name='',marker=marker)

				kw=check_kwargs(kwargs,PIE_KWARGS)
				kw['textfont']={'color':kw.pop('textcolor',None)}
				pie.update(kw)
				data=[]
				del layout['xaxis']
				del layout['yaxis']
				data.append(Pie(pie))
				validate=False

			elif kind in ('old_candle','old_ohlc'):
				d=ta._ohlc_dict(self)
				if len(list(d.keys()))!=4:
					raise Exception("OHLC type of charts require an Open, High, Low and Close column")
				ohlc_kwargs=check_kwargs(kwargs,OHLC_KWARGS)
				if kind=='old_candle':
					fig=tools.get_candle(self,theme=theme,layout=layout,**ohlc_kwargs)
				else:
					fig=tools.get_ohlc(self,theme=theme,layout=layout,**ohlc_kwargs)
				if bestfit:
					df=self.copy()
					bf=_to_iplot(self[d['close']],bestfit=True,bestfit_colors=bestfit_colors,asTimestamp=True)
					fig['data'].append(bf[1])
				data=fig['data']
				layout=fig['layout']

			elif kind in ('candle','ohlc','candlestick'):
				kind='candlestick' if kind=='candle' else kind
				kw=check_kwargs(kwargs,OHLC_KWARGS)
				d=ta._ohlc_dict(self,validate='ohlc',**kw)
				_d=dict(type=kind,
							open=self[d['open']].values.tolist(),
							high=self[d['high']].values.tolist(),
							low=self[d['low']].values.tolist(),
							close=self[d['close']].values.tolist())
				if isinstance(self.index,pd.core.indexes.datetimes.DatetimeIndex):
					_d['x']=self.index.astype('str')
				else:
					_d['x']=self.index
				if 'name' in kw:
					_d['name']=kw['name']

				showlegend=False
				if 'showlegend' in kwargs:
					showlegend=kwargs['showlegend']
				else:
					if 'legend' in kwargs:
						if type(kwargs['legend'])==bool:
							showlegend=kwargs['legend']
				# https://github.com/santosjorge/cufflinks/issues/113
				# _d['increasing']=dict(line=dict(color=kw['up_color']) if 'up_color' in kw else dict(),showlegend=showlegend)
				# _d['decreasing']=dict(line=dict(color=kw['down_color']) if 'down_color' in kw else dict(),showlegend=showlegend)
				_d['increasing']=dict(line=dict(color=kw['up_color']) if 'up_color' in kw else dict())
				_d['decreasing']=dict(line=dict(color=kw['down_color']) if 'down_color' in kw else dict())
				for k in ('increasing','decreasing'):
					if k in kw:
						_d[k]=deep_update(_d[k],kw[k])

				_d['showlegend']=showlegend
				_d['yaxis']='y2'
				data=[_d]

			elif kind in ('choropleth','scattergeo'):
				kw=check_kwargs(kwargs,GEO_KWARGS)
				if kind=='choropleth':
					if not all([x!=None for x in (locations,z)]):
						raise Exception("Choropleth maps require a 'location' and 'z' column names specified")
					geo_data={'type':'choropleth','locations':self[locations],'z':self[z],
							'colorscale':get_colorscale(colorscale),
							'marker':get_marker(dict(line=dict(width=width)))}
				elif kind=='scattergeo':
					if not all([x!=None for x in (lon,lat)]):
						raise Exception("Scattergeo maps require a 'lon' and 'lat' column names specified")
					geo_data={'type':'scattergeo','lat':self[lat],'lon':self[lon],
							'marker':get_marker(dict(line=dict(width=width),
												symbol=symbol,colorscale=get_colorscale(colorscale),
												color=self[z] if z else None))}
				if 'colorbar' in kwargs:
					geo_data['colorbar']=kwargs['colorbar']
				geo_data.update(kw)
				if text:
					geo_data.update(text=self[text])
				validate=False
				data=[]
				data.append(geo_data)

			# Figure Factory
			elif kind in ('distplot'):
				colors=get_colors(colors,colorscale,self.keys(),asList=True)
				hist_data=self.transpose().values
				kw=check_kwargs(kwargs,FF_DISTPLOT)
				group_labels=kw.pop('group_labels',self.columns)
				if histnorm:
					kw['histnorm']=histnorm
				fig=ff.create_distplot(hist_data=hist_data,group_labels=group_labels,
										 colors=colors,**kw)
				data=fig.data
				layout=tools.merge_dict(layout,fig.layout)
			elif kind in ('violin'):
				df=pd.DataFrame(self) if type(self)==pd.core.series.Series else self.copy()
				kw=check_kwargs(kwargs,FF_VIOLIN)
				kw['rugplot']=kw.pop('show_rug',True)
				kw['title']=title
				if 'group_header' not in kw:
					kw['group_header']=categories if categories else None
				categories=kw.get('group_header')
				colors=get_colors(colors,colorscale,df[categories].value_counts().values if categories else df.keys(),asList=True)
				kw['colors']=colors
				if categories:
					for _ in range(2,df[categories].value_counts().size+1):
						layout['xaxis{0}'.format(_)]=layout['xaxis'].copy()
					if categories not in df:
						raise CufflinksError('Column "{0}" not found in DataFrame'.format(categories))
					elif len(df.columns)==1:
						raise CufflinksError('When "categories" are specified, two columns are expected. \n Only one column was found.')
					elif len(df.columns)==2:
						cols=list(df.columns)
						cols.remove(categories)
						kw['data_header']=cols[0]
					else:
						if 'data_header' not in kw:
							raise CufflinksError('data_header must be the column name with the desired numeric data for the violin plot.')
				else:
					if len(df.columns)==1:
						kw['data_header']=df.columns[0]
					elif len(df.columns)>1:
						if 'data_header' not in kw:
							raise CufflinksError('data_header must be the column name with the desired numeric data for the violin plot.')
				fig=ff.create_violin(df,**kw).to_dict()
				data=fig['data']
				layout=tools.merge_dict(layout,fig['layout'])

## Sharing Values
	if all(['world_readable' in kwargs,sharing is None]):
		sharing=kwargs['world_readable']
	if isinstance(sharing,bool):
			if sharing:
				sharing='public'
			else:
				sharing='private'
	if sharing is None:
		sharing=auth.get_config_file()['sharing']

	if not filename:
		if title:
			filename=title
		else:
			filename='Plotly Playground {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S"))

## Figure defintion
	figure={}
	figure['data']=data
	figure['layout']=layout

## Check secondary axis
	if secondary_y:
		figure=tools._set_axis(figure,secondary_y,side='right')
		if secondary_y_title:
			figure.layout.yaxis2.title=secondary_y_title

## Error Bars
	if kind in ('scatter','bar','barh','lines','line'):
		if any([error_x,error_y]):
			def set_error(axis,**kwargs):
				return tools.set_errors(figure,axis=axis,**kwargs)
			kw=check_kwargs(kwargs,ERROR_KWARGS)
			kw=dict([(k.replace('error_',''),v) for k,v in list(kw.items())])
			kw['type']=error_type
			if error_x:
				kw['values']=error_x
				figure=set_error('x',**kw)
			if error_y:
				kw['values']=error_y
				figure=set_error('y',**kw)
## Subplots

	if subplots:
		fig=tools.strip_figures(figure)
		kw=check_kwargs(kwargs,SUBPLOT_KWARGS)
		for _ in ['x','y']:
			if 'shared_{0}axes'.format(_) not in kw:
				kw['shared_{0}axes'.format(_)]=kw.pop('shared_{0}axis'.format(_),False)
		if 'subplot_titles' in kwargs:
			if kwargs['subplot_titles']==True:
				kw['subplot_titles']=[d['name'] for d in data]
			else:
				kw['subplot_titles']=kwargs['subplot_titles']
		figure=tools.subplots(fig,shape,base_layout=layout,theme=theme,**kw)

## Exports
	validate = False if 'shapes' in layout else validate

	if asFigure:
		return Figure(figure)
	else:
		return iplot(figure,validate=validate,sharing=sharing,filename=filename,
			 online=online,asImage=asImage,asUrl=asUrl,asPlot=asPlot,
			 dimensions=dimensions,display_image=kwargs.get('display_image',True))


Instruction:
Write a Python 3 function for
returning a dict with an item per key

Response:
def get_items_as_list(items,keys,items_names='styles'):
	"""
	Returns a dict with an item per key

	Parameters:
	-----------
		items : string, list or dict
			Items (ie line styles)
		keys: list
			List of keys
		items_names : string
			Name of items
	"""
	if type(items)!=dict:
		if type(items)==list:
			if len(items)!=len(keys):
				raise Exception('List of {0} is not the same length as keys'.format(items_names))
			else:
				items=dict(zip(keys,items))
		else:
			items=dict(zip(keys,[items]*len(keys)))
	return items


Instruction:
Make a summary of the following Python 3 code
def _scatter_matrix(self,theme=None,bins=10,color='grey',size=2, asFigure=False, **iplot_kwargs):
	sm=tools.scatter_matrix(self,theme=theme,bins=bins,color=color,size=size)
	if asFigure:
		return sm
	else:
		return iplot(sm,**iplot_kwargs)

Response:
Displays a matrix with scatter plot for each pair of
	Series in the DataFrame.


Instruction:
Given the following Python 3 function, write the documentation
def iplot(figure,validate=True,sharing=None,filename='',
			 online=None,asImage=False,asUrl=False,asPlot=False,
			 dimensions=None,display_image=True,**kwargs):
	"""
	Plots a figure in IPython, creates an HTML or generates an Image

	figure : figure
		Plotly figure to be charted
	validate : bool
		If True then all values are validated before
		it is charted
	sharing : string
		Sets the sharing level permission
			public - anyone can see this chart
			private - only you can see this chart
			secret - only people with the link can see the chart
	filename : string
		Name to be used to save the file in the server, or as an image
	online : bool
		If True then the chart/image is rendered on the server
		even when running in offline mode.
	asImage : bool
			If True it returns an Image (png)
			In ONLINE mode:
				Image file is saved in the working directory
					Accepts:
						filename
						dimensions
						scale
						display_image
			In OFFLINE mode:
				Image file is downloaded (downloads folder) and a
				regular plotly chart is displayed in Jupyter
					Accepts:
						filename
						dimensions
	asUrl : bool
		If True the chart url/path is returned. No chart is displayed.
			If Online : the URL is returned
			If Offline : the local path is returned
	asPlot : bool
		If True the chart opens in browser
	dimensions : tuple(int,int)
		Dimensions for image
			(width,height)
	display_image : bool
		If true, then the image is displayed after it has been saved
		Requires Jupyter Notebook
		Only valid when asImage=True

	Other Kwargs
	============
		legend : bool
			If False then the legend will not be shown
		scale : integer
			Increase the resolution of the image by `scale` amount
			Only valid when asImage=True
	"""
	valid_kwargs=['world_readable','legend','scale']

	for key in list(kwargs.keys()):
		if key not in valid_kwargs:
			raise Exception("Invalid keyword : '{0}'".format(key))

	if 'legend' in kwargs:
		if 'layout' in figure:
			figure['layout'].update(showlegend=kwargs['legend'])

	## Sharing Values
	if all(['world_readable' in kwargs,sharing is None]):
		sharing=kwargs['world_readable']
	if isinstance(sharing,bool):
			if sharing:
				sharing='public'
			else:
				sharing='private'
	if sharing is None:
		sharing=auth.get_config_file()['sharing']

	## Filename Handling
	if not filename:
		# if not figure.get('layout', None):
		# 	figure['layout'] = {}
		try:
			filename=figure['layout']['title']
		except:
			filename='Plotly Playground {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S"))

	## Dimensions
	if not dimensions:
		dimensions=(800,500) if not auth.get_config_file()['dimensions'] else auth.get_config_file()['dimensions']

	## Offline Links
	show_link = auth.get_config_file()['offline_show_link']
	link_text = auth.get_config_file()['offline_link_text']
	config = auth.get_config_file()['offline_config']

	## Remove validation if shapes are present
	if 'layout' in figure:
		validate = False if 'shapes' in figure['layout'] else validate

	## asURL
	auto_open=True
	if asUrl:
		asPlot=True
		auto_open=False

	## Exports
	if asImage:
		if offline.is_offline() and not online:
			return offline.py_offline.iplot(figure,validate=validate, filename=filename, show_link=show_link,link_text=link_text,
				image='png', image_width=dimensions[0], image_height=dimensions[1], config=config)
		else:
			try:
				py.image.save_as(figure,filename='img/'+filename,format='png',
					width=dimensions[0],height=dimensions[1],scale=kwargs.get('scale',None))
				path='img/'+filename+'.png'
			except:
				py.image.save_as(figure,filename=filename,format='png',
					width=dimensions[0],height=dimensions[1],scale=kwargs.get('scale',None))
				path=filename+'.png'
			if display_image:
				return display(Image(path))
			else:
				print('Image saved : {0}'.format(path))
				return None

	## asPlot and asUrl
	if asPlot:
		filename+='.html'
		if offline.is_offline() and not online:
			return offline.py_offline.plot(figure, filename=filename, validate=validate,
								show_link=show_link, link_text=link_text, auto_open=auto_open, config=config)
		else:
			return py.plot(figure, sharing=sharing, filename=filename, validate=validate,
							auto_open=auto_open)

	## iplot
	if offline.is_offline() and not online:
		return offline.py_offline.iplot(figure, validate=validate, filename=filename, show_link=show_link, link_text=link_text, config=config)
	else:
		return py.iplot(figure,validate=validate,sharing=sharing,
						filename=filename)

Response: This function is used to plot a figure in IPython notebook.


Instruction:
Here you have a function in Python 3, explain what it does
def _ta_plot(self,study,periods=14,column=None,include=True,str='{name}({period})',detail=False,
			 theme=None,sharing=None,filename='',asFigure=False,**iplot_kwargs):
	"""
	Generates a Technical Study Chart

	Parameters:
	-----------
			study : string
				Technical Study to be charted
					sma - 'Simple Moving Average'
					rsi - 'R Strength Indicator'
			periods : int
				Number of periods
			column : string
				Name of the column on which the
				study will be done
			include : bool
				Indicates if the input column(s)
				should be included in the chart
			str : string
				Label factory for studies
				The following wildcards can be used:
					{name} : Name of the column
					{study} : Name of the study
					{period} : Period used
				Examples:
					'study: {study} - period: {period}'
			detail : bool
				If True the supporting data/calculations
				are included in the chart
			study_colors : string or [string]
				Colors to be used for the studies

		Study Specific Parameters
		-------------------------
		RSI
			rsi_upper : int (0,100]
				Level for the upper rsi band
				default : 70
			rsi_lower : int (0,100]
				Level for the lower rsi band
				default : 30
		CCI
			cci_upper : int
				Level for the upper cci band
				default : 100
			cci_lower : int
				Level for the lower cci band
				default : -100
		BOLL
			boll_std : int or float
				Number of standard deviations
		MACD
			fast_period : int
				Number of periods for the fast moving average
			slow_period : int
				Number of periods for the slow moving average
			signal_period : int
				Number of periods for the signal
		CORREL
			how : string
				Method for the correlation calculation
					values
					pct_cht
					diff

	"""

	if 'columns' in iplot_kwargs:
		column=iplot_kwargs.pop('columns')

	if 'period' in iplot_kwargs:
		periods=iplot_kwargs.pop('period')

	if 'world_readable' in iplot_kwargs:
		sharing=iplot_kwargs.pop('world_readable')

	if 'study_color' in iplot_kwargs:
		iplot_kwargs['study_colors']=iplot_kwargs.pop('study_color')

	if sharing is None:
			sharing = auth.get_config_file()['sharing']
	if isinstance(sharing,bool):
			if sharing:
				sharing='public'
			else:
				sharing='private'
	iplot_kwargs['sharing']=sharing
	if theme is None:
		theme = iplot_kwargs.pop('study_theme',auth.get_config_file()['theme'])

	if not filename:
		if 'title' in iplot_kwargs:
			filename=iplot_kwargs['title']
		else:
			filename='Plotly Playground {0}'.format(time.strftime("%Y-%m-%d %H:%M:%S"))

	def get_subplots(figures):
		shape=(len(figures),1)
		layout=tools.get_base_layout(figures)
		subplots=tools.subplots(figures,shape=shape,shared_xaxes=True,base_layout=layout)
		if len(figures)==2:
			subplots['layout']['yaxis']['domain']=[.27,1.0]
			subplots['layout']['yaxis2']['domain']=[0,.25]
		return subplots

	def get_study(df,func,iplot_kwargs,iplot_study_kwargs,str=None,include=False,column=None,inset=False):
		df=df.copy()
		if inset:
			if not column:
				if isinstance(df,pd.DataFrame):
					column=df.keys().tolist()
				else:
					df=pd.DataFrame(df)
					column=df.keys().tolist()
		if 'legend' in iplot_kwargs:
			iplot_study_kwargs['legend']=iplot_kwargs['legend']
		fig_0=df.figure(**iplot_kwargs)
		df_ta=func(df,column=column,include=False,str=str,**study_kwargs)
		kind=iplot_kwargs['kind'] if 'kind' in iplot_kwargs else ''
		iplot_study_kwargs['kind']='scatter'
		iplot_study_kwargs['colors']=iplot_study_kwargs.get('colors',['blue','green','red'] if study=='dmi' else 'blue')
		fig_1=df_ta.figure(theme=theme,**iplot_study_kwargs)
		if kind in ['candle','ohlc']:
				for i in fig_1['data']:
					i['x']=[pd.Timestamp(_) for _ in i['x']]
		if inset:
			figure=tools.merge_figures([fig_0,fig_1]) if include else fig_1
		else:
			figure=get_subplots([fig_0,fig_1]) if include else fig_1
		return figure

	study_kwargs={}
	iplot_study_kwargs={}

	study_kwargs=check_kwargs(iplot_kwargs,__TA_KWARGS,{},clean_origin=True)
	iplot_study_kwargs=kwargs_from_keyword(iplot_kwargs,{},'study')

	study_kwargs.update({'periods':periods})

	ta_func = eval('ta.{0}'.format(study))

	inset=study in ('sma','boll','ema','atr','ptps')
	figure=get_study(self,ta_func,iplot_kwargs,iplot_study_kwargs,include=include,
					 column=column,str=str,inset=inset)

	## Add Bands
	if study in ('rsi','cci'):
		bands= {'rsi':(30,70),
				'cci':(-100,100)}
		_upper=study_kwargs.get('{0}_upper'.format(study),bands[study][0])
		_lower=study_kwargs.get('{0}_lower'.format(study),bands[study][1])
		yref='y2' if include else 'y1'
		shapes=[tools.get_shape(y=i,yref=yref,color=j,dash='dash') for (i,j) in [(_lower,'green'),(_upper,'red')]]
		figure['layout']['shapes']=shapes

	# if study=='rsi':
	# 	rsi_upper=study_kwargs.get('rsi_upper',70)
	# 	rsi_lower=study_kwargs.get('rsi_lower',30)
	# 	yref='y2' if include else 'y1'
	# 	shapes=[tools.get_shape(y=i,yref=yref,color=j,dash='dash') for (i,j) in [(rsi_lower,'green'),(rsi_upper,'red')]]
	# 	figure['layout']['shapes']=shapes

	# if study=='cci':
	# 	cci_upper=study_kwargs.get('cci_upper',100)
	# 	cci_lower=study_kwargs.get('cci_lower',-100)
	# 	yref='y2' if include else 'y1'
	# 	shapes=[tools.get_shape(y=i,yref=yref,color=j,dash='dash') for (i,j) in [(cci_lower,'green'),(cci_upper,'red')]]
	# 	figure['layout']['shapes']=shapes

	## Exports

	if asFigure:
		return figure
	else:
		return iplot(figure,sharing=sharing,filename=filename)

Response: This function generates a TA chart for the given study and periods.


Instruction:
Can you generate the documentation for the following Python 3 function
def _fig_iplot(self,validate=True,sharing=None,filename='',
			 online=None,asImage=False,asUrl=False,asPlot=False,
			 dimensions=None,display_image=True,**kwargs):
	"""
	Plots a figure in IPython

	figure : figure
		Plotly figure to be charted
	validate : bool
		If True then all values are validated before
		it is charted
	sharing : string
		Sets the sharing level permission
			public - anyone can see this chart
			private - only you can see this chart
			secret - only people with the link can see the chart
	filename : string
		Name to be used to save the file in the server, or as an image
	online : bool
		If True then the chart is rendered on the server
		even when running in offline mode.
	asImage : bool
			If True it returns an Image (png)
			In ONLINE mode:
				Image file is saved in the working directory
					Accepts:
						filename
						dimensions
						scale
						display_image
			In OFFLINE mode:
				Image file is downloaded (downloads folder) and a
				regular plotly chart is displayed in Jupyter
					Accepts:
						filename
						dimensions
	asUrl : bool
		If True the chart url/path is returned. No chart is displayed.
			If Online : the URL is returned
			If Offline : the local path is returned
	asPlot : bool
		If True the chart opens in browser
	dimensions : tuple(int,int)
		Dimensions for image
			(width,height)
	display_image : bool
		If true, then the image is displayed after it has been saved
		Requires Jupyter Notebook
		onlh valide when asImage=True

	Other Kwargs
	============

		legend : bool
			If False then the legend will not be shown
	"""
	return iplot(self,validate=validate,sharing=sharing,filename=filename,
			 online=online,asImage=asImage,asUrl=asUrl,asPlot=asPlot,
			 dimensions=dimensions,display_image=display_image,**kwargs)

Response: Function that returns a figure in IPython notebook.


Instruction:
How would you implement a function in Python 3 that
ensures that all local files are set in a valid way.

Response:
def ensure_local_files():
	"""
	Ensure that filesystem is setup/filled out in a valid way
	"""
	if _file_permissions:
		if not os.path.isdir(AUTH_DIR):
			os.mkdir(AUTH_DIR)
		for fn in [CONFIG_FILE]:
			contents = load_json_dict(fn)
			for key, val in list(_FILE_CONTENT[fn].items()):
				if key not in contents:
					contents[key] = val
			contents_keys = list(contents.keys())
			for key in contents_keys:
				if key not in _FILE_CONTENT[fn]:
					del contents[key]
			save_json_dict(fn, contents)
	else:
		warnings.warn("Looks like you don't have 'read-write' permission to "
					  "your 'home' ('~') directory")


Instruction:
Implement a Python 3 function for
setting the config file for the current chart.

Response:
def set_config_file(sharing=None,theme=None,colorscale=None,offline=None,offline_connected=None,
					offline_url=None,offline_show_link=None,offline_link_text=None,
					offline_config=None,
					datagen_mode=None,**kwargs):
	"""
	Set the keyword-value pairs in `~/.config`.

	sharing : string
			Sets the sharing level permission
				public - anyone can see this chart
				private - only you can see this chart
				secret - only people with the link can see the chart
	theme : string
			Sets the default theme
			See cufflinks.getThemes() for available themes
	colorscale : string
			Sets the default colorscale
			See cufflinks.scales()
	offline : bool
			If true then the charts are rendered
			locally.
	offline_connected : bool
			If True, the plotly.js library will be loaded
			from an online CDN. If False, the plotly.js library will be loaded locally
			from the plotly python package
	offline_show_link : bool
			If true then the chart will show a link to
			plot.ly at the bottom right of the chart
	offline_link_text : string
			Text to display as link at the bottom
			right of the chart
	offline_config : dict
			Additional configuration options
			For the complete list of config options check out:
			https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js
	datagen_mode : string
			Mode in which the data is generated
			by the datagen module
				stocks : random stock names are used for the index
				abc : alphabet values are used for the index
	dimensions : tuple
			Sets the default (width,height) of the chart
	margin : dict or tuple
			Dictionary (l,r,b,t) or
			Tuple containing the left,
			right, bottom and top margins
	"""
	if not _file_permissions:
		raise Exception("You don't have proper file permissions "
									 "to run this function.")
	valid_kwargs=['world_readable','dimensions','margin','offline_config']
	for key in list(kwargs.keys()):
		if key not in valid_kwargs:
			raise Exception("Invalid keyword : '{0}'".format(key))
	if all(['world_readable' in kwargs,sharing is None]):
		sharing=kwargs['world_readable']
	if isinstance(sharing,bool):
			if sharing:
				sharing='public'
			else:
				sharing='private'
	config = get_config_file()
	if sharing is not None:
		config['sharing'] = sharing
	if theme:
		config['theme']=theme
	if colorscale:
		config['colorscale']=colorscale
	if offline_connected:
		config['offline_connected']=offline_connected
	if offline is not None:
		config['offline']=offline
		if offline:
			go_offline()
	if datagen_mode:
		config['datagen_mode']=datagen_mode
	if offline_url:
		config['offline_url']=offline_url
	if offline_show_link is not None:
		config['offline_show_link']=offline_show_link
	if offline_link_text:
		config['offline_link_text']=offline_link_text
	if offline_config:
		config['offline_config']=offline_config
	for _ in valid_kwargs:
		if _ in kwargs:
			config[_]=kwargs[_]
	save_json_dict(CONFIG_FILE, config)
	ensure_local_files()


Instruction:
Can you tell what is the following Python 3 function doing
def load_json_dict(filename, *args):
	data = {}
	if os.path.exists(filename):
		with open(filename, "r") as f:
			try:
				data = json.load(f)
				if not isinstance(data, dict):
					data = {}
			except:
				pass
		if args:
			return {key: data[key] for key in args if key in data}
	return data

Response: Checks if file exists. Returns {} if something fails. Returns {} if something fails.


Instruction:
Implement a Python 3 function for
returning a dictionary with the schema for a QuantFigure

Response:
def _get_schema(self):
		"""
		Returns a dictionary with the schema for a QuantFigure

		"""
		d={}
		layout_kwargs=dict((_,'') for _ in get_layout_kwargs())
		for _ in ('data','layout','theme','panels'):
			d[_]={}
			for __ in eval('__QUANT_FIGURE_{0}'.format(_.upper())):
				layout_kwargs.pop(__,None)
				d[_][__]=None
		d['layout'].update(annotations=dict(values=[],
											params=utils.make_dict_from_list(get_annotation_kwargs())))
		d['layout'].update(shapes=utils.make_dict_from_list(get_shapes_kwargs()))
		[layout_kwargs.pop(_,None) for _ in get_annotation_kwargs()+get_shapes_kwargs()]
		d['layout'].update(**layout_kwargs)
		return d


Instruction:
Here you have a function in Python 3, explain what it does
def _get_sliced(self,slice,df=None):

		df=self.df.copy() if df==None else df
		if type(slice) not in (list,tuple):
			raise Exception('Slice must be a tuple two values')
		if len(slice)!=2:
			raise Exception('Slice must be a tuple two values')
		a,b=slice
		a=None if a in ('',None) else utils.make_string(a)
		b=None if b in ('',None) else utils.make_string(b)
		return df.ix[a:b]

Response: Returns a sliced DataFrame


Instruction:
Can you tell what is the following Python 3 function doing
def _get_resampled(self,rule,how={'ohlc':'last','volume':'sum'},df=None,**kwargs):
		df=self.df.copy() if df is None else df
		if rule==None:
			return df
		else:
			if isinstance(how,dict):
				if 'ohlc' in how:
					v=how.pop('ohlc')
					for _ in ['open','high','low','close']:
						how[_]=v
				_how=how.copy()
				for _ in _how:
					if _ not in self._d:
						del how[_]
			return df.resample(rule=rule,**kwargs).apply(how)

Response: Returns a resampled DataFrame with the given rule


Instruction:
Make a summary of the following Python 3 code
def update(self,**kwargs):
		if 'columns' in kwargs:
			self._d=ta._ohlc_dict(self.df,columns=kwargs.pop('columns',None))
		schema=self._get_schema()
		annotations=kwargs.pop('annotations',None)

		if annotations:
			self.layout['annotations']['values']=utils.make_list(annotations)
		for k,v in list(kwargs.items()):
			try:
				utils.dict_update(self.__dict__,k,v,schema)
			except:
				self.kwargs.update({k:v})

Response: Updates the values for a QuantFigure


Instruction:
Can you create a Python 3 function that
deletes the values for a QuantFigure

Response:
def delete(self,*args):
		"""
		Deletes the values for a QuantFigure
		The key-values are automatically deleted from the correct
		section of the QuantFigure
		"""
		if args:
			args=args[0] if utils.is_list(args[0]) else args
			path=utils.dict_path(self.__dict__)
			for _ in args:
				if _ in self.__dict__.keys():
					raise Exception('"{0}" cannot be deleted'.format(_))

			for a in args:
				try:
					if a in ('shapes'):
						self.layout[a].clear()
					elif a=='annotations':
						self.layout['annotations']={'values':[],'params':{}}
					else:
						del reduce(dict.get, path[a],self.__dict__)[a]
				except:
					raise Exception('Key: {0} not found'.format(a))


Instruction:
Write a Python 3 script to
return the panel domains for each axis.

Response:
def _panel_domains(self,n=2,min_panel_size=.15,spacing=0.08,top_margin=1,bottom_margin=0):
		"""

		Returns the panel domains for each axis

		"""
		d={}
		for _ in range(n+1,1,-1):
			lower=round(bottom_margin+(min_panel_size+spacing)*(n+1-_),2)
			d['yaxis{0}'.format(_)]=dict(domain=(lower,lower+min_panel_size))
		top=d['yaxis2']['domain']
		d['yaxis2']['domain']=(top[0],top_margin)
		return d


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_trendline(self,date0=None,date1=None,on=None,kind='trend',to_strfmt='%Y-%m-%d',from_strfmt='%d%b%y',**kwargs):
		ann_values=copy.deepcopy(get_annotation_kwargs())
		ann_values.extend(['x','y'])
		ann_kwargs=utils.check_kwargs(kwargs,ann_values,{},clean_origin=True)
		def position(d0,d1):
			return d0+(d1-d0)/2

		date0=kwargs.pop('date',date0)
		date0=date_tools.stringToString(date0,from_strfmt,to_strfmt) if '-' not in date0 else date0

		if kind=='trend':
			date1=date_tools.stringToString(date1,from_strfmt,to_strfmt) if '-' not in date1 else date1
			on='close' if not on else on
			df=pd.DataFrame(self.df[self._d[on]])
			y0=kwargs.get('y0',df.ix[date0].values[0])
			y1=kwargs.get('y1',df.ix[date1].values[0])

		if kind in ('support','resistance'):
			mode=kwargs.pop('mode','starttoend')
			if not on:
				on='low' if kind=='support' else 'high'
			df=pd.DataFrame(self.df[self._d[on]])
			y0=kwargs.get('y0',df.ix[date0].values[0])
			y1=kwargs.get('y1',y0)
			if mode=='starttoend':
				date0=df.index[0]
				date1=df.index[-1]
			elif mode=='toend':
				date1=df.index[-1]
			elif mode=='fromstart':
				date1=date0
				date0=df.index[0]

		if isinstance(date0,pd.Timestamp):
			date0=date_tools.dateToString(date0,to_strfmt)
		if isinstance(date1,pd.Timestamp):
			date1=date_tools.dateToString(date1,to_strfmt)
		d={'x0':date0,'x1':date1,'y0':y0,'y1':y1}
		d.update(**kwargs)
		shape=tools.get_shape(**d)

		if ann_kwargs.get('text',False):
			ann_kwargs['x']=ann_kwargs.get('x',date_tools.dateToString(position(date_tools.stringToDate(date0,to_strfmt),date_tools.stringToDate(date1,to_strfmt)),to_strfmt))
			ann_kwargs['y']=ann_kwargs.get('y',position(shape['y0'],shape['y1']))
		else:
			ann_kwargs={}
		return {'shape':shape,'annotation':ann_kwargs}

Response: Returns a trendline object


Instruction:
Can you tell what is the following Python 3 function doing
def add_trendline(self,date0,date1,on='close',text=None,**kwargs):
		d={'kind':'trend','date0':date0,'date1':date1,'on':on,'text':text}
		d.update(**kwargs)
		self.trendlines.append(d)

Response: Adds a trendline to the QuantFigure.


Instruction:
Write a Python 3 script for
adding a support line to the QuantFigure object.

Response:
def add_support(self,date,on='low',mode='starttoend',text=None,**kwargs):
		"""
		Adds a support line to the QuantFigure

		Parameters:
			date0 : string
				The support line will be drawn at the 'y' level
				value that corresponds to this date.
			on : string
				Indicate the data series in which the
				support line should be based.
					'close'
					'high'
					'low'
					'open'
			mode : string
				Defines how the support/resistance will
				be drawn
					'starttoened' : (x0,x1)
					'fromstart' : (x0,date)
					'toend' : (date,x1)
			text : string
				If passed, then an annotation will be added
				to the support line (at mid point)

		kwargs:
			from_strfmt : string
				Defines the date formating in which
				date0 and date1 are stated.
				default: '%d%b%y'
			to_strfmt : string
				Defines the date formatting
				to which it should be converted.
				This should match the same format as the timeseries index.
				default : '%Y-%m-%d'
		"""
		d={'kind':'support','date':date,'mode':mode,'on':on,'text':text}
		d.update(**kwargs)
		self.trendlines.append(d)


Instruction:
Can you write a function in Python 3 where it
adds an annotation to the QuantFigure.

Response:
def add_annotations(self,annotations,**kwargs):
		"""
		Add an annotation to the QuantFigure.

		Parameters:
			annotations : dict or list(dict,)
				Annotations can be on the form form of
					{'date' : 'text'}
					and the text will automatically be placed at the
					right level on the chart
				or
					A Plotly fully defined annotation

		kwargs :
			fontcolor : str
				Text color for annotations
			fontsize : int
				Text size for annotations
			textangle : int
				Textt angle
			See https://plot.ly/python/reference/#layout-annotations
			for a complete list of valid parameters.

		"""
		ann_kwargs=utils.check_kwargs(kwargs,get_annotation_kwargs(),{},clean_origin=True)
		if type(annotations)==list:
			self.layout['annotations']['values'].extend(annotations)
		else:
			self.layout['annotations']['values'].append(annotations)
		if ann_kwargs:
			self.layout['annotations']['params'].update(**ann_kwargs)


Instruction:
Create a Python 3 function to
add a shape to the QuantFigure.

Response:
def add_shapes(self,**kwargs):
		"""
		Add a shape to the QuantFigure.

		kwargs :
			hline : int, list or dict
				Draws a horizontal line at the
				indicated y position(s)
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			vline : int, list or dict
				Draws a vertical line at the
				indicated x position(s)
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			hspan : (y0,y1)
				Draws a horizontal rectangle at the
				indicated (y0,y1) positions.
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			vspan : (x0,x1)
				Draws a vertical rectangle at the
				indicated (x0,x1) positions.
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			shapes : dict or list(dict)
				List of dictionaries with the
				specifications of a given shape.
				See help(cufflinks.tools.get_shape)
				for more information

		"""
		kwargs=utils.check_kwargs(kwargs,get_shapes_kwargs(),{},clean_origin=True)
		for k,v in list(kwargs.items()):
			if k in self.layout['shapes']:
				if utils.is_list(v):
					self.layout['shapes'][k].extend(v)
				else:
					self.layout['shapes'][k].append(v)
			else:
				self.layout['shapes'][k]=utils.make_list(v)


Instruction:
How would you explain what the following Python 3 function does
def _add_study(self,study):
		str='{study} {name}({period})' if study['params'].get('str',None)==None else study['params']['str']
		study['params']['str']=str

		if not study['name']:
			study['name']=ta.get_column_name(study['kind'].upper(),study=study['kind'],
												str=str,
												period=study['params'].get('periods',None),
												column=study['params'].get('column',None))

		restore=study['display'].pop('restore',False)

		if restore:
			_=self.studies.pop(study['kind'],None)

		if study['kind'] in self.studies:
			try:
				id='{0} ({1})'.format(study['kind'],study['params']['periods'])
			except:
				id='{0} ({1})'.format(study['kind'],'(2)')
		else:
			id=study['kind']

		_id=id
		n=1
		while id in self.studies:
			id='{0} ({1})'.format(_id,n)
			n+=1
		self.studies[id]=study

Response:
Adds a study to QuantFigure. studyies
	if


Instruction:
How would you explain what the following Python 3 function does
def add_volume(self,colorchange=True,column=None,name='',str='{name}',**kwargs):
		if not column:
			column=self._d['volume']
		up_color=kwargs.pop('up_color',self.theme['up_color'])
		down_color=kwargs.pop('down_color',self.theme['down_color'])
		study={'kind':'volume',
			   'name':name,
			   'params':{'colorchange':colorchange,'base':'close','column':column,
						 'str':None},
			  'display':utils.merge_dict({'up_color':up_color,'down_color':down_color},kwargs)}
		self._add_study(study)

Response: Add a volume study to QuantFigure. studies


Instruction:
How would you code a function in Python 3 to
add a MACD study to QuantFigure. studies

Response:
def add_macd(self,fast_period=12,slow_period=26,signal_period=9,column=None,
				 name='',str=None,**kwargs):
		"""
		Add Moving Average Convergence Divergence (MACD) study to QuantFigure.studies

		Parameters:
			fast_period : int
				MACD Fast Period
			slow_period : int
				MACD Slow Period
			signal_period : int
				MACD Signal Period
			column :string
				Defines the data column name that contains the
				data over which the study will be applied.
				Default: 'close'
			name : string
				Name given to the study
			str : string
				Label factory for studies
				The following wildcards can be used:
					{name} : Name of the column
					{study} : Name of the study
					{period} : Period used
				Examples:
					'study: {study} - period: {period}'
		kwargs:
			legendgroup : bool
				If true, all legend items are grouped into a
				single one
			All formatting values available on iplot()
		"""

		if not column:
			column=self._d['close']
		study={'kind':'macd',
			   'name':name,
			   'params':{'fast_period':fast_period,'slow_period':slow_period,
						 'signal_period':signal_period,'column':column,
						 'str':str},
			  'display':utils.merge_dict({'legendgroup':False,'colors':['blue','red']},kwargs)}
		study['params']['periods']='[{0},{1},{2}]'.format(fast_period,slow_period,signal_period)
		self._add_study(study)


Instruction:
Create a Python 3 function for
adding a simple moving average study to QuantFigure. studies

Response:
def add_sma(self,periods=20,column=None,name='',
					str=None,**kwargs):
		"""
		Add Simple Moving Average (SMA) study to QuantFigure.studies

		Parameters:
			periods : int or list(int)
				Number of periods
			column :string
				Defines the data column name that contains the
				data over which the study will be applied.
				Default: 'close'
			name : string
				Name given to the study
			str : string
				Label factory for studies
				The following wildcards can be used:
					{name} : Name of the column
					{study} : Name of the study
					{period} : Period used
				Examples:
					'study: {study} - period: {period}'
		kwargs:
			legendgroup : bool
				If true, all legend items are grouped into a
				single one
			All formatting values available on iplot()
		"""
		if not column:
			column=self._d['close']
		study={'kind':'sma',
			   'name':name,
			   'params':{'periods':periods,'column':column,
						 'str':str},
			  'display':utils.merge_dict({'legendgroup':False},kwargs)}
		self._add_study(study)


Instruction:
Here you have a function in Python 3, explain what it does
def add_rsi(self,periods=20,rsi_upper=70,rsi_lower=30,showbands=True,column=None,
						   name='',str=None,**kwargs):
		"""
		Add Relative Strength Indicator (RSI) study to QuantFigure.studies

		Parameters:
			periods : int or list(int)
				Number of periods
			rsi_upper : int
				bounds [0,100]
				Upper (overbought) level
			rsi_lower : int
				bounds [0,100]
				Lower (oversold) level
			showbands : boolean
				If True, then the rsi_upper and
				rsi_lower levels are displayed
			column :string
				Defines the data column name that contains the
				data over which the study will be applied.
				Default: 'close'
			name : string
				Name given to the study
			str : string
				Label factory for studies
				The following wildcards can be used:
					{name} : Name of the column
					{study} : Name of the study
					{period} : Period used
				Examples:
					'study: {study} - period: {period}'
		kwargs:
			legendgroup : bool
				If true, all legend items are grouped into a
				single one
			All formatting values available on iplot()
		"""
		if not column:
			column=self._d['close']
		str=str if str else '{name}({column},{period})'

		study={'kind':'rsi',
			   'name':name,
			   'params':{'periods':periods,'column':column,
						 'str':str},
			  'display':utils.merge_dict({'legendgroup':True,'rsi_upper':rsi_upper,
						 'rsi_lower':rsi_lower,'showbands':showbands},kwargs)}
		self._add_study(study)

Response: Add Relative Strength Indicator to QuantFigure. studies


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_bollinger_bands(self,periods=20,boll_std=2,fill=True,column=None,name='',
						   str='{name}({column},{period})',**kwargs):
		"""
		Add Bollinger Bands (BOLL) study to QuantFigure.studies

		Parameters:
			periods : int or list(int)
				Number of periods
			boll_std : int
				Number of standard deviations for
				the bollinger upper and lower bands
			fill : boolean
				If True, then the innner area of the
				bands will filled
			column :string
				Defines the data column name that contains the
				data over which the study will be applied.
				Default: 'close'
			name : string
				Name given to the study
			str : string
				Label factory for studies
				The following wildcards can be used:
					{name} : Name of the column
					{study} : Name of the study
					{period} : Period used
				Examples:
					'study: {study} - period: {period}'
		kwargs:
			legendgroup : bool
				If true, all legend items are grouped into a
				single one
			fillcolor : string
				Color to be used for the fill color.
				Example:
					'rgba(62, 111, 176, .4)'
			All formatting values available on iplot()
		"""
		if not column:
			column=self._d['close']
		study={'kind':'boll',
			   'name':name,
			   'params':{'periods':periods,'boll_std':boll_std,'column':column,
						'str':str},
			  'display':utils.merge_dict({'legendgroup':True,'fill':fill},kwargs)}
		self._add_study(study)

Response: Adds a Bollinger Bands to the QuantFigure. studies


Instruction:
Make a summary of the following Python 3 code
def add_cci(self,periods=14,cci_upper=100,cci_lower=-100,
			    showbands=True,str=None,name='',**kwargs):
		"""
		Commodity Channel Indicator study to QuantFigure.studies

		Parameters:
			periods : int or list(int)
				Number of periods
			cci_upper : int
				Upper bands level
				default : 100
			cci_lower : int
				Lower band level
				default : -100
			showbands : boolean
				If True, then the cci_upper and
				cci_lower levels are displayed
			name : string
				Name given to the study
			str : string
				Label factory for studies
				The following wildcards can be used:
					{name} : Name of the column
					{study} : Name of the study
					{period} : Period used
				Examples:
					'study: {study} - period: {period}'
		kwargs:
			legendgroup : bool
				If true, all legend items are grouped into a
				single one
			All formatting values available on iplot()
		"""
		study={'kind':'cci',
			   'name':name,
			   'params':{'periods':periods,'high':self._d['high'],'low':self._d['low'],'close':self._d['close'],
						 'str':str},
			  'display':utils.merge_dict({'legendgroup':True,'cci_upper':cci_upper,
						 'cci_lower':cci_lower,'showbands':showbands},kwargs)}
		self._add_study(study)

Response: Add a new CCI column to QuantFigure. studies


Instruction:
Explain what the following Python 3 code does
def add_ptps(self,periods=14,af=0.2,initial='long',str=None,name='',**kwargs):
		study={'kind':'ptps',
			   'name':name,
			   'params':{'periods':periods,'high':self._d['high'],'low':self._d['low'],'af':af,'initial':initial,
						 'str':str},
			  'display':utils.merge_dict({'legendgroup':False},kwargs)}
		self._add_study(study)

Response: This method adds a Parabolic SAR study to QuantFigure. studies


Instruction:
Can you create a Python 3 function that
adds Average True Range (ATR) study to QuantFigure.studies Parameters: periods : int or list(int) Number of periods name : string Name given to the study str : string Label factory for studies The following wildcards can be used: {name} : Name of the column {study} : Name of the study {period} : Period used Examples: 'study: {study} - period: {period}' kwargs: legendgroup : bool If true, all legend items are grouped into a single one All formatting values available on iplot()

Response:
def add_atr(self,periods=14,str=None,name='',**kwargs):
		"""
		Add Average True Range (ATR) study to QuantFigure.studies

		Parameters:
			periods : int or list(int)
				Number of periods
			name : string
				Name given to the study
			str : string
				Label factory for studies
				The following wildcards can be used:
					{name} : Name of the column
					{study} : Name of the study
					{period} : Period used
				Examples:
					'study: {study} - period: {period}'
		kwargs:
			legendgroup : bool
				If true, all legend items are grouped into a
				single one
			All formatting values available on iplot()
		"""
		study={'kind':'atr',
			   'name':name,
			   'params':{'periods':periods,'high':self._d['high'],'low':self._d['low'],'close':self._d['close'],
						 'str':str},
			  'display':utils.merge_dict({'legendgroup':False},kwargs)}
		self._add_study(study)


Instruction:
Given the following Python 3 function, write the documentation
def go_offline(connected=None):
    from .auth import get_config_file
    if connected is None:
        try:
            connected=True if get_config_file()['offline_connected'] is None else get_config_file()['offline_connected']
        except:
            connected=True
    if run_from_ipython():
        try:
            py_offline.init_notebook_mode(connected)
        except TypeError:
            #For older versions of plotly
            py_offline.init_notebook_mode()
        py_offline.__PLOTLY_OFFLINE_INITIALIZED=True

Response:
connected : bool
        If True, the plotly.js library will be loaded
        from an online CDN. If False, the plotly.js library will be loaded locally
        from the plotly python package


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _screen(self,include=True,**kwargs):
	df=self.copy()
	for k,v in list(kwargs.items()):
		v=[v] if type(v)!=list else v
		if include:
			df=df[df[k].str.contains('|'.join(v),flags=re.IGNORECASE).fillna(False)]
		else:
			df=df[df[k].str.contains('|'.join(v),flags=re.IGNORECASE).fillna(False)==False]
	return df

Response: Returns a DataFrame that contains the given strings in the screen.


Instruction:
How would you code a function in Python 3 to
return a series with the bestfit values.

Response:
def bestfit(self):
	"""
	Returns a series with the bestfit values.

	Example:
		Series.bestfit()

	Returns: series
		The returned series contains a parameter
		called 'formula' which includes the string representation
		of the bestfit line.
	"""
	# statsmodel cannot be included on requirements.txt
	# see https://github.com/scikit-learn/scikit-learn/issues/4164
	# which shares the same issue as statsmodel
	try:
		import statsmodels.api as sm
	except:
		raise Exception("statsmodels is required: " \
						"please run " \
						"pip install statsmodels" )

	x=pd.Series(list(range(1,len(self)+1)),index=self.index)
	x=sm.add_constant(x)
	model=sm.OLS(self,x)
	fit=model.fit()
	vals=fit.params.values
	best_fit=fit.fittedvalues
	# the below methods have been deprecated in Pandas
	# model=pd.ols(x=x,y=self,intercept=True)
	# best_fit=model.y_fitted
	best_fit.formula='%.2f*x+%.2f' % (vals[0],vals[1])
	return best_fit


Instruction:
Can you implement a function in Python 3 that
returns a normalized series or DataFrame

Response:
def normalize(self,asOf=None,multiplier=100):
	"""
	Returns a normalized series or DataFrame

	Example:
		Series.normalize()

	Returns: series of DataFrame

	Parameters:
	-----------
		asOf : string
			Date format
			'2015-02-29'
		multiplier : int
			Factor by which the results will be adjusted
	"""
	if not asOf:
		x0=self.ix[0]
	else:
		x0=self.ix[asOf]
	return self/x0*multiplier


Instruction:
Can you generate the documentation for the following Python 3 function
def pp(el,preString=''):
	tab=' '*4
	if isinstance(el,dict):
		keys=list(el.keys())
		keys.sort()
		for key in keys:
			val=el[key]
			if isinstance(val,dict) or isinstance(val,list):
				print('%s%s :' % (preString,key))
				pp(val,preString+tab)
			else:
				print('%s%s  =  %s' % (preString,key,val))

	elif isinstance(el,list):
		print(preString+tab+'[')
		preString+=tab
		for _ in el:
			if isinstance(_,dict):
				print (preString+tab+'{')
				pp(_,preString+tab*2)
				print(preString+tab+'}')
			elif isinstance(_,list):
				print(preString+tab+'[')
				pp(_,preString+tab)
				print(preString+tab+']')
			else:
				pp(_,preString+tab)
			#print preString+'      '+str('-')*10
		print(preString	+']')
	else:
		print(preString+str(el))

Response: prettyprint a concatenated dictionary


Instruction:
Can you write a function in Python 3 where it
returns a dictionay indexed by values { value_k : key_k }

Response:
def inverseDict(d):
	"""
	Returns a dictionay indexed by values {value_k:key_k}
	Parameters:
	-----------
		d : dictionary
	"""
	dt={}
	for k,v in list(d.items()):
		if type(v) in (list,tuple):
			for i in v:
				dt[i]=k
		else:
			dt[v]=k
	return dt


Instruction:
Can you create a Python 3 function that
looks for keys of the format keyword_value. And return a dictionary with {keyword:value} format Parameters: ----------- from_kwargs : dict Original dictionary to_kwargs : dict Dictionary where the items will be appended keyword : string Keyword to look for in the orginal dictionary clean_origin : bool If True then the k,v pairs from the original dictionary are deleted

Response:
def kwargs_from_keyword(from_kwargs,to_kwargs,keyword,clean_origin=True):
	"""
	Looks for keys of the format keyword_value.
	And return a dictionary with {keyword:value} format

	Parameters:
	-----------
		from_kwargs : dict
			Original dictionary
		to_kwargs : dict
			Dictionary where the items will be appended
		keyword : string
			Keyword to look for in the orginal dictionary
		clean_origin : bool
			If True then the k,v pairs from the original
			dictionary are deleted
	"""
	for k in list(from_kwargs.keys()):
		if '{0}_'.format(keyword) in k:
			to_kwargs[k.replace('{0}_'.format(keyword),'')]=from_kwargs[k]
			if clean_origin:
				del from_kwargs[k]
	return to_kwargs


Instruction:
Here you have a function in Python 3, explain what it does
def deep_update(d,d_update):
	for k,v in list(d_update.items()):
		if isinstance(v,dict):
			if k in d:
				deep_update(d[k],v)
			else:
				d[k]=v
		elif isinstance(d,list):
			d.append({k:v})
		else:
			d[k]=v
	return d

Response: Updates the values of a given dictionary d with the values of d_update.


Instruction:
Implement a Python 3 function for
reading a google sheet from the specified URL.

Response:
def read_google(self,url,**kwargs):
	"""
	Reads a google sheet
	"""
	if url[-1]!='/':
		url+='/'
	return self.read_csv(url+'export?gid=0&format=csv',**kwargs)


Instruction:
Implement a Python 3 function for
returning a string that represents a date n numbers of days from today.

Response:
def getDateFromToday(delta,strfmt='%Y%m%d'):
	""" Returns a string that represents a date n numbers of days from today.
	Parameters:
	-----------
		delta : int
			number of days
		strfmt : string
			format in which the date will be represented
	"""
	return (dt.date.today() + dt.timedelta(delta)).strftime(strfmt)


Instruction:
How would you code a function in Python 3 to
return a dictionary with the actual column names that correspond to each of the OHLCV values.

Response:
def _ohlc_dict(df_or_figure,open='',high='',low='',close='',volume='',
			   validate='',**kwargs):
	"""
	Returns a dictionary with the actual column names that
	correspond to each of the OHLCV values.

	df_or_figure :  DataFrame or Figure
	open : string
		Column name to be used for OPEN values
	high : string
		Column name to be used for HIGH values
	low : string
		Column name to be used for LOW values
	close : string
		Column name to be used for CLOSE values
	volume : string
		Column name to be used for VOLUME values
	validate : string
		Validates that the stated column exists
		Example:
			validate='ohv' | Will ensure Open, High
							 and close values exist.
	"""
	c_dir={}
	ohlcv=['open','high','low','close','volume']
	if type(df_or_figure)==pd.DataFrame:
		cnames=df_or_figure.columns
	elif type(df_or_figure)==Figure or type(df_or_figure) == dict:
		cnames=df_or_figure.axis['ref'].keys()
	elif type(df_or_figure)==pd.Series:
		cnames=[df_or_figure.name]
	c_min=dict([(v.lower(),v) for v in cnames])
	for _ in ohlcv:
		if _ in c_min.keys():
			c_dir[_]=c_min[_]
		else:
			for c in cnames:
				if _ in c.lower():
					c_dir[_]=c

	if open:
		c_dir['open']=open
	if high:
		c_dir['high']=high
	if low:
		c_dir['low']=low
	if close:
		c_dir['close']=close
	if volume:
		c_dir['volume']=volume

	for v in list(c_dir.values()):
		if v not in cnames:
			raise StudyError('{0} is not a valid column name'.format(v))

	if validate:
			errs=[]
			val=validate.lower()
			s_names=dict([(_[0],_) for _ in ohlcv])
			cols=[_[0] for _ in c_dir.keys()]
			for _ in val:
				if _ not in cols:
					errs.append(s_names[_])
			if errs:
				raise StudyError('Missing Columns: {0}'.format(', '.join(errs)))

	return c_dir


Instruction:
Can you write a function in Python 3 where it
returns a DataFrame with the data from the scattergeo. csv file

Response:
def scattergeo():
	"""
	Returns
	"""
	path=os.path.join(os.path.dirname(__file__), '../data/scattergeo.csv')
	df=pd.read_csv(path)
	del df['Unnamed: 0']
	df['text'] = df['airport'] + ' ' + df['city'] + ', ' + df['state'] + ' ' + 'Arrivals: ' + df['cnt'].astype(str)
	df=df.rename(columns={'cnt':'z','long':'lon'})
	return df


Instruction:
Can you tell what is the following Python 3 function doing
def choropleth():
	path=os.path.join(os.path.dirname(__file__), '../data/choropleth.csv')
	df=pd.read_csv(path)
	del df['Unnamed: 0']
	df['z']=[np.random.randint(0,100) for _ in range(len(df))]
	return df

Response: Returns a DataFrame with the choropleth data.


Instruction:
Create a Python 3 function for
returning a DataFrame with the required format for a pie plot Parameters :

Response:
def pie(n_labels=5,mode=None):
	"""
	Returns a DataFrame with the required format for
	a pie plot

	Parameters:
	-----------
		n_labels : int
			Number of labels
		mode : string
			Format for each item
				'abc' for alphabet columns
				'stocks' for random stock names
	"""
	return pd.DataFrame({'values':np.random.randint(1,100,n_labels),
						 'labels':getName(n_labels,mode=mode)})


Instruction:
How would you implement a function in Python 3 that
returns a DataFrame with the required format for a scatter plot

Response:
def scatter(n_categories=5,n=10,prefix='category',mode=None):
	"""
	Returns a DataFrame with the required format for
	a scatter plot

	Parameters:
	-----------
		n_categories : int
			Number of categories
		n : int
			Number of points for each category
		prefix : string
			Name for each category
		mode : string
			Format for each item
				'abc' for alphabet columns
				'stocks' for random stock names
	"""
	categories=[]
	for i in range(n_categories):
		categories.extend([prefix+str(i+1)]*n)
	return pd.DataFrame({'x':np.random.randn(n*n_categories),
						 'y':np.random.randn(n*n_categories),
						 'text':getName(n*n_categories,mode=mode),
						 'categories':categories})


Instruction:
Write a Python 3 script for
returning a DataFrame with the required format for a heatmap plot

Response:
def heatmap(n_x=5,n_y=10):
	"""
	Returns a DataFrame with the required format for
	a heatmap plot

	Parameters:
	-----------
		n_x : int
			Number of x categories
		n_y : int
			Number of y categories
	"""
	x=['x_'+str(_) for _ in range(n_x)]
	y=['y_'+str(_) for _ in range(n_y)]
	return pd.DataFrame(surface(n_x-1,n_y-1).values,index=x,columns=y)


Instruction:
Create a Python 3 function for
returning a DataFrame with the required format for a scatter plot

Response:
def lines(n_traces=5,n=100,columns=None,dateIndex=True,mode=None):
	"""
	Returns a DataFrame with the required format for
	a scatter (lines) plot

	Parameters:
	-----------
		n_traces : int
			Number of traces
		n : int
			Number of points for each trace
		columns : [str]
			List of column names
		dateIndex : bool
			If True it will return a datetime index
			if False it will return a enumerated index
		mode : string
			Format for each item
				'abc' for alphabet columns
				'stocks' for random stock names
	"""
	index=pd.date_range('1/1/15',periods=n) if dateIndex else list(range(n))
	df=pd.DataFrame(np.random.randn(n,n_traces),index=index,
		columns=getName(n_traces,columns=columns,mode=mode))
	return df.cumsum()


Instruction:
Make a summary of the following Python 3 code
def bars(n=3,n_categories=3,prefix='category',columns=None,mode='abc'):
	categories=[]
	if not columns:
		columns=getName(n,mode=mode)
	for i in range(n_categories):
		categories.extend([prefix+str(i+1)])
	data=dict([(x,np.random.randint(1,100,n_categories)) for x in columns])
	return pd.DataFrame(data,index=categories)

Response:
Returns a DataFrame with the required format for
	a bar plot


Instruction:
How would you code a function in Python 3 to
return a DataFrame with the required format for a candlestick or ohlc plot

Response:
def ohlc(n=100):
	"""
	Returns a DataFrame with the required format for
	a candlestick or ohlc plot
	df[['open','high','low','close']]

	Parameters:
	-----------
		n : int
			Number of ohlc points

	"""
	index=pd.date_range('1/1/15',periods=n*288,freq='5min',tz='utc')
	data=np.random.randn(n*288)
	data[0]=np.array([100])
	df=pd.DataFrame(data,index=index,
		columns=['a'])
	df=df.cumsum()
	df=df.resample('1d').ohlc()
	df.index=df.index.date
	df.index=pd.to_datetime(df.index)
	return df['a']


Instruction:
How would you explain what the following Python 3 function does
def ohlcv(n=100):
	df=ohlc()
	df['volume']=[np.random.randint(1000,10000) for _ in range(len(df))]
	return df

Response:
Returns a DataFrame with the required format for
	a candlestick or ohlc plot


Instruction:
Make a summary of the following Python 3 code
def box(n_traces=5,n=100,mode=None):
	df=pd.DataFrame([np.random.chisquare(np.random.randint(2,10),n_traces) for _ in range(n)],
		columns=getName(n_traces,mode=mode))
	return df

Response:
Returns a DataFrame with the required format for
	a box plot
	n


Instruction:
Make a summary of the following Python 3 code
def histogram(n_traces=1,n=500,dispersion=2,mode=None):
	df=pd.DataFrame(np.transpose([np.random.randn(n)+np.random.randint(-1*dispersion,dispersion) for _ in range(n_traces)]),
		columns=getName(n_traces,mode=mode))
	return df

Response:
Returns a DataFrame with the required format for
	a histogram plot


Instruction:
Can you tell what is the following Python 3 function doing
def distplot(n_traces=1,n=500,dispersion=3,mode=None):
	return histogram(n_traces,n,dispersion,mode)

Response:
Returns a DataFrame with the required format for
	a distribution plot


Instruction:
Make a summary of the following Python 3 code
def violin(n=500,dispersion=3,categories=True,n_categories=5):
	df = histogram(1,n,dispersion,'abc')
	df=df.rename(columns={'a':'data'})
	if categories:
		df['categories']=['category_{0}'.format(np.random.randint(n_categories)) for _ in range(n)]
	return df

Response: Returns a DataFrame with the required format for INDRA points in the distribution plot.


Instruction:
Create a Python 3 function for
returning a DataFrame with the required format for a surface plot

Response:
def surface(n_x=20,n_y=20):
	"""
	Returns a DataFrame with the required format for
	a surface plot

	Parameters:
	-----------
		n_x : int
			Number of points along the X axis
		n_y : int
			Number of points along the Y axis
	"""
	x=[float(np.random.randint(0,100))]
	for i in range(n_x):
		x.append(x[:1][0]+np.random.randn()*np.random.randint(1,10))
	df=pd.DataFrame(x)
	for i in range(n_y):
		df[i+1]=df[i].map(lambda x:x+np.random.randn()*np.random.randint(1,10))
	return df


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sinwave(n=4,inc=.25):
	x=np.arange(-n,n,inc)
	y=np.arange(-n,n,inc)
	X,Y=np.meshgrid(x,y)
	R = np.sqrt(X**2 + Y**2)
	Z = np.sin(R)/(.5*R)
	return pd.DataFrame(Z,index=x,columns=y)

Response:
Returns a DataFrame with the required format for
	a surface ( sine wave ) plot.


Instruction:
Write a Python 3 function that can
return a theme definition.

Response:
def getTheme(theme=None):
	"""
	Returns a theme definition.

	To see the colors translated (hex) use
	cufflinks.getLayout(theme) instead.
	"""
	if not theme:
		theme = auth.get_config_file()['theme']

	if theme in THEMES:
		return updateColors(copy.deepcopy(THEMES[theme]))
	else:
		raise Exception("Invalid Theme: {0}".format(theme))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getLayout(kind=None,theme=None,title='',xTitle='',yTitle='',zTitle='',barmode='',bargap=None,bargroupgap=None,
			  margin=None, dimensions=None, width=None, height=None,
			  annotations=None,is3d=False,**kwargs):
	"""
	Generates a plotly Layout

	Parameters:
	-----------
		theme : string
			Layout Theme
				solar
				pearl
				white
		title : string
			Chart Title
		xTitle : string
			X Axis Title
		yTitle : string
			Y Axis Title
		zTitle : string
			Z Axis Title
			Applicable only for 3d charts
		barmode : string
			Mode when displaying bars
				group
				stack
				overlay
		bargap : float
			Sets the gap between bars
				[0,1)
			Applicabe for bar and histogram plots
		bargroupgap : float
			Set the gap between groups
				[0,1)
			Applicabe for bar and histogram plots
		gridcolor : string
				grid color
		zerolinecolor : string
				zero line color
		margin : dict or tuple
				Dictionary (l,r,b,t) or
				Tuple containing the left,
				right, bottom and top margins
		dimensions : tuple
			Dimensions of figure
		annotations : dict or list
			Dictionary of annotations
				{x_point : text}
			or
			List of Plotly Annotations
		is3d : bool
			Indicates if the layout is for a 3D chart

		Other Kwargs
		============

		Shapes
			hline : int, list or dict
				Draws a horizontal line at the
				indicated y position(s)
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			vline : int, list or dict
				Draws a vertical line at the
				indicated x position(s)
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			hspan : (y0,y1)
				Draws a horizontal rectangle at the
				indicated (y0,y1) positions.
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			vspan : (x0,x1)
				Draws a vertical rectangle at the
				indicated (x0,x1) positions.
				Extra parameters can be passed in
				the form of a dictionary (see shapes)
			shapes : dict or list(dict)
				List of dictionaries with the
				specifications of a given shape.
				See help(cufflinks.tools.get_shape)
				for more information

		Axis Ranges
			xrange : [lower_bound,upper_bound]
				Sets the range for the x axis
			yrange : [lower_bound,upper_bound]
				Sets the range for the y axis
			zrange : [lower_bound,upper_bound]
				Sets the range for the z axis

		Explicit Layout Updates
			layout_update : dict
				The layout will be modified with all
				the explicit values stated in the
				dictionary

		Range Selector
			rangeselector : dict
				Defines a rangeselector object
				see help(cf.tools.get_range_selector) for more information
				Example:
					{'steps':['1y','2 months','5 weeks','ytd','2mtd'],
					 'axis':'xaxis', 'bgcolor' : ('blue',.3),
					 'x': 0.2 , 'y' : 0.9}

		Range Slider
			rangeslider : bool or dict
				Defines if a rangeslider is displayed
				If bool:
					True : Makes it visible
				if dict:
					Rangeslider object
				Example:
					{'bgcolor':('blue',.3),'autorange':True}

		Annotations
			fontcolor : str
				Text color for annotations
			fontsize : int
				Text size for annotations
			textangle : int
				Textt angle
			See https://plot.ly/python/reference/#layout-annotations
			for a complete list of valid parameters.
	"""

	for key in list(kwargs.keys()):
		if key not in __LAYOUT_KWARGS:
			raise Exception("Invalid keyword : '{0}'".format(key))

	if not theme:
		theme = auth.get_config_file()['theme']

	theme_data = getTheme(theme)
	layout=theme_data['layout']
	layout['xaxis'].update({'title':xTitle})
	layout['yaxis'].update({'title':yTitle})

	fontfamily=kwargs.pop('fontfamily',None)
	if fontfamily:
		deep_update(layout,{'font':{'family':fontfamily}})

	if barmode:
		layout.update({'barmode':barmode})
	if bargroupgap:
		layout.update({'bargroupgap':bargroupgap})
	if bargap:
		layout.update(bargap=bargap)
	if title:
		layout.update({'title':title})
	if annotations:
		layout.update({'annotations':annotations})

	def update_axis(layout,axis='xy',**vals):
		for _x in axis:
			for k,v in list(vals.items()):
				if v==None:
					vals.pop(k)
			for k in layout:
				if '{0}{1}'.format(_x,'axis') in k:
					layout[k].update(**vals)
		return layout

	axis_kwargs=check_kwargs(kwargs,__LAYOUT_AXIS,{},True)
	xaxis_kwargs=kwargs_from_keyword(kwargs,{},'xaxis',True)
	yaxis_kwargs=kwargs_from_keyword(kwargs,{},'yaxis',True)

	for _x,_vals in (('xy',axis_kwargs),('x',xaxis_kwargs),('y',yaxis_kwargs)):
		layout=update_axis(layout,_x,**_vals)

	if margin:
		if isinstance(margin,dict):
			margin=margin
		else:
			margin=dict(list(zip(('l','r','b','t'),margin)))
		layout.update(margin=margin)

	if dimensions:
		layout.update(width=dimensions[0])
		layout.update(height=dimensions[1])

	if height:
		layout.update(height=height)
	if width:
		layout.update(width=width)
	if is3d:
		if '3d' in theme_data:
			layout=deep_update(layout,theme_data['3d'])
		zaxis=layout['xaxis'].copy()
		zaxis.update(title=zTitle)
		scene=dict(xaxis=layout['xaxis'].copy(),yaxis=layout['yaxis'].copy(),zaxis=zaxis)
		layout.update(scene=scene)
		del layout['xaxis']
		del layout['yaxis']

	## Axis Range
	for r in ['x','y','z']:
		if '{0}range'.format(r) in kwargs:
			if is3d:
				layout['scene']['{0}axis'.format(r)].update(range=kwargs['{0}range'.format(r)])
			else:
				layout['{0}axis'.format(r)].update(range=kwargs['{0}range'.format(r)])

	# Need to update this for an add_axis approach.
	if kind in ('candlestick','ohlc','candle'):
		layout['yaxis2']=layout['yaxis'].copy()
		layout['yaxis'].update(showticklabels=False)

	## Kwargs

	if 'legend' in kwargs:
		if type(kwargs['legend'])==bool:
			layout['showlegend']=kwargs['legend']
		elif type(kwargs['legend'])==str:
			if kwargs['legend']=='top':
				layout['legend'].update(orientation='h',yanchor='bottom',x=.3,y=.95)
			elif kwargs['legend']=='bottom':
				layout['legend'].update(orientation='h',yanchor='bottom',x=.3,y=-0.5)
			layout['showlegend']=True
		else:
			layout['legend']=kwargs['legend']
			layout['showlegend']=True

	if 'showlegend' in kwargs:
		layout['showlegend']=kwargs['showlegend']

	# Logarithmic Axis
	for _ in ['x','y','z']:
		if 'log{0}'.format(_) in kwargs:
			if is3d:
				if kwargs['log{0}'.format(_)]:
					layout['scene']['{0}axis'.format(_)]['type']='log'
			else:
				if kwargs['log{0}'.format(_)]:
					layout['{0}axis'.format(_)]['type']='log'

	# Shapes

	if any(k in kwargs for k in ['vline','hline','shapes','hspan','vspan']):
		shapes=[]

		def get_shapes(xline):

			orientation=xline[0]
			xline=kwargs[xline]
			if isinstance(xline,list):
				for x_i in xline:
					if isinstance(x_i,dict):
						x_i['kind']='line'
						shapes.append(get_shape(**x_i))
					else:
						if orientation=='h':
							shapes.append(get_shape(kind='line',y=x_i))
						else:
							shapes.append(get_shape(kind='line',x=x_i))
			elif isinstance(xline,dict):
				shapes.append(get_shape(**xline))
			else:
				if orientation=='h':
					shapes.append(get_shape(kind='line',y=xline))
				else:
					shapes.append(get_shape(kind='line',x=xline))

		def get_span(xspan):
			orientation=xspan[0]
			xspan=kwargs[xspan]
			if isinstance(xspan,list):
				for x_i in xspan:
					if isinstance(x_i,dict):
						x_i['kind']='rect'
						shapes.append(get_shape(**x_i))
					else:
						v0,v1=x_i
						if orientation=='h':
							shapes.append(get_shape(kind='rect',y0=v0,y1=v1,fill=True,opacity=.5))
						else:
							shapes.append(get_shape(kind='rect',x0=v0,x1=v1,fill=True,opacity=.5))
			elif isinstance(xspan,dict):
				xspan['kind']='rect'
				shapes.append(get_shape(**xspan))
			elif isinstance(xspan,tuple):
				v0,v1=xspan
				if orientation=='h':
					shapes.append(get_shape(kind='rect',y0=v0,y1=v1,fill=True,opacity=.5))
				else:
					shapes.append(get_shape(kind='rect',x0=v0,x1=v1,fill=True,opacity=.5))
			else:
				raise Exception('Invalid value for {0}span: {1}'.format(orientation,xspan))

		if 'hline' in kwargs:
			get_shapes('hline')
		if 'vline' in kwargs:
			get_shapes('vline')
		if 'hspan' in kwargs:
			get_span('hspan')
		if 'vspan' in kwargs:
			get_span('vspan')
		if 'shapes' in kwargs:
			shapes_=kwargs['shapes']
			if isinstance(shapes_,list):
				for i in shapes_:
					shp=i if 'type' in i else get_shape(**i)
					shapes.append(shp)
			elif isinstance(shapes_,dict):
					shp=shapes_ if 'type' in shapes_ else get_shape(**shapes_)
					shapes.append(shp)
			else:
				raise Exception("Shapes need to be either a dict or list of dicts")

		layout['shapes']=shapes

	# Maps
	if kind in ('choropleth','scattergeo'):
		kw=check_kwargs(kwargs,__GEO_KWARGS)
		defaults={'projection':{'type':'equirectangular'},'showframe':False,'showcoastlines':False}
		for k,v in list(defaults.items()):
			if k not in kw:
				kw[k]=v
		kw_=kwargs_from_keyword(kw,{},'projection')
		deep_update(kw,kw_)
		layout['geo']=kw
		del layout['xaxis']
		del layout['yaxis']
		if not margin:
			layout['margin']={'autoexpand':True}

	# Range Selector
	if 'rangeselector' in kwargs:
		rs=kwargs['rangeselector']
		if 'axis' in rs:
			axis=rs['axis']
			del rs['axis']
		else:
			axis='xaxis'
		layout[axis]['rangeselector']=get_range_selector(**rs)

	# Range Slider
	if 'rangeslider' in kwargs:
		if type(kwargs['rangeslider'])==bool:
			if kwargs['rangeslider']:
				layout['xaxis']['rangeslider']=dict(visible=kwargs['rangeslider'])
			else:
				layout['xaxis']['rangeslider']=dict(visible=False)
				# layout['yaxis1'].update(domain=(0,0))
		else:
			layout['xaxis']['rangeslider']=kwargs['rangeslider']
	else:
		if kind in ('ohlc','candle','candlestick'):
			layout['xaxis']['rangeslider']=dict(visible=False)
			# layout['yaxis1'].update(domain=(0,0))

	# Explicit Updates

	if 'layout_update' in kwargs:
		layout=deep_update(layout,kwargs['layout_update'])

	return layout

Response: This function returns a string that can be used to create a plotly layout.