INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Add a read-only ``{prop_name}`` property to the element class that
returns the present member of this group, or |None| if none are
present. | def _add_choice_getter(self):
"""
Add a read-only ``{prop_name}`` property to the element class that
returns the present member of this group, or |None| if none are
present.
"""
property_ = property(self._choice_getter, None, None)
# assign unconditionally to over... |
Add a ``_remove_eg_x()`` method to the element class for this choice
group. | def _add_group_remover(self):
"""
Add a ``_remove_eg_x()`` method to the element class for this choice
group.
"""
def _remove_choice_group(obj):
for tagname in self._member_nsptagnames:
obj.remove_all(tagname)
_remove_choice_group.__doc__ = (
... |
Return a function object suitable for the "get" side of the property
descriptor. | def _choice_getter(self):
"""
Return a function object suitable for the "get" side of the property
descriptor.
"""
def get_group_member_element(obj):
return obj.first_child_found_in(*self._member_nsptagnames)
get_group_member_element.__doc__ = (
'R... |
Return the first child found with tag in *tagnames*, or None if
not found. | def first_child_found_in(self, *tagnames):
"""
Return the first child found with tag in *tagnames*, or None if
not found.
"""
for tagname in tagnames:
child = self.find(qn(tagname))
if child is not None:
return child
return None |
Remove all child elements whose tagname (e.g. 'a:p') appears in
*tagnames*. | def remove_all(self, *tagnames):
"""
Remove all child elements whose tagname (e.g. 'a:p') appears in
*tagnames*.
"""
for tagname in tagnames:
matching = self.findall(qn(tagname))
for child in matching:
self.remove(child) |
Override of ``lxml`` _Element.xpath() method to provide standard Open
XML namespace mapping (``nsmap``) in centralized location. | def xpath(self, xpath_str):
"""
Override of ``lxml`` _Element.xpath() method to provide standard Open
XML namespace mapping (``nsmap``) in centralized location.
"""
return super(BaseOxmlElement, self).xpath(
xpath_str, namespaces=nsmap
) |
An |RGBColor| value or |None| if no RGB color is specified.
When :attr:`type` is `MSO_COLOR_TYPE.RGB`, the value of this property
will always be an |RGBColor| value. It may also be an |RGBColor|
value if :attr:`type` is `MSO_COLOR_TYPE.THEME`, as Word writes the
current value of a theme... | def rgb(self):
"""
An |RGBColor| value or |None| if no RGB color is specified.
When :attr:`type` is `MSO_COLOR_TYPE.RGB`, the value of this property
will always be an |RGBColor| value. It may also be an |RGBColor|
value if :attr:`type` is `MSO_COLOR_TYPE.THEME`, as Word writes t... |
A member of :ref:`MsoThemeColorIndex` or |None| if no theme color is
specified. When :attr:`type` is `MSO_COLOR_TYPE.THEME`, the value of
this property will always be a member of :ref:`MsoThemeColorIndex`.
When :attr:`type` has any other value, the value of this property is
|None|.
... | def theme_color(self):
"""
A member of :ref:`MsoThemeColorIndex` or |None| if no theme color is
specified. When :attr:`type` is `MSO_COLOR_TYPE.THEME`, the value of
this property will always be a member of :ref:`MsoThemeColorIndex`.
When :attr:`type` has any other value, the valu... |
Read-only. A member of :ref:`MsoColorType`, one of RGB, THEME, or
AUTO, corresponding to the way this color is defined. Its value is
|None| if no color is applied at this level, which causes the
effective color to be inherited from the style hierarchy. | def type(self):
"""
Read-only. A member of :ref:`MsoColorType`, one of RGB, THEME, or
AUTO, corresponding to the way this color is defined. Its value is
|None| if no color is applied at this level, which causes the
effective color to be inherited from the style hierarchy.
... |
The type of this inline shape as a member of
``docx.enum.shape.WD_INLINE_SHAPE``, e.g. ``LINKED_PICTURE``.
Read-only. | def type(self):
"""
The type of this inline shape as a member of
``docx.enum.shape.WD_INLINE_SHAPE``, e.g. ``LINKED_PICTURE``.
Read-only.
"""
graphicData = self._inline.graphic.graphicData
uri = graphicData.uri
if uri == nsmap['pic']:
blip = gr... |
Extracts the data from a Plotly Figure
Parameters
----------
figure : plotly_figure
Figure from which data will be
extracted
Returns a DataFrame or list of DataFrame | def to_df(figure):
"""
Extracts the data from a Plotly Figure
Parameters
----------
figure : plotly_figure
Figure from which data will be
extracted
Returns a DataFrame or list of DataFrame
"""
dfs=[]
for trace in figure['data']:
if '... |
Converts from hex|rgb to rgba
Parameters:
-----------
color : string
Color representation on hex or rgb
alpha : float
Value from 0 to 1.0 that represents the
alpha value.
Example:
to_rgba('#E1E5ED',0.6)
... | def to_rgba(color, alpha):
"""
Converts from hex|rgb to rgba
Parameters:
-----------
color : string
Color representation on hex or rgb
alpha : float
Value from 0 to 1.0 that represents the
alpha value.
Example:
... |
Converts from hex to rgb
Parameters:
-----------
color : string
Color representation on hex or rgb
Example:
hex_to_rgb('#E1E5ED')
hex_to_rgb('#f03') | def hex_to_rgb(color):
"""
Converts from hex to rgb
Parameters:
-----------
color : string
Color representation on hex or rgb
Example:
hex_to_rgb('#E1E5ED')
hex_to_rgb('#f03')
"""
color = normalize(color)
color = color[1:]
# r... |
Returns an hex color
Parameters:
-----------
color : string
Color representation in rgba|rgb|hex
Example:
normalize('#f03') | def normalize(color):
"""
Returns an hex color
Parameters:
-----------
color : string
Color representation in rgba|rgb|hex
Example:
normalize('#f03')
"""
if type(color) == tuple:
color = to_rgba(*color)
if 'rgba' in color:
ret... |
Converts from rgb to hex
Parameters:
-----------
color : string
Color representation on hex or rgb
Example:
rgb_to_hex('rgb(23,25,24)') | def rgb_to_hex(color):
"""
Converts from rgb to hex
Parameters:
-----------
color : string
Color representation on hex or rgb
Example:
rgb_to_hex('rgb(23,25,24)')
"""
rgb = eval(color.replace('rgb', ''))
# return '#'+''.join(map(chr, rgb)).en... |
Converts from rgba to rgb
Parameters:
-----------
color : string
Color representation in rgba
bg : string
Color representation in rgb
Example:
rgba_to_rgb('rgb(23,25,24,.4)'' | def rgba_to_rgb(color, bg='rgb(255,255,255)'):
"""
Converts from rgba to rgb
Parameters:
-----------
color : string
Color representation in rgba
bg : string
Color representation in rgb
Example:
rgba_to_rgb('rgb(23,25,24,.4... |
Converts from hex to hsv
Parameters:
-----------
color : string
Color representation on color
Example:
hex_to_hsv('#ff9933') | def hex_to_hsv(color):
"""
Converts from hex to hsv
Parameters:
-----------
color : string
Color representation on color
Example:
hex_to_hsv('#ff9933')
"""
color = normalize(color)
color = color[1:]
# color=tuple(ord(c)/255.0 for c in col... |
Generates a scale of colours from a base colour
Parameters:
-----------
color : string
Color representation in hex
N : int
number of colours to generate
Example:
color_range('#ff9933',20) | def color_range(color, N=20):
"""
Generates a scale of colours from a base colour
Parameters:
-----------
color : string
Color representation in hex
N : int
number of colours to generate
Example:
color_range('#ff9933',20... |
Generates a colour table
Parameters:
-----------
color : string | list | dict
Color representation in rgba|rgb|hex
If a list of colors is passed then these
are displayed in a table
N : int
number of colou... | def color_table(color, N=1, sort=False, sort_values=False, inline=False, as_html=False):
"""
Generates a colour table
Parameters:
-----------
color : string | list | dict
Color representation in rgba|rgb|hex
If a list of colors is passed then these
... |
Returns a generator with a list of colors
and gradients of those colors
Parameters:
-----------
colors : list(colors)
List of colors to use
Example:
colorgen()
colorgen(['blue','red','pink'])
colorgen(['#f03','rgb(23,25,25)']) | def colorgen(colors=None, n=None, scale=None, theme=None):
"""
Returns a generator with a list of colors
and gradients of those colors
Parameters:
-----------
colors : list(colors)
List of colors to use
Example:
colorgen()
colorgen(['blue... |
Displays a color scale (HTML)
Parameters:
-----------
scale : str
Color scale name
If no scale name is provided then all scales are returned
(max number for each scale)
If scale='all' then all scale combinations... | def scales(scale=None):
"""
Displays a color scale (HTML)
Parameters:
-----------
scale : str
Color scale name
If no scale name is provided then all scales are returned
(max number for each scale)
If sca... |
Returns a color scale
Parameters:
-----------
scale : str
Color scale name
If the color name is preceded by a minus (-)
then the scale is inversed
n : int
Number of colors
If n < numbe... | def get_scales(scale=None, n=None):
"""
Returns a color scale
Parameters:
-----------
scale : str
Color scale name
If the color name is preceded by a minus (-)
then the scale is inversed
n : int
Nu... |
Returns a color scale to be used for a plotly figure
Parameters:
-----------
scale : str or list
Color scale name
If the color name is preceded by a minus (-)
then the scale is inversed.
Also accepts a list of colors (... | def get_colorscale(scale):
"""
Returns a color scale to be used for a plotly figure
Parameters:
-----------
scale : str or list
Color scale name
If the color name is preceded by a minus (-)
then the scale is inversed.
... |
Generates a plotly Data object
Parameters
----------
colors : list or dict
{key:color} to specify the color for each column
[colors] to use the colors in the defined order
colorscale : str
Color scale name
Only valid if 'colors' is null
See cufflinks.colors.scales() for available scales
kind :... | def _to_iplot(self,colors=None,colorscale=None,kind='scatter',mode='lines',interpolation='linear',symbol='dot',size='12',fill=False,
width=3,dash='solid',sortbars=False,keys=False,bestfit=False,bestfit_colors=None,opacity=0.6,
mean=False,mean_colors=None,asDates=False,asTimestamp=False,text=None,**kwargs):
"""
Ge... |
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... | 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,histn... |
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 | 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... |
Displays a matrix with scatter plot for each pair of
Series in the DataFrame.
The diagonal shows a histogram for each of the Series
Parameters:
-----------
df : DataFrame
Pandas DataFrame
theme : string
Theme to be used (if not the default)
bins : int
Number of bins to use for histogram
color : s... | def _scatter_matrix(self,theme=None,bins=10,color='grey',size=2, asFigure=False, **iplot_kwargs):
"""
Displays a matrix with scatter plot for each pair of
Series in the DataFrame.
The diagonal shows a histogram for each of the Series
Parameters:
-----------
df : DataFrame
Pandas DataFrame
theme : string
... |
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... | 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 va... |
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
... | 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 Averag... |
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... | 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 c... |
Ensure that filesystem is setup/filled out in a valid way | 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:
c... |
Checks if file exists. Returns {} if something fails. | def load_json_dict(filename, *args):
"""Checks if file exists. Returns {} if something fails."""
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 ... |
Will error if filename is not appropriate, but it's checked elsewhere. | def save_json_dict(filename, json_dict):
"""Will error if filename is not appropriate, but it's checked elsewhere.
"""
if isinstance(json_dict, dict):
with open(filename, "w") as f:
f.write(json.dumps(json_dict, indent=4))
else:
raise TypeError("json_dict was not a dictionay. couldn't save.") |
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 availab... | 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... |
Returns a dictionary with the schema for a QuantFigure | 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[_][__]=N... |
Returns a sliced DataFrame
Parameters
----------
slice : tuple(from,to)
from : str
to : str
States the 'from' and 'to' values which
will get rendered as df.ix[from:to]
df : DataFrame
If omitted then the QuantFigure.DataFrame is resampled. | def _get_sliced(self,slice,df=None):
"""
Returns a sliced DataFrame
Parameters
----------
slice : tuple(from,to)
from : str
to : str
States the 'from' and 'to' values which
will get rendered as df.ix[from:to]
df : DataFrame
If omitted then the QuantFigure.DataFrame is resampled.
... |
Returns a resampled DataFrame
Parameters
----------
rule : str
the offset string or object representing target conversion
for all aliases available see http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
how : str or dict
states the form in which the resampling will be done... | def _get_resampled(self,rule,how={'ohlc':'last','volume':'sum'},df=None,**kwargs):
"""
Returns a resampled DataFrame
Parameters
----------
rule : str
the offset string or object representing target conversion
for all aliases available see http://pandas.pydata.org/pandas-docs/stable/timeseries.html#o... |
Updates the values for a QuantFigure
The key-values are automatically assigned to the correct
section of the QuantFigure | def update(self,**kwargs):
"""
Updates the values for a QuantFigure
The key-values are automatically assigned to the correct
section of the QuantFigure
"""
if 'columns' in kwargs:
self._d=ta._ohlc_dict(self.df,columns=kwargs.pop('columns',None))
schema=self._get_schema()
annotations=kwargs.pop('anno... |
Deletes the values for a QuantFigure
The key-values are automatically deleted from the correct
section of the QuantFigure | 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():
... |
Returns the panel domains for each axis | 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))
... |
Returns a trendline (line), support or resistance
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate the data series in which the
trendline should be based.
'close'
'high'
'low'
'open'
kind : string
Def... | def _get_trendline(self,date0=None,date1=None,on=None,kind='trend',to_strfmt='%Y-%m-%d',from_strfmt='%d%b%y',**kwargs):
"""
Returns a trendline (line), support or resistance
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate the data... |
Adds a trendline to the QuantFigure.
Given 2 dates, the trendline is connected on the data points
that correspond to those dates.
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on : string
Indicate the data series in which the
trendline should be... | def add_trendline(self,date0,date1,on='close',text=None,**kwargs):
"""
Adds a trendline to the QuantFigure.
Given 2 dates, the trendline is connected on the data points
that correspond to those dates.
Parameters:
date0 : string
Trendline starting date
date1 : string
Trendline end date
on ... |
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 : str... | 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 l... |
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 : st... | 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... |
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 pa... | 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
... |
Adds a study to QuantFigure.studies
Parameters:
study : dict
{'kind':study_kind,
'params':study_parameters,
'display':display_parameters} | def _add_study(self,study):
"""
Adds a study to QuantFigure.studies
Parameters:
study : dict
{'kind':study_kind,
'params':study_parameters,
'display':display_parameters}
"""
str='{study} {name}({period})' if study['params'].get('str',None)==None else study['params']['str']
study['params'][... |
Add 'volume' study to QuantFigure.studies
Parameters:
colorchange : bool
If True then each volume bar will have a fill color
depending on if 'base' had a positive or negative
change compared to the previous value
If False then each volume bar will have a fill color
depending on if the volume... | def add_volume(self,colorchange=True,column=None,name='',str='{name}',**kwargs):
"""
Add 'volume' study to QuantFigure.studies
Parameters:
colorchange : bool
If True then each volume bar will have a fill color
depending on if 'base' had a positive or negative
change compared to the previous value... |
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 stu... | 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
... |
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 :... | 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 ap... |
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_uppe... | 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 (overbough... |
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
... | 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... |
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 level... | 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
... |
Add Parabolic SAR (PTPS) study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
af : float
acceleration factor
initial : 'long' or 'short'
Iniital position
default: long
name : string
Name given to the study
str : string
Label factory for studies
... | def add_ptps(self,periods=14,af=0.2,initial='long',str=None,name='',**kwargs):
"""
Add Parabolic SAR (PTPS) study to QuantFigure.studies
Parameters:
periods : int or list(int)
Number of periods
af : float
acceleration factor
initial : 'long' or 'short'
Iniital position
default: long
n... |
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 stu... | 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:... |
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 | def go_offline(connected=None):
"""
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
"""
from .auth import get_config_file
if connected is None:
try... |
Filters a DataFrame for columns that contain the given strings.
Parameters:
-----------
include : bool
If False then it will exclude items that match
the given filters.
This is the same as passing a regex ^keyword
kwargs :
Key value pairs that indicate the column and
value to screen for
Examp... | def _screen(self,include=True,**kwargs):
"""
Filters a DataFrame for columns that contain the given strings.
Parameters:
-----------
include : bool
If False then it will exclude items that match
the given filters.
This is the same as passing a regex ^keyword
kwargs :
Key value pairs that indicate... |
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. | 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://g... |
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 | 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:
... |
d1 <-- d2 | def merge_dict(d1,d2):
"""
d1 <-- d2
"""
d=copy.deepcopy(d2)
for k,v in list(d1.items()):
if k not in d:
d[k]=v
else:
if isinstance(v,dict):
d[k]=merge_dict(d1[k],d[k])
return d |
Returns a dictionary with the path in which each of the keys is found
Parameters:
from_d : dict
Dictionary that contains all the keys, values
to_d : dict
Dictionary to which the results will be appended
Example:
dict_path({'level1':{'level2':{'level3':'value'}}})
Returns
{'level1': [],
'level... | def dict_path(from_d,to_d={},l=[]):
"""
Returns a dictionary with the path in which each of the keys is found
Parameters:
from_d : dict
Dictionary that contains all the keys, values
to_d : dict
Dictionary to which the results will be appended
Example:
dict_path({'level1':{'level2':{'level3':'value'}}... |
Formats (prettyprint) a concatenated dictionary | def pp(el,preString=''):
"""
Formats (prettyprint) a concatenated dictionary
"""
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:
... |
Returns a dictionay indexed by values {value_k:key_k}
Parameters:
-----------
d : dictionary | 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 |
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 : ... | 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
key... |
Updates the values (deep form) of a given dictionary
Parameters:
-----------
d : dict
dictionary that contains the values to update
d_update : dict
dictionary to be updated | def deep_update(d,d_update):
"""
Updates the values (deep form) of a given dictionary
Parameters:
-----------
d : dict
dictionary that contains the values to update
d_update : dict
dictionary to be updated
"""
for k,v in list(d_update.items()):
if isinstance(v,dict):
if k in d:
deep_update(d[k... |
Reads a google sheet | 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) |
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 | 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) |
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
C... | 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... |
how : string
value
pct_chg
diff | def correl(df,periods=21,columns=None,include=True,str=None,detail=False,how='value',**correl_kwargs):
"""
how : string
value
pct_chg
diff
"""
def _correl(df,periods=21,columns=None,include=True,str=None,detail=False,**correl_kwargs):
study='CORREL'
df,_df,columns=validate(df,columns)
_df['CORREL']... |
Returns | 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'})
retu... |
Returns | def choropleth():
"""
Returns
"""
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 |
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 | 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.ra... |
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 r... | 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
Fo... |
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 | 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... |
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 enu... | 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
... |
Returns a DataFrame with the required format for
a bar plot
Parameters:
-----------
n : int
Number of points for each trace
n_categories : int
Number of categories for each point
prefix : string
Name for each category
columns : [str]
List of column names
mode : string
Format for each item
... | def bars(n=3,n_categories=3,prefix='category',columns=None,mode='abc'):
"""
Returns a DataFrame with the required format for
a bar plot
Parameters:
-----------
n : int
Number of points for each trace
n_categories : int
Number of categories for each point
prefix : string
Name for each category
co... |
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 | 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(... |
Returns a DataFrame with the required format for
a candlestick or ohlc plot
df[['open','high','low','close','volume']
Parameters:
-----------
n : int
Number of ohlc points | def ohlcv(n=100):
"""
Returns a DataFrame with the required format for
a candlestick or ohlc plot
df[['open','high','low','close','volume']
Parameters:
-----------
n : int
Number of ohlc points
"""
df=ohlc()
df['volume']=[np.random.randint(1000,10000) for _ in range(len(df))]
return df |
Returns a DataFrame with the required format for
a box plot
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for random stock names | def box(n_traces=5,n=100,mode=None):
"""
Returns a DataFrame with the required format for
a box plot
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for random stock name... |
Returns a DataFrame with the required format for
a histogram plot
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for random stock names | def histogram(n_traces=1,n=500,dispersion=2,mode=None):
"""
Returns a DataFrame with the required format for
a histogram plot
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet columns
'stoc... |
Returns a DataFrame with the required format for
a distribution plot (distplot)
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for random stock names | def distplot(n_traces=1,n=500,dispersion=3,mode=None):
"""
Returns a DataFrame with the required format for
a distribution plot (distplot)
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet colu... |
Returns a DataFrame with the required format for
a distribution plot (distplot)
Parameters:
-----------
n : int
Number of points
categories : bool or int
If True, then a column with categories is added
n_categories : int
Number of categories | def violin(n=500,dispersion=3,categories=True,n_categories=5):
"""
Returns a DataFrame with the required format for
a distribution plot (distplot)
Parameters:
-----------
n : int
Number of points
categories : bool or int
If True, then a column with categories is added
n_categories : int
Number of... |
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 | 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.... |
Returns a DataFrame with the required format for
a surface (sine wave) plot
Parameters:
-----------
n : int
Ranges for X and Y axis (-n,n)
n_y : int
Size of increment along the axis | def sinwave(n=4,inc=.25):
"""
Returns a DataFrame with the required format for
a surface (sine wave) plot
Parameters:
-----------
n : int
Ranges for X and Y axis (-n,n)
n_y : int
Size of increment along the axis
"""
x=np.arange(-n,n,inc)
y=np.arange(-n,n,inc)
X,Y=np.meshgrid(x,y)
R = np.sqrt(X**2... |
Returns a theme definition.
To see the colors translated (hex) use
cufflinks.getLayout(theme) instead. | 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}".... |
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 displ... | 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... |
Generates an annotations object
Parameters:
-----------
df : DataFrame
Original DataFrame of values
annotations : dict or list
Dictionary of annotations
{x_point : text}
or
List of Plotly annotations | def get_annotations(df,annotations,kind='lines',theme=None,**kwargs):
"""
Generates an annotations object
Parameters:
-----------
df : DataFrame
Original DataFrame of values
annotations : dict or list
Dictionary of annotations
{x_point : text}
or
List of Plotly annotations
"""
for key in ... |
Strips a figure into multiple figures with a trace on each of them
Parameters:
-----------
figure : Figure
Plotly Figure | def strip_figures(figure):
"""
Strips a figure into multiple figures with a trace on each of them
Parameters:
-----------
figure : Figure
Plotly Figure
"""
fig=[]
for trace in figure['data']:
fig.append(dict(data=[trace],layout=figure['layout']))
return fig |
Generates a layout with the union of all properties of multiple
figures' layouts
Parameters:
-----------
fig : list(Figures)
List of Plotly Figures | def get_base_layout(figs):
"""
Generates a layout with the union of all properties of multiple
figures' layouts
Parameters:
-----------
fig : list(Figures)
List of Plotly Figures
"""
layout={}
for fig in figs:
if not isinstance(fig,dict):
fig=fig.to_dict()
for k,v in list(fig['layout'].items()):
... |
Generates multiple Plotly figures for a given DataFrame
Parameters:
-----------
df : DataFrame
Pandas DataFrame
specs : list(dict)
List of dictionaries with the properties
of each figure.
All properties avaialbe can be seen with
help(cufflinks.pd.DataFrame.iplot)
asList : boolean
If True, the... | def figures(df,specs,asList=False):
"""
Generates multiple Plotly figures for a given DataFrame
Parameters:
-----------
df : DataFrame
Pandas DataFrame
specs : list(dict)
List of dictionaries with the properties
of each figure.
All properties avaialbe can be seen with
help(cufflinks.pd.DataFrame... |
Generates a single Figure from a list of figures
Parameters:
-----------
figures : list(Figures)
List of figures to be merged. | def merge_figures(figures):
"""
Generates a single Figure from a list of figures
Parameters:
-----------
figures : list(Figures)
List of figures to be merged.
"""
figure={}
data=[]
for fig in figures:
for trace in fig['data']:
data.append(trace)
layout=get_base_layout(figures)
figure['data']=data
... |
Generates a subplot view for a set of figures
This is a wrapper for plotly.tools.make_subplots
Parameters:
-----------
figures : [Figures]
List of Plotly Figures
shape : (rows,cols)
Tuple indicating the size of rows and columns
If omitted then the layout is automatically set
shared_xaxes : bool
As... | def subplots(figures,shape=None,
shared_xaxes=False, shared_yaxes=False,
start_cell='top-left', theme=None,base_layout=None,
**kwargs):
"""
Generates a subplot view for a set of figures
This is a wrapper for plotly.tools.make_subplots
Parameters:
-----------
figures : [Figures]
List of Plot... |
Generates a subplot view for a set of figures
Parameters:
-----------
rows : int
Number of rows
cols : int
Number of cols
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 gird.
shared_yaxes : bool
Assign s... | def get_subplots(rows=1,cols=1,
shared_xaxes=False, shared_yaxes=False,
start_cell='top-left', theme=None,base_layout=None,
**kwargs):
"""
Generates a subplot view for a set of figures
Parameters:
-----------
rows : int
Number of rows
cols : int
Number of cols
shared_xaxes : bool
... |
Displays a matrix with scatter plot for each pair of
Series in the DataFrame.
The diagonal shows a histogram for each of the Series
Parameters:
-----------
df : DataFrame
Pandas DataFrame
theme : string
Theme to be used (if not the default)
bins : int
Number of bins to use for histogram
color : st... | def scatter_matrix(df,theme=None,bins=10,color='grey',size=2):
"""
Displays a matrix with scatter plot for each pair of
Series in the DataFrame.
The diagonal shows a histogram for each of the Series
Parameters:
-----------
df : DataFrame
Pandas DataFrame
theme : string
Theme to be used (if not the defa... |
Sets the axis in which each trace should appear
If the axis doesn't exist then a new axis is created
Parameters:
-----------
traces : list(str)
List of trace names
on : string
The axis in which the traces should be placed.
If this is not indicated then a new axis will be
created
side : string
S... | def _set_axis(self,traces,on=None,side='right',title=''):
"""
Sets the axis in which each trace should appear
If the axis doesn't exist then a new axis is created
Parameters:
-----------
traces : list(str)
List of trace names
on : string
The axis in which the traces should be placed.
If this is not i... |
Returns a plotly shape
Parameters:
-----------
kind : string
Shape kind
line
rect
circle
x : float
x values for the shape.
This assumes x0=x1
x0 : float
x0 value for the shape
x1 : float
x1 value for the shape
y : float
y values for the shape.
This assumes y0=y1
y0 : floa... | def get_shape(kind='line',x=None,y=None,x0=None,y0=None,x1=None,y1=None,span=0,color='red',dash='solid',width=1,
fillcolor=None,fill=False,opacity=1,xref='x',yref='y'):
"""
Returns a plotly shape
Parameters:
-----------
kind : string
Shape kind
line
rect
circle
x : float
x values for the ... |
Returns a range selector
Reference: https://plot.ly/python/reference/#layout-xaxis-rangeselector
Parameters:
-----------
steps : string or list(string)
Steps for the range
Examples:
['1y','2 months','5 weeks','ytd','2mtd']
bgocolor : string or tuple(color,alpha)
Background color
Examples:
... | def get_range_selector(steps=['1m','1y'],bgcolor='rgba(150, 200, 250, 0.4)',x=0,y=0.9,
visible=True,**kwargs):
"""
Returns a range selector
Reference: https://plot.ly/python/reference/#layout-xaxis-rangeselector
Parameters:
-----------
steps : string or list(string)
Steps for the range
Examples:
... |
Display an [n, m] matrix of labels | def view_label_matrix(L, colorbar=True):
"""Display an [n, m] matrix of labels"""
L = L.todense() if sparse.issparse(L) else L
plt.imshow(L, aspect="auto")
plt.title("Label Matrix")
if colorbar:
labels = sorted(np.unique(np.asarray(L).reshape(-1, 1).squeeze()))
boundaries = np.array(... |
Display an [m, m] matrix of overlaps | def view_overlaps(L, self_overlaps=False, normalize=True, colorbar=True):
"""Display an [m, m] matrix of overlaps"""
L = L.todense() if sparse.issparse(L) else L
G = _get_overlaps_matrix(L, normalize=normalize)
if not self_overlaps:
np.fill_diagonal(G, 0) # Zero out self-overlaps
plt.imshow... |
Display an [m, m] matrix of conflicts | def view_conflicts(L, normalize=True, colorbar=True):
"""Display an [m, m] matrix of conflicts"""
L = L.todense() if sparse.issparse(L) else L
C = _get_conflicts_matrix(L, normalize=normalize)
plt.imshow(C, aspect="auto")
plt.title("Conflicts")
if colorbar:
plt.colorbar()
plt.show() |
Plot a histogram from a numpy array of probabilities
Args:
Y_p: An [n] or [n, 1] np.ndarray of probabilities (floats in [0,1]) | def plot_probabilities_histogram(Y_p, title=None):
"""Plot a histogram from a numpy array of probabilities
Args:
Y_p: An [n] or [n, 1] np.ndarray of probabilities (floats in [0,1])
"""
if Y_p.ndim > 1:
msg = (
f"Arg Y_p should be a 1-dimensional np.ndarray, not of shape "
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.