index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
723,544 | serial_bus.models | SerialBusRenderableModel | A Renderable model allows for its instances to render a string
according to a Jinja2 template. This enables various automation
use-cases.
The expected template file name is derived in either of two ways:
- a statically defined `_template_name` attribute in the child class.
- the class name split on the capital letters, removing
the word 'Model' (if present), and then joined by underscores ('_'):
- MyClass -> my_class
- OtherClassModel -> other_class
- ModelYetAnotherClass -> yet_another_class
NOTE: Support for additional templating languages is under consideration.
| class SerialBusRenderableModel(SerialBusBaseModel):
"""A Renderable model allows for its instances to render a string
according to a Jinja2 template. This enables various automation
use-cases.
The expected template file name is derived in either of two ways:
- a statically defined `_template_name` attribute in the child class.
- the class name split on the capital letters, removing
the word 'Model' (if present), and then joined by underscores ('_'):
- MyClass -> my_class
- OtherClassModel -> other_class
- ModelYetAnotherClass -> yet_another_class
NOTE: Support for additional templating languages is under consideration.
"""
def __new__(cls, *args, **kwargs):
"""Overrides the __new__ method to prevent direct instantiation of this class."""
if cls == SerialBusRenderableModel:
raise ModelInitializationError(
"Cannot instantiate SerialBusRenderableModel directly."
)
return super().__new__(cls)
@classmethod
def create(
cls, dict_args: Dict[Any, Any], *args, **kwargs
) -> "SerialBusRenderableModel":
"""Overrides the create method to guarantee the _template_name attribute"""
cls._set_template(**dict_args)
return super().create(dict_args, *args, **kwargs)
@classmethod
def _set_template(cls, **kwargs):
"""
Guarantees the instance will have a _template_name attribute already set.
If the child class doesn't define it already, one will be created.
"""
try:
getattr(cls, "_template_name")
except AttributeError:
informed_template_name = kwargs.get("template_name")
if informed_template_name:
cls._template_name = informed_template_name
else:
split_cls_name = re.findall("[A-Z][^A-Z]*", cls.__name__)
if "Model" in split_cls_name:
split_cls_name.remove("Model")
cls._template_name = "_".join(split_cls_name).lower()
@property
def template_name(self) -> str:
"""A property to access the _template_name attribute."""
return self._template_name
def get_rendered_str(self, extra_vars_dict: Optional[Dict[str, Any]] = None) -> str:
"""
Renders this RenderableSerialBusModel into a string according to the Jinja2
template indicated by _template_name attribute.
A dictionary representation of this instance will be passed to the render method.
However, if the template requires additional variables that wouldn't match any of
the attributes of this instance, the caller can pass them through `extra_vars_dict`
argument.
Args:
extra_vars_dict (Optional[Dict[str, Any]], optional): A dictionary containing
extra vars that the template may require. Defaults to None.
Returns:
str: the rendered string produced by the .render() method of the Template
object.
"""
if extra_vars_dict:
_dict_to_render = dict(self)
_dict_to_render.update(extra_vars_dict)
return self._get_template().render(_dict_to_render)
return self._get_template().render(dict(self))
def _get_template(self) -> Template:
"""
Retrieves the template file to be used to render this RenderableSerialBusModel.
Currently, only Jinja2 templates are supported. Hence, the file is expected to
have a '.j2' extension.
Raises:
RenderableTemplateError: if a template file with expected name does not exist.
Returns:
Template: The template file as a jinja2.Template object.
"""
env = Environment(loader=FileSystemLoader(GLOBAL_CONFIGS.templates_dir))
try:
return env.get_template(f"{self.template_name}.j2")
except TemplateNotFound as err:
raise RenderableTemplateError(err.message)
| () -> None |
723,558 | serial_bus.models | __new__ | Overrides the __new__ method to prevent direct instantiation of this class. | def __new__(cls, *args, **kwargs):
"""Overrides the __new__ method to prevent direct instantiation of this class."""
if cls == SerialBusRenderableModel:
raise ModelInitializationError(
"Cannot instantiate SerialBusRenderableModel directly."
)
return super().__new__(cls)
| (cls, *args, **kwargs) |
723,571 | serial_bus.models | _get_template |
Retrieves the template file to be used to render this RenderableSerialBusModel.
Currently, only Jinja2 templates are supported. Hence, the file is expected to
have a '.j2' extension.
Raises:
RenderableTemplateError: if a template file with expected name does not exist.
Returns:
Template: The template file as a jinja2.Template object.
| def _get_template(self) -> Template:
"""
Retrieves the template file to be used to render this RenderableSerialBusModel.
Currently, only Jinja2 templates are supported. Hence, the file is expected to
have a '.j2' extension.
Raises:
RenderableTemplateError: if a template file with expected name does not exist.
Returns:
Template: The template file as a jinja2.Template object.
"""
env = Environment(loader=FileSystemLoader(GLOBAL_CONFIGS.templates_dir))
try:
return env.get_template(f"{self.template_name}.j2")
except TemplateNotFound as err:
raise RenderableTemplateError(err.message)
| (self) -> jinja2.environment.Template |
723,575 | serial_bus.models | get_rendered_str |
Renders this RenderableSerialBusModel into a string according to the Jinja2
template indicated by _template_name attribute.
A dictionary representation of this instance will be passed to the render method.
However, if the template requires additional variables that wouldn't match any of
the attributes of this instance, the caller can pass them through `extra_vars_dict`
argument.
Args:
extra_vars_dict (Optional[Dict[str, Any]], optional): A dictionary containing
extra vars that the template may require. Defaults to None.
Returns:
str: the rendered string produced by the .render() method of the Template
object.
| def get_rendered_str(self, extra_vars_dict: Optional[Dict[str, Any]] = None) -> str:
"""
Renders this RenderableSerialBusModel into a string according to the Jinja2
template indicated by _template_name attribute.
A dictionary representation of this instance will be passed to the render method.
However, if the template requires additional variables that wouldn't match any of
the attributes of this instance, the caller can pass them through `extra_vars_dict`
argument.
Args:
extra_vars_dict (Optional[Dict[str, Any]], optional): A dictionary containing
extra vars that the template may require. Defaults to None.
Returns:
str: the rendered string produced by the .render() method of the Template
object.
"""
if extra_vars_dict:
_dict_to_render = dict(self)
_dict_to_render.update(extra_vars_dict)
return self._get_template().render(_dict_to_render)
return self._get_template().render(dict(self))
| (self, extra_vars_dict: Optional[Dict[str, Any]] = None) -> str |
723,587 | wordninja | LanguageModel | null | class LanguageModel(object):
def __init__(self, word_file):
# Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability).
with gzip.open(word_file) as f:
words = f.read().decode().split()
self._wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words))
self._maxword = max(len(x) for x in words)
def split(self, s):
"""Uses dynamic programming to infer the location of spaces in a string without spaces."""
l = [self._split(x) for x in _SPLIT_RE.split(s)]
return [item for sublist in l for item in sublist]
def _split(self, s):
# Find the best match for the i first characters, assuming cost has
# been built for the i-1 first characters.
# Returns a pair (match_cost, match_length).
def best_match(i):
candidates = enumerate(reversed(cost[max(0, i-self._maxword):i]))
return min((c + self._wordcost.get(s[i-k-1:i].lower(), 9e999), k+1) for k,c in candidates)
# Build the cost array.
cost = [0]
for i in range(1,len(s)+1):
c,k = best_match(i)
cost.append(c)
# Backtrack to recover the minimal-cost string.
out = []
i = len(s)
while i>0:
c,k = best_match(i)
assert c == cost[i]
# Apostrophe and digit handling (added by Genesys)
newToken = True
if not s[i-k:i] == "'": # ignore a lone apostrophe
if len(out) > 0:
# re-attach split 's and split digits
if out[-1] == "'s" or (s[i-1].isdigit() and out[-1][0].isdigit()): # digit followed by digit
out[-1] = s[i-k:i] + out[-1] # combine current token with previous token
newToken = False
# (End of Genesys addition)
if newToken:
out.append(s[i-k:i])
i -= k
return reversed(out)
| (word_file) |
723,588 | wordninja | __init__ | null | def __init__(self, word_file):
# Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability).
with gzip.open(word_file) as f:
words = f.read().decode().split()
self._wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words))
self._maxword = max(len(x) for x in words)
| (self, word_file) |
723,589 | wordninja | _split | null | def _split(self, s):
# Find the best match for the i first characters, assuming cost has
# been built for the i-1 first characters.
# Returns a pair (match_cost, match_length).
def best_match(i):
candidates = enumerate(reversed(cost[max(0, i-self._maxword):i]))
return min((c + self._wordcost.get(s[i-k-1:i].lower(), 9e999), k+1) for k,c in candidates)
# Build the cost array.
cost = [0]
for i in range(1,len(s)+1):
c,k = best_match(i)
cost.append(c)
# Backtrack to recover the minimal-cost string.
out = []
i = len(s)
while i>0:
c,k = best_match(i)
assert c == cost[i]
# Apostrophe and digit handling (added by Genesys)
newToken = True
if not s[i-k:i] == "'": # ignore a lone apostrophe
if len(out) > 0:
# re-attach split 's and split digits
if out[-1] == "'s" or (s[i-1].isdigit() and out[-1][0].isdigit()): # digit followed by digit
out[-1] = s[i-k:i] + out[-1] # combine current token with previous token
newToken = False
# (End of Genesys addition)
if newToken:
out.append(s[i-k:i])
i -= k
return reversed(out)
| (self, s) |
723,590 | wordninja | split | Uses dynamic programming to infer the location of spaces in a string without spaces. | def split(self, s):
"""Uses dynamic programming to infer the location of spaces in a string without spaces."""
l = [self._split(x) for x in _SPLIT_RE.split(s)]
return [item for sublist in l for item in sublist]
| (self, s) |
723,594 | wordninja | split | null | def split(s):
return DEFAULT_LANGUAGE_MODEL.split(s)
| (s) |
723,595 | maybe_type.main | Some |
Some[T] is a wrapper for a value of type T.
This allows us to apply the functions bind and map to the value.
Also allows for fancy pattern matching.
| class Some(typing.Generic[T]):
"""
Some[T] is a wrapper for a value of type T.
This allows us to apply the functions bind and map to the value.
Also allows for fancy pattern matching.
"""
value: T
def bind(self, f: typing.Callable[[T], 'Maybe[T]']) -> 'Maybe[T]':
"""Applies a function, that returns a Maybe, to the value, that is wrapped."""
return f(self.value)
def map(self, f: typing.Callable[[T], T]) -> 'Maybe[T]':
"""Applies a function to the value, that is wrapped."""
return Some(f(self.value))
def __repr__(self) -> str:
return f'Some[{self.value.__class__.__name__}]({self.value})'
| (value: ~T) -> None |
723,596 | maybe_type.main | __delattr__ | null | import typing
import functools
from dataclasses import dataclass
T = typing.TypeVar('T')
@dataclass(frozen=True)
class Some(typing.Generic[T]):
"""
Some[T] is a wrapper for a value of type T.
This allows us to apply the functions bind and map to the value.
Also allows for fancy pattern matching.
"""
value: T
def bind(self, f: typing.Callable[[T], 'Maybe[T]']) -> 'Maybe[T]':
"""Applies a function, that returns a Maybe, to the value, that is wrapped."""
return f(self.value)
def map(self, f: typing.Callable[[T], T]) -> 'Maybe[T]':
"""Applies a function to the value, that is wrapped."""
return Some(f(self.value))
def __repr__(self) -> str:
return f'Some[{self.value.__class__.__name__}]({self.value})'
| (self, name) |
723,600 | maybe_type.main | __repr__ | null | def __repr__(self) -> str:
return f'Some[{self.value.__class__.__name__}]({self.value})'
| (self) -> str |
723,602 | maybe_type.main | bind | Applies a function, that returns a Maybe, to the value, that is wrapped. | def bind(self, f: typing.Callable[[T], 'Maybe[T]']) -> 'Maybe[T]':
"""Applies a function, that returns a Maybe, to the value, that is wrapped."""
return f(self.value)
| (self, f: Callable[[~T], Optional[maybe_type.main.Some[~T]]]) -> Optional[maybe_type.main.Some[~T]] |
723,603 | maybe_type.main | map | Applies a function to the value, that is wrapped. | def map(self, f: typing.Callable[[T], T]) -> 'Maybe[T]':
"""Applies a function to the value, that is wrapped."""
return Some(f(self.value))
| (self, f: Callable[[~T], ~T]) -> Optional[maybe_type.main.Some[~T]] |
723,608 | maybe_type.main | with_maybe | A decorator that wraps a function, that may throw an exception, in a Maybe. | def with_maybe(f: typing.Callable[..., T]) -> typing.Callable[..., Maybe[T]]:
"""A decorator that wraps a function, that may throw an exception, in a Maybe."""
@functools.wraps(f)
def wrapper(*args: typing.Any, **kwargs: typing.Any) -> Maybe[T]:
try:
return Some(f(*args, **kwargs))
except Exception:
return None
return wrapper
| (f: Callable[..., ~T]) -> Callable[..., Optional[maybe_type.main.Some[~T]]] |
723,609 | yfinance.ticker | Ticker | null | class Ticker(TickerBase):
def __init__(self, ticker, session=None, proxy=None):
super(Ticker, self).__init__(ticker, session=session, proxy=proxy)
self._expirations = {}
self._underlying = {}
def __repr__(self):
return f'yfinance.Ticker object <{self.ticker}>'
def _download_options(self, date=None):
if date is None:
url = f"{_BASE_URL_}/v7/finance/options/{self.ticker}"
else:
url = f"{_BASE_URL_}/v7/finance/options/{self.ticker}?date={date}"
r = self._data.get(url=url, proxy=self.proxy).json()
if len(r.get('optionChain', {}).get('result', [])) > 0:
for exp in r['optionChain']['result'][0]['expirationDates']:
self._expirations[_datetime.datetime.utcfromtimestamp(
exp).strftime('%Y-%m-%d')] = exp
self._underlying = r['optionChain']['result'][0].get('quote', {})
opt = r['optionChain']['result'][0].get('options', [])
return dict(**opt[0],underlying=self._underlying) if len(opt) > 0 else {}
return {}
def _options2df(self, opt, tz=None):
data = _pd.DataFrame(opt).reindex(columns=[
'contractSymbol',
'lastTradeDate',
'strike',
'lastPrice',
'bid',
'ask',
'change',
'percentChange',
'volume',
'openInterest',
'impliedVolatility',
'inTheMoney',
'contractSize',
'currency'])
data['lastTradeDate'] = _pd.to_datetime(
data['lastTradeDate'], unit='s', utc=True)
if tz is not None:
data['lastTradeDate'] = data['lastTradeDate'].dt.tz_convert(tz)
return data
def option_chain(self, date=None, tz=None):
if date is None:
options = self._download_options()
else:
if not self._expirations:
self._download_options()
if date not in self._expirations:
raise ValueError(
f"Expiration `{date}` cannot be found. "
f"Available expirations are: [{', '.join(self._expirations)}]")
date = self._expirations[date]
options = self._download_options(date)
return _namedtuple('Options', ['calls', 'puts', 'underlying'])(**{
"calls": self._options2df(options['calls'], tz=tz),
"puts": self._options2df(options['puts'], tz=tz),
"underlying": options['underlying']
})
# ------------------------
@property
def isin(self):
return self.get_isin()
@property
def major_holders(self) -> _pd.DataFrame:
return self.get_major_holders()
@property
def institutional_holders(self) -> _pd.DataFrame:
return self.get_institutional_holders()
@property
def mutualfund_holders(self) -> _pd.DataFrame:
return self.get_mutualfund_holders()
@property
def insider_purchases(self) -> _pd.DataFrame:
return self.get_insider_purchases()
@property
def insider_transactions(self) -> _pd.DataFrame:
return self.get_insider_transactions()
@property
def insider_roster_holders(self) -> _pd.DataFrame:
return self.get_insider_roster_holders()
@property
def dividends(self) -> _pd.Series:
return self.get_dividends()
@property
def capital_gains(self) -> _pd.Series:
return self.get_capital_gains()
@property
def splits(self) -> _pd.Series:
return self.get_splits()
@property
def actions(self) -> _pd.DataFrame:
return self.get_actions()
@property
def shares(self) -> _pd.DataFrame:
return self.get_shares()
@property
def info(self) -> dict:
return self.get_info()
@property
def fast_info(self):
return self.get_fast_info()
@property
def calendar(self) -> dict:
"""
Returns a dictionary of events, earnings, and dividends for the ticker
"""
return self.get_calendar()
@property
def recommendations(self):
return self.get_recommendations()
@property
def recommendations_summary(self):
return self.get_recommendations_summary()
@property
def upgrades_downgrades(self):
return self.get_upgrades_downgrades()
@property
def earnings(self) -> _pd.DataFrame:
return self.get_earnings()
@property
def quarterly_earnings(self) -> _pd.DataFrame:
return self.get_earnings(freq='quarterly')
@property
def income_stmt(self) -> _pd.DataFrame:
return self.get_income_stmt(pretty=True)
@property
def quarterly_income_stmt(self) -> _pd.DataFrame:
return self.get_income_stmt(pretty=True, freq='quarterly')
@property
def incomestmt(self) -> _pd.DataFrame:
return self.income_stmt
@property
def quarterly_incomestmt(self) -> _pd.DataFrame:
return self.quarterly_income_stmt
@property
def financials(self) -> _pd.DataFrame:
return self.income_stmt
@property
def quarterly_financials(self) -> _pd.DataFrame:
return self.quarterly_income_stmt
@property
def balance_sheet(self) -> _pd.DataFrame:
return self.get_balance_sheet(pretty=True)
@property
def quarterly_balance_sheet(self) -> _pd.DataFrame:
return self.get_balance_sheet(pretty=True, freq='quarterly')
@property
def balancesheet(self) -> _pd.DataFrame:
return self.balance_sheet
@property
def quarterly_balancesheet(self) -> _pd.DataFrame:
return self.quarterly_balance_sheet
@property
def cash_flow(self) -> _pd.DataFrame:
return self.get_cash_flow(pretty=True, freq="yearly")
@property
def quarterly_cash_flow(self) -> _pd.DataFrame:
return self.get_cash_flow(pretty=True, freq='quarterly')
@property
def cashflow(self) -> _pd.DataFrame:
return self.cash_flow
@property
def quarterly_cashflow(self) -> _pd.DataFrame:
return self.quarterly_cash_flow
@property
def analyst_price_target(self) -> _pd.DataFrame:
return self.get_analyst_price_target()
@property
def revenue_forecasts(self) -> _pd.DataFrame:
return self.get_rev_forecast()
@property
def sustainability(self) -> _pd.DataFrame:
return self.get_sustainability()
@property
def options(self) -> tuple:
if not self._expirations:
self._download_options()
return tuple(self._expirations.keys())
@property
def news(self) -> list:
return self.get_news()
@property
def trend_details(self) -> _pd.DataFrame:
return self.get_trend_details()
@property
def earnings_trend(self) -> _pd.DataFrame:
return self.get_earnings_trend()
@property
def earnings_dates(self) -> _pd.DataFrame:
return self.get_earnings_dates()
@property
def earnings_forecasts(self) -> _pd.DataFrame:
return self.get_earnings_forecast()
@property
def history_metadata(self) -> dict:
return self.get_history_metadata()
| (ticker, session=None, proxy=None) |
723,610 | yfinance.ticker | __init__ | null | def __init__(self, ticker, session=None, proxy=None):
super(Ticker, self).__init__(ticker, session=session, proxy=proxy)
self._expirations = {}
self._underlying = {}
| (self, ticker, session=None, proxy=None) |
723,611 | yfinance.ticker | __repr__ | null | def __repr__(self):
return f'yfinance.Ticker object <{self.ticker}>'
| (self) |
723,612 | yfinance.ticker | _download_options | null | def _download_options(self, date=None):
if date is None:
url = f"{_BASE_URL_}/v7/finance/options/{self.ticker}"
else:
url = f"{_BASE_URL_}/v7/finance/options/{self.ticker}?date={date}"
r = self._data.get(url=url, proxy=self.proxy).json()
if len(r.get('optionChain', {}).get('result', [])) > 0:
for exp in r['optionChain']['result'][0]['expirationDates']:
self._expirations[_datetime.datetime.utcfromtimestamp(
exp).strftime('%Y-%m-%d')] = exp
self._underlying = r['optionChain']['result'][0].get('quote', {})
opt = r['optionChain']['result'][0].get('options', [])
return dict(**opt[0],underlying=self._underlying) if len(opt) > 0 else {}
return {}
| (self, date=None) |
723,613 | yfinance.utils | wrapper | null | def log_indent_decorator(func):
def wrapper(*args, **kwargs):
logger = get_indented_logger('yfinance')
logger.debug(f'Entering {func.__name__}()')
with IndentationContext():
result = func(*args, **kwargs)
logger.debug(f'Exiting {func.__name__}()')
return result
return wrapper
| (*args, **kwargs) |
723,614 | yfinance.base | _get_ticker_tz | null | def _get_ticker_tz(self, proxy, timeout):
proxy = proxy or self.proxy
if self._tz is not None:
return self._tz
c = cache.get_tz_cache()
tz = c.lookup(self.ticker)
if tz and not utils.is_valid_timezone(tz):
# Clear from cache and force re-fetch
c.store(self.ticker, None)
tz = None
if tz is None:
tz = self._fetch_ticker_tz(proxy, timeout)
if utils.is_valid_timezone(tz):
# info fetch is relatively slow so cache timezone
c.store(self.ticker, tz)
else:
tz = None
self._tz = tz
return tz
| (self, proxy, timeout) |
723,615 | yfinance.base | _lazy_load_price_history | null | def _lazy_load_price_history(self):
if self._price_history is None:
self._price_history = PriceHistory(self._data, self.ticker, self._get_ticker_tz(self.proxy, timeout=10))
return self._price_history
| (self) |
723,616 | yfinance.ticker | _options2df | null | def _options2df(self, opt, tz=None):
data = _pd.DataFrame(opt).reindex(columns=[
'contractSymbol',
'lastTradeDate',
'strike',
'lastPrice',
'bid',
'ask',
'change',
'percentChange',
'volume',
'openInterest',
'impliedVolatility',
'inTheMoney',
'contractSize',
'currency'])
data['lastTradeDate'] = _pd.to_datetime(
data['lastTradeDate'], unit='s', utc=True)
if tz is not None:
data['lastTradeDate'] = data['lastTradeDate'].dt.tz_convert(tz)
return data
| (self, opt, tz=None) |
723,617 | yfinance.base | get_actions | null | def get_actions(self, proxy=None) -> pd.Series:
return self._lazy_load_price_history().get_actions(proxy)
| (self, proxy=None) -> pandas.core.series.Series |
723,618 | yfinance.base | get_analyst_price_target | null | def get_analyst_price_target(self, proxy=None, as_dict=False):
self._analysis.proxy = proxy or self.proxy
data = self._analysis.analyst_price_target
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,619 | yfinance.base | get_balance_sheet |
:Parameters:
as_dict: bool
Return table as Python dict
Default is False
pretty: bool
Format row names nicely for readability
Default is False
freq: str
"yearly" or "quarterly"
Default is "yearly"
proxy: str
Optional. Proxy server URL scheme
Default is None
| def get_balance_sheet(self, proxy=None, as_dict=False, pretty=False, freq="yearly"):
"""
:Parameters:
as_dict: bool
Return table as Python dict
Default is False
pretty: bool
Format row names nicely for readability
Default is False
freq: str
"yearly" or "quarterly"
Default is "yearly"
proxy: str
Optional. Proxy server URL scheme
Default is None
"""
self._fundamentals.proxy = proxy or self.proxy
data = self._fundamentals.financials.get_balance_sheet_time_series(freq=freq, proxy=proxy)
if pretty:
data = data.copy()
data.index = utils.camel2title(data.index, sep=' ', acronyms=["PPE"])
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False, pretty=False, freq='yearly') |
723,620 | yfinance.base | get_balancesheet | null | def get_balancesheet(self, proxy=None, as_dict=False, pretty=False, freq="yearly"):
return self.get_balance_sheet(proxy, as_dict, pretty, freq)
| (self, proxy=None, as_dict=False, pretty=False, freq='yearly') |
723,621 | yfinance.base | get_calendar | null | def get_calendar(self, proxy=None) -> dict:
self._quote.proxy = proxy or self.proxy
return self._quote.calendar
| (self, proxy=None) -> dict |
723,622 | yfinance.base | get_capital_gains | null | def get_capital_gains(self, proxy=None) -> pd.Series:
return self._lazy_load_price_history().get_capital_gains(proxy)
| (self, proxy=None) -> pandas.core.series.Series |
723,623 | yfinance.base | get_cash_flow |
:Parameters:
as_dict: bool
Return table as Python dict
Default is False
pretty: bool
Format row names nicely for readability
Default is False
freq: str
"yearly" or "quarterly"
Default is "yearly"
proxy: str
Optional. Proxy server URL scheme
Default is None
| def get_cash_flow(self, proxy=None, as_dict=False, pretty=False, freq="yearly") -> Union[pd.DataFrame, dict]:
"""
:Parameters:
as_dict: bool
Return table as Python dict
Default is False
pretty: bool
Format row names nicely for readability
Default is False
freq: str
"yearly" or "quarterly"
Default is "yearly"
proxy: str
Optional. Proxy server URL scheme
Default is None
"""
self._fundamentals.proxy = proxy or self.proxy
data = self._fundamentals.financials.get_cash_flow_time_series(freq=freq, proxy=proxy)
if pretty:
data = data.copy()
data.index = utils.camel2title(data.index, sep=' ', acronyms=["PPE"])
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False, pretty=False, freq='yearly') -> Union[pandas.core.frame.DataFrame, dict] |
723,624 | yfinance.base | get_cashflow | null | def get_cashflow(self, proxy=None, as_dict=False, pretty=False, freq="yearly"):
return self.get_cash_flow(proxy, as_dict, pretty, freq)
| (self, proxy=None, as_dict=False, pretty=False, freq='yearly') |
723,625 | yfinance.base | get_dividends | null | def get_dividends(self, proxy=None) -> pd.Series:
return self._lazy_load_price_history().get_dividends(proxy)
| (self, proxy=None) -> pandas.core.series.Series |
723,626 | yfinance.base | get_earnings |
:Parameters:
as_dict: bool
Return table as Python dict
Default is False
freq: str
"yearly" or "quarterly"
Default is "yearly"
proxy: str
Optional. Proxy server URL scheme
Default is None
| def get_earnings(self, proxy=None, as_dict=False, freq="yearly"):
"""
:Parameters:
as_dict: bool
Return table as Python dict
Default is False
freq: str
"yearly" or "quarterly"
Default is "yearly"
proxy: str
Optional. Proxy server URL scheme
Default is None
"""
self._fundamentals.proxy = proxy or self.proxy
data = self._fundamentals.earnings[freq]
if as_dict:
dict_data = data.to_dict()
dict_data['financialCurrency'] = 'USD' if 'financialCurrency' not in self._earnings else self._earnings[
'financialCurrency']
return dict_data
return data
| (self, proxy=None, as_dict=False, freq='yearly') |
723,628 | yfinance.base | get_earnings_forecast | null | def get_earnings_forecast(self, proxy=None, as_dict=False):
self._analysis.proxy = proxy or self.proxy
data = self._analysis.eps_est
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,629 | yfinance.base | get_earnings_trend | null | def get_earnings_trend(self, proxy=None, as_dict=False):
self._analysis.proxy = proxy or self.proxy
data = self._analysis.earnings_trend
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,630 | yfinance.base | get_fast_info | null | def get_fast_info(self, proxy=None):
if self._fast_info is None:
self._fast_info = FastInfo(self, proxy=proxy)
return self._fast_info
| (self, proxy=None) |
723,631 | yfinance.base | get_financials | null | def get_financials(self, proxy=None, as_dict=False, pretty=False, freq="yearly"):
return self.get_income_stmt(proxy, as_dict, pretty, freq)
| (self, proxy=None, as_dict=False, pretty=False, freq='yearly') |
723,632 | yfinance.base | get_history_metadata | null | def get_history_metadata(self, proxy=None) -> dict:
return self._lazy_load_price_history().get_history_metadata(proxy)
| (self, proxy=None) -> dict |
723,633 | yfinance.base | get_income_stmt |
:Parameters:
as_dict: bool
Return table as Python dict
Default is False
pretty: bool
Format row names nicely for readability
Default is False
freq: str
"yearly" or "quarterly"
Default is "yearly"
proxy: str
Optional. Proxy server URL scheme
Default is None
| def get_income_stmt(self, proxy=None, as_dict=False, pretty=False, freq="yearly"):
"""
:Parameters:
as_dict: bool
Return table as Python dict
Default is False
pretty: bool
Format row names nicely for readability
Default is False
freq: str
"yearly" or "quarterly"
Default is "yearly"
proxy: str
Optional. Proxy server URL scheme
Default is None
"""
self._fundamentals.proxy = proxy or self.proxy
data = self._fundamentals.financials.get_income_time_series(freq=freq, proxy=proxy)
if pretty:
data = data.copy()
data.index = utils.camel2title(data.index, sep=' ', acronyms=["EBIT", "EBITDA", "EPS", "NI"])
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False, pretty=False, freq='yearly') |
723,634 | yfinance.base | get_incomestmt | null | def get_incomestmt(self, proxy=None, as_dict=False, pretty=False, freq="yearly"):
return self.get_income_stmt(proxy, as_dict, pretty, freq)
| (self, proxy=None, as_dict=False, pretty=False, freq='yearly') |
723,635 | yfinance.base | get_info | null | def get_info(self, proxy=None) -> dict:
self._quote.proxy = proxy or self.proxy
data = self._quote.info
return data
| (self, proxy=None) -> dict |
723,636 | yfinance.base | get_insider_purchases | null | def get_insider_purchases(self, proxy=None, as_dict=False):
self._holders.proxy = proxy or self.proxy
data = self._holders.insider_purchases
if data is not None:
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,637 | yfinance.base | get_insider_roster_holders | null | def get_insider_roster_holders(self, proxy=None, as_dict=False):
self._holders.proxy = proxy or self.proxy
data = self._holders.insider_roster
if data is not None:
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,638 | yfinance.base | get_insider_transactions | null | def get_insider_transactions(self, proxy=None, as_dict=False):
self._holders.proxy = proxy or self.proxy
data = self._holders.insider_transactions
if data is not None:
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,639 | yfinance.base | get_institutional_holders | null | def get_institutional_holders(self, proxy=None, as_dict=False):
self._holders.proxy = proxy or self.proxy
data = self._holders.institutional
if data is not None:
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,640 | yfinance.base | get_isin | null | def get_isin(self, proxy=None) -> Optional[str]:
# *** experimental ***
if self._isin is not None:
return self._isin
ticker = self.ticker.upper()
if "-" in ticker or "^" in ticker:
self._isin = '-'
return self._isin
q = ticker
self._quote.proxy = proxy or self.proxy
if self._quote.info is None:
# Don't print error message cause self._quote.info will print one
return None
if "shortName" in self._quote.info:
q = self._quote.info['shortName']
url = f'https://markets.businessinsider.com/ajax/SearchController_Suggest?max_results=25&query={urlencode(q)}'
data = self._data.cache_get(url=url, proxy=proxy).text
search_str = f'"{ticker}|'
if search_str not in data:
if q.lower() in data.lower():
search_str = '"|'
if search_str not in data:
self._isin = '-'
return self._isin
else:
self._isin = '-'
return self._isin
self._isin = data.split(search_str)[1].split('"')[0].split('|')[0]
return self._isin
| (self, proxy=None) -> Optional[str] |
723,641 | yfinance.base | get_major_holders | null | def get_major_holders(self, proxy=None, as_dict=False):
self._holders.proxy = proxy or self.proxy
data = self._holders.major
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,642 | yfinance.base | get_mutualfund_holders | null | def get_mutualfund_holders(self, proxy=None, as_dict=False):
self._holders.proxy = proxy or self.proxy
data = self._holders.mutualfund
if data is not None:
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,643 | yfinance.base | get_news | null | def get_news(self, proxy=None) -> list:
if self._news:
return self._news
# Getting data from json
url = f"{_BASE_URL_}/v1/finance/search?q={self.ticker}"
data = self._data.cache_get(url=url, proxy=proxy)
if "Will be right back" in data.text:
raise RuntimeError("*** YAHOO! FINANCE IS CURRENTLY DOWN! ***\n"
"Our engineers are working quickly to resolve "
"the issue. Thank you for your patience.")
data = data.json()
# parse news
self._news = data.get("news", [])
return self._news
| (self, proxy=None) -> list |
723,644 | yfinance.base | get_recommendations |
Returns a DataFrame with the recommendations
Columns: period strongBuy buy hold sell strongSell
| def get_recommendations(self, proxy=None, as_dict=False):
"""
Returns a DataFrame with the recommendations
Columns: period strongBuy buy hold sell strongSell
"""
self._quote.proxy = proxy or self.proxy
data = self._quote.recommendations
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,645 | yfinance.base | get_recommendations_summary | null | def get_recommendations_summary(self, proxy=None, as_dict=False):
return self.get_recommendations(proxy=proxy, as_dict=as_dict)
| (self, proxy=None, as_dict=False) |
723,646 | yfinance.base | get_rev_forecast | null | def get_rev_forecast(self, proxy=None, as_dict=False):
self._analysis.proxy = proxy or self.proxy
data = self._analysis.rev_est
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,647 | yfinance.base | get_shares | null | def get_shares(self, proxy=None, as_dict=False) -> Union[pd.DataFrame, dict]:
self._fundamentals.proxy = proxy or self.proxy
data = self._fundamentals.shares
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) -> Union[pandas.core.frame.DataFrame, dict] |
723,649 | yfinance.base | get_splits | null | def get_splits(self, proxy=None) -> pd.Series:
return self._lazy_load_price_history().get_splits(proxy)
| (self, proxy=None) -> pandas.core.series.Series |
723,650 | yfinance.base | get_sustainability | null | def get_sustainability(self, proxy=None, as_dict=False):
self._quote.proxy = proxy or self.proxy
data = self._quote.sustainability
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,651 | yfinance.base | get_trend_details | null | def get_trend_details(self, proxy=None, as_dict=False):
self._analysis.proxy = proxy or self.proxy
data = self._analysis.analyst_trend_details
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,652 | yfinance.base | get_upgrades_downgrades |
Returns a DataFrame with the recommendations changes (upgrades/downgrades)
Index: date of grade
Columns: firm toGrade fromGrade action
| def get_upgrades_downgrades(self, proxy=None, as_dict=False):
"""
Returns a DataFrame with the recommendations changes (upgrades/downgrades)
Index: date of grade
Columns: firm toGrade fromGrade action
"""
self._quote.proxy = proxy or self.proxy
data = self._quote.upgrades_downgrades
if as_dict:
return data.to_dict()
return data
| (self, proxy=None, as_dict=False) |
723,654 | yfinance.ticker | option_chain | null | def option_chain(self, date=None, tz=None):
if date is None:
options = self._download_options()
else:
if not self._expirations:
self._download_options()
if date not in self._expirations:
raise ValueError(
f"Expiration `{date}` cannot be found. "
f"Available expirations are: [{', '.join(self._expirations)}]")
date = self._expirations[date]
options = self._download_options(date)
return _namedtuple('Options', ['calls', 'puts', 'underlying'])(**{
"calls": self._options2df(options['calls'], tz=tz),
"puts": self._options2df(options['puts'], tz=tz),
"underlying": options['underlying']
})
| (self, date=None, tz=None) |
723,655 | yfinance.tickers | Tickers | null | class Tickers:
def __repr__(self):
return f"yfinance.Tickers object <{','.join(self.symbols)}>"
def __init__(self, tickers, session=None):
tickers = tickers if isinstance(
tickers, list) else tickers.replace(',', ' ').split()
self.symbols = [ticker.upper() for ticker in tickers]
self.tickers = {ticker: Ticker(ticker, session=session) for ticker in self.symbols}
# self.tickers = _namedtuple(
# "Tickers", ticker_objects.keys(), rename=True
# )(*ticker_objects.values())
def history(self, period="1mo", interval="1d",
start=None, end=None, prepost=False,
actions=True, auto_adjust=True, repair=False,
proxy=None,
threads=True, group_by='column', progress=True,
timeout=10, **kwargs):
return self.download(
period, interval,
start, end, prepost,
actions, auto_adjust, repair,
proxy,
threads, group_by, progress,
timeout, **kwargs)
def download(self, period="1mo", interval="1d",
start=None, end=None, prepost=False,
actions=True, auto_adjust=True, repair=False,
proxy=None,
threads=True, group_by='column', progress=True,
timeout=10, **kwargs):
data = multi.download(self.symbols,
start=start, end=end,
actions=actions,
auto_adjust=auto_adjust,
repair=repair,
period=period,
interval=interval,
prepost=prepost,
proxy=proxy,
group_by='ticker',
threads=threads,
progress=progress,
timeout=timeout,
**kwargs)
for symbol in self.symbols:
self.tickers.get(symbol, {})._history = data[symbol]
if group_by == 'column':
data.columns = data.columns.swaplevel(0, 1)
data.sort_index(level=0, axis=1, inplace=True)
return data
def news(self):
return {ticker: [item for item in Ticker(ticker).news] for ticker in self.symbols}
| (tickers, session=None) |
723,656 | yfinance.tickers | __init__ | null | def __init__(self, tickers, session=None):
tickers = tickers if isinstance(
tickers, list) else tickers.replace(',', ' ').split()
self.symbols = [ticker.upper() for ticker in tickers]
self.tickers = {ticker: Ticker(ticker, session=session) for ticker in self.symbols}
# self.tickers = _namedtuple(
# "Tickers", ticker_objects.keys(), rename=True
# )(*ticker_objects.values())
| (self, tickers, session=None) |
723,657 | yfinance.tickers | __repr__ | null | def __repr__(self):
return f"yfinance.Tickers object <{','.join(self.symbols)}>"
| (self) |
723,658 | yfinance.tickers | download | null | def download(self, period="1mo", interval="1d",
start=None, end=None, prepost=False,
actions=True, auto_adjust=True, repair=False,
proxy=None,
threads=True, group_by='column', progress=True,
timeout=10, **kwargs):
data = multi.download(self.symbols,
start=start, end=end,
actions=actions,
auto_adjust=auto_adjust,
repair=repair,
period=period,
interval=interval,
prepost=prepost,
proxy=proxy,
group_by='ticker',
threads=threads,
progress=progress,
timeout=timeout,
**kwargs)
for symbol in self.symbols:
self.tickers.get(symbol, {})._history = data[symbol]
if group_by == 'column':
data.columns = data.columns.swaplevel(0, 1)
data.sort_index(level=0, axis=1, inplace=True)
return data
| (self, period='1mo', interval='1d', start=None, end=None, prepost=False, actions=True, auto_adjust=True, repair=False, proxy=None, threads=True, group_by='column', progress=True, timeout=10, **kwargs) |
723,659 | yfinance.tickers | history | null | def history(self, period="1mo", interval="1d",
start=None, end=None, prepost=False,
actions=True, auto_adjust=True, repair=False,
proxy=None,
threads=True, group_by='column', progress=True,
timeout=10, **kwargs):
return self.download(
period, interval,
start, end, prepost,
actions, auto_adjust, repair,
proxy,
threads, group_by, progress,
timeout, **kwargs)
| (self, period='1mo', interval='1d', start=None, end=None, prepost=False, actions=True, auto_adjust=True, repair=False, proxy=None, threads=True, group_by='column', progress=True, timeout=10, **kwargs) |
723,660 | yfinance.tickers | news | null | def news(self):
return {ticker: [item for item in Ticker(ticker).news] for ticker in self.symbols}
| (self) |
723,666 | yfinance.utils | enable_debug_mode | null | def enable_debug_mode():
get_yf_logger().setLevel(logging.DEBUG)
setup_debug_formatting()
| () |
723,669 | yfinance | pdr_override |
make pandas datareader optional
otherwise can be called via fix_yahoo_finance.download(...)
| def pdr_override():
"""
make pandas datareader optional
otherwise can be called via fix_yahoo_finance.download(...)
"""
try:
import pandas_datareader
pandas_datareader.data.get_data_yahoo = download
pandas_datareader.data.get_data_yahoo_actions = download
pandas_datareader.data.DataReader = download
except Exception:
pass
| () |
723,671 | yfinance.cache | set_tz_cache_location | null | def set_tz_cache_location(cache_dir: str):
set_cache_location(cache_dir)
| (cache_dir: str) |
723,680 | zappa | running_in_docker |
Determine if zappa is running in docker.
- When docker is used allow usage of any python version
| def running_in_docker() -> bool:
"""
Determine if zappa is running in docker.
- When docker is used allow usage of any python version
"""
# https://stackoverflow.com/questions/63116419
running_in_docker_flag = os.getenv("ZAPPA_RUNNING_IN_DOCKER", "False").lower() in {"y", "yes", "t", "true", "1"}
return running_in_docker_flag
| () -> bool |
723,682 | inflector.languages.english | English |
Inflector for pluralize and singularize English nouns.
This is the default Inflector for the Inflector obj
| class English(Base):
"""
Inflector for pluralize and singularize English nouns.
This is the default Inflector for the Inflector obj
"""
def pluralize(self, word) :
'''Pluralizes English nouns.'''
rules = [
['(?i)(quiz)$' , '\\1zes'],
['(?i)^(ox)$' , '\\1en'],
['(?i)([m|l])ouse$' , '\\1ice'],
['(?i)(matr|vert|ind)ix|ex$' , '\\1ices'],
['(?i)(x|ch|ss|sh)$' , '\\1es'],
['(?i)([^aeiouy]|qu)ies$' , '\\1y'],
['(?i)([^aeiouy]|qu)y$' , '\\1ies'],
['(?i)(hive)$' , '\\1s'],
['(?i)(?:([^f])fe|([lr])f)$' , '\\1\\2ves'],
['(?i)sis$' , 'ses'],
['(?i)([ti])um$' , '\\1a'],
['(?i)(buffal|tomat)o$' , '\\1oes'],
['(?i)(bu)s$' , '\\1ses'],
['(?i)(alias|status)' , '\\1es'],
['(?i)(octop|vir)us$' , '\\1i'],
['(?i)(ax|test)is$' , '\\1es'],
['(?i)s$' , 's'],
['(?i)$' , 's']
]
uncountable_words = ['equipment', 'information', 'rice', 'money',
'species', 'series', 'fish', 'sheep', 'deer', 'moose']
irregular_words = {
'person' : 'people',
'man' : 'men',
'child' : 'children',
'sex' : 'sexes',
'move' : 'moves',
'staff' : 'staves',
'foot' : 'feet',
'goose' : 'geese',
}
lower_cased_word = word.lower()
for uncountable_word in uncountable_words:
if lower_cased_word[-1*len(uncountable_word):] == uncountable_word :
return word
for irregular in irregular_words.keys():
match = re.search('('+irregular+')$',word, re.IGNORECASE)
if match:
return re.sub('(?i)'+irregular+'$', match.expand('\\1')[0]+irregular_words[irregular][1:], word)
for rule in range(len(rules)):
match = re.search(rules[rule][0], word, re.IGNORECASE)
if match :
groups = match.groups()
for k in range(0,len(groups)) :
if groups[k] is None :
rules[rule][1] = rules[rule][1].replace('\\'+str(k+1), '')
return re.sub(rules[rule][0], rules[rule][1], word)
return word
def singularize(self, word) :
'''Singularizes English nouns.'''
rules = [
['(?i)(quiz)zes$' , '\\1'],
['(?i)(matr)ices$' , '\\1ix'],
['(?i)(vert|ind)ices$' , '\\1ex'],
['(?i)^(ox)en' , '\\1'],
['(?i)(alias|status)es$' , '\\1'],
['(?i)([octop|vir])i$' , '\\1us'],
['(?i)(cris|ax|test)es$' , '\\1is'],
['(?i)(shoe)s$' , '\\1'],
['(?i)(o)es$' , '\\1'],
['(?i)(bus)es$' , '\\1'],
['(?i)([m|l])ice$' , '\\1ouse'],
['(?i)(x|ch|ss|sh)es$' , '\\1'],
['(?i)(m)ovies$' , '\\1ovie'],
['(?i)(s)eries$' , '\\1eries'],
['(?i)([^aeiouy]|qu)ies$' , '\\1y'],
['(?i)([lr])ves$' , '\\1f'],
['(?i)(tive)s$' , '\\1'],
['(?i)(hive)s$' , '\\1'],
['(?i)([^f])ves$' , '\\1fe'],
['(?i)(^analy)ses$' , '\\1sis'],
['(?i)((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$' , '\\1\\2sis'],
['(?i)([ti])a$' , '\\1um'],
['(?i)(n)ews$' , '\\1ews'],
['(?i)s$' , ''],
]
uncountable_words = ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep','sms']
irregular_words = {
'people' : 'person',
'men' : 'man',
'children' : 'child',
'sexes' : 'sex',
'moves' : 'move'
}
lower_cased_word = word.lower()
for uncountable_word in uncountable_words:
if lower_cased_word[-1*len(uncountable_word):] == uncountable_word :
return word
for irregular in irregular_words.keys():
match = re.search('('+irregular+')$',word, re.IGNORECASE)
if match:
return re.sub('(?i)'+irregular+'$', match.expand('\\1')[0]+irregular_words[irregular][1:], word)
for rule in range(len(rules)):
match = re.search(rules[rule][0], word, re.IGNORECASE)
if match :
groups = match.groups()
for k in range(0,len(groups)) :
if groups[k] is None :
rules[rule][1] = rules[rule][1].replace('\\'+str(k+1), '')
return re.sub(rules[rule][0], rules[rule][1], word)
return word
| () |
723,683 | inflector.languages.base | camelize | Returns given word as CamelCased
Converts a word like "send_email" to "SendEmail". It
will remove non alphanumeric character from the word, so
"who's online" will be converted to "WhoSOnline" | def camelize(self, word):
''' Returns given word as CamelCased
Converts a word like "send_email" to "SendEmail". It
will remove non alphanumeric character from the word, so
"who's online" will be converted to "WhoSOnline"'''
return ''.join(w[0].upper() + w[1:] for w in re.sub('[^A-Z^a-z^0-9^:]+', ' ', word).split(' '))
| (self, word) |
723,684 | inflector.languages.base | classify | Converts a table name to its class name according to rails
naming conventions. Example: Converts "people" to "Person" | def classify(self, table_name):
'''Converts a table name to its class name according to rails
naming conventions. Example: Converts "people" to "Person" '''
return self.camelize(self.singularize(table_name))
| (self, table_name) |
723,685 | inflector.languages.base | conditional_plural | Returns the plural form of a word if first parameter is greater than 1 | def conditional_plural(self, number_of_records, word):
'''Returns the plural form of a word if first parameter is greater than 1'''
if number_of_records > 1:
return self.pluralize(word)
else:
return word
| (self, number_of_records, word) |
723,686 | inflector.languages.base | demodulize | null | def demodulize(self, module_name):
return self.humanize(self.underscore(re.sub('^.*::', '', module_name)))
| (self, module_name) |
723,687 | inflector.languages.base | foreign_key | Returns class_name in underscored form, with "_id" tacked on at the end.
This is for use in dealing with the database. | def foreign_key(self, class_name, separate_class_name_and_id_with_underscore=1):
''' Returns class_name in underscored form, with "_id" tacked on at the end.
This is for use in dealing with the database.'''
if separate_class_name_and_id_with_underscore:
tail = '_id'
else:
tail = 'id'
return self.underscore(self.demodulize(class_name)) + tail
| (self, class_name, separate_class_name_and_id_with_underscore=1) |
723,688 | inflector.languages.base | humanize | Returns a human-readable string from word
Returns a human-readable string from word, by replacing
underscores with a space, and by upper-casing the initial
character by default.
If you need to uppercase all the words you just have to
pass 'all' as a second parameter. | def humanize(self, word, uppercase=''):
'''Returns a human-readable string from word
Returns a human-readable string from word, by replacing
underscores with a space, and by upper-casing the initial
character by default.
If you need to uppercase all the words you just have to
pass 'all' as a second parameter.'''
if uppercase == 'first':
return re.sub('_id$', '', word).replace('_', ' ').capitalize()
else:
return re.sub('_id$', '', word).replace('_', ' ').title()
| (self, word, uppercase='') |
723,689 | inflector.languages.base | modulize | null | def modulize(self, module_description):
return self.camelize(self.singularize(module_description))
| (self, module_description) |
723,690 | inflector.languages.base | ordinalize | Converts number to its ordinal English form.
This method converts 13 to 13th, 2 to 2nd ... | def ordinalize(self, number):
'''Converts number to its ordinal English form.
This method converts 13 to 13th, 2 to 2nd ...'''
tail = 'th'
if number % 100 == 11 or number % 100 == 12 or number % 100 == 13:
tail = 'th'
elif number % 10 == 1:
tail = 'st'
elif number % 10 == 2:
tail = 'nd'
elif number % 10 == 3:
tail = 'rd'
return str(number) + tail
| (self, number) |
723,691 | inflector.languages.english | pluralize | Pluralizes English nouns. | def pluralize(self, word) :
'''Pluralizes English nouns.'''
rules = [
['(?i)(quiz)$' , '\\1zes'],
['(?i)^(ox)$' , '\\1en'],
['(?i)([m|l])ouse$' , '\\1ice'],
['(?i)(matr|vert|ind)ix|ex$' , '\\1ices'],
['(?i)(x|ch|ss|sh)$' , '\\1es'],
['(?i)([^aeiouy]|qu)ies$' , '\\1y'],
['(?i)([^aeiouy]|qu)y$' , '\\1ies'],
['(?i)(hive)$' , '\\1s'],
['(?i)(?:([^f])fe|([lr])f)$' , '\\1\\2ves'],
['(?i)sis$' , 'ses'],
['(?i)([ti])um$' , '\\1a'],
['(?i)(buffal|tomat)o$' , '\\1oes'],
['(?i)(bu)s$' , '\\1ses'],
['(?i)(alias|status)' , '\\1es'],
['(?i)(octop|vir)us$' , '\\1i'],
['(?i)(ax|test)is$' , '\\1es'],
['(?i)s$' , 's'],
['(?i)$' , 's']
]
uncountable_words = ['equipment', 'information', 'rice', 'money',
'species', 'series', 'fish', 'sheep', 'deer', 'moose']
irregular_words = {
'person' : 'people',
'man' : 'men',
'child' : 'children',
'sex' : 'sexes',
'move' : 'moves',
'staff' : 'staves',
'foot' : 'feet',
'goose' : 'geese',
}
lower_cased_word = word.lower()
for uncountable_word in uncountable_words:
if lower_cased_word[-1*len(uncountable_word):] == uncountable_word :
return word
for irregular in irregular_words.keys():
match = re.search('('+irregular+')$',word, re.IGNORECASE)
if match:
return re.sub('(?i)'+irregular+'$', match.expand('\\1')[0]+irregular_words[irregular][1:], word)
for rule in range(len(rules)):
match = re.search(rules[rule][0], word, re.IGNORECASE)
if match :
groups = match.groups()
for k in range(0,len(groups)) :
if groups[k] is None :
rules[rule][1] = rules[rule][1].replace('\\'+str(k+1), '')
return re.sub(rules[rule][0], rules[rule][1], word)
return word
| (self, word) |
723,692 | inflector.languages.english | singularize | Singularizes English nouns. | def singularize(self, word) :
'''Singularizes English nouns.'''
rules = [
['(?i)(quiz)zes$' , '\\1'],
['(?i)(matr)ices$' , '\\1ix'],
['(?i)(vert|ind)ices$' , '\\1ex'],
['(?i)^(ox)en' , '\\1'],
['(?i)(alias|status)es$' , '\\1'],
['(?i)([octop|vir])i$' , '\\1us'],
['(?i)(cris|ax|test)es$' , '\\1is'],
['(?i)(shoe)s$' , '\\1'],
['(?i)(o)es$' , '\\1'],
['(?i)(bus)es$' , '\\1'],
['(?i)([m|l])ice$' , '\\1ouse'],
['(?i)(x|ch|ss|sh)es$' , '\\1'],
['(?i)(m)ovies$' , '\\1ovie'],
['(?i)(s)eries$' , '\\1eries'],
['(?i)([^aeiouy]|qu)ies$' , '\\1y'],
['(?i)([lr])ves$' , '\\1f'],
['(?i)(tive)s$' , '\\1'],
['(?i)(hive)s$' , '\\1'],
['(?i)([^f])ves$' , '\\1fe'],
['(?i)(^analy)ses$' , '\\1sis'],
['(?i)((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$' , '\\1\\2sis'],
['(?i)([ti])a$' , '\\1um'],
['(?i)(n)ews$' , '\\1ews'],
['(?i)s$' , ''],
]
uncountable_words = ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep','sms']
irregular_words = {
'people' : 'person',
'men' : 'man',
'children' : 'child',
'sexes' : 'sex',
'moves' : 'move'
}
lower_cased_word = word.lower()
for uncountable_word in uncountable_words:
if lower_cased_word[-1*len(uncountable_word):] == uncountable_word :
return word
for irregular in irregular_words.keys():
match = re.search('('+irregular+')$',word, re.IGNORECASE)
if match:
return re.sub('(?i)'+irregular+'$', match.expand('\\1')[0]+irregular_words[irregular][1:], word)
for rule in range(len(rules)):
match = re.search(rules[rule][0], word, re.IGNORECASE)
if match :
groups = match.groups()
for k in range(0,len(groups)) :
if groups[k] is None :
rules[rule][1] = rules[rule][1].replace('\\'+str(k+1), '')
return re.sub(rules[rule][0], rules[rule][1], word)
return word
| (self, word) |
723,693 | inflector.languages.base | string_replace | This function returns a copy of word, translating
all occurrences of each character in find to the
corresponding character in replace | def string_replace(self, word, find, replace):
'''This function returns a copy of word, translating
all occurrences of each character in find to the
corresponding character in replace'''
for k in range(0, len(find)):
word = re.sub(find[k], replace[k], word)
return word
| (self, word, find, replace) |
723,694 | inflector.languages.base | tableize | Converts a class name to its table name according to rails
naming conventions. Example. Converts "Person" to "people" | def tableize(self, class_name):
''' Converts a class name to its table name according to rails
naming conventions. Example. Converts "Person" to "people" '''
return self.pluralize(self.underscore(class_name))
| (self, class_name) |
723,695 | inflector.languages.base | titleize | Converts an underscored or CamelCase word into a English sentence.
The titleize function converts text like "WelcomePage",
"welcome_page" or "welcome page" to this "Welcome Page".
If second parameter is set to 'first' it will only
capitalize the first character of the title. | def titleize(self, word, uppercase=''):
'''Converts an underscored or CamelCase word into a English sentence.
The titleize function converts text like "WelcomePage",
"welcome_page" or "welcome page" to this "Welcome Page".
If second parameter is set to 'first' it will only
capitalize the first character of the title.'''
if uppercase == 'first':
return self.humanize(self.underscore(word)).capitalize()
else:
return self.humanize(self.underscore(word)).title()
| (self, word, uppercase='') |
723,696 | inflector.languages.base | unaccent | Transforms a string to its unaccented version.
This might be useful for generating "friendly" URLs | def unaccent(self, text):
'''Transforms a string to its unaccented version.
This might be useful for generating "friendly" URLs'''
# find = u'\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u00C6\u00C7\u00C8\u00C9\u00CA\u00CB\u00CC\u00CD\u00CE\u00CF\u00D0\u00D1\u00D2\u00D3\u00D4\u00D5\u00D6\u00D8\u00D9\u00DA\u00DB\u00DC\u00DD\u00DE\u00DF\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5\u00E6\u00E7\u00E8\u00E9\u00EA\u00EB\u00EC\u00ED\u00EE\u00EF\u00F0\u00F1\u00F2\u00F3\u00F4\u00F5\u00F6\u00F8\u00F9\u00FA\u00FB\u00FC\u00FD\u00FE\u00FF'
# replace = u'AAAAAAACEEEEIIIIDNOOOOOOUUUUYTsaaaaaaaceeeeiiiienoooooouuuuyty'
# return self.string_replace(text, find, replace)
s = unicodedata.normalize('NFD', text)
return ''.join((c for c in s if unicodedata.category(c) != 'Mn'))
| (self, text) |
723,697 | inflector.languages.base | underscore | Converts a word "into_it_s_underscored_version"
Convert any "CamelCased" or "ordinary Word" into an
"underscored_word".
This can be really useful for creating friendly URLs. | def underscore(self, word):
''' Converts a word "into_it_s_underscored_version"
Convert any "CamelCased" or "ordinary Word" into an
"underscored_word".
This can be really useful for creating friendly URLs.'''
return re.sub(r'[^A-Z^a-z^0-9^\/]+', '_', \
re.sub(r'([a-z\d])([A-Z])', '\\1_\\2', \
re.sub(r'([A-Z]+)([A-Z][a-z])', '\\1_\\2', re.sub(r'::', '/', word)))).lower()
| (self, word) |
723,698 | inflector.languages.base | urlize | Transform a string its unaccented and underscored
version ready to be inserted in friendly URLs | def urlize(self, text):
'''Transform a string its unaccented and underscored
version ready to be inserted in friendly URLs'''
return re.sub('^_|_$', '', self.underscore(self.unaccent(text)))
| (self, text) |
723,699 | inflector.languages.base | variablize | Same as camelize but first char is lowercased
Converts a word like "send_email" to "sendEmail". It
will remove non alphanumeric character from the word, so
"who's online" will be converted to "whoSOnline" | def variablize(self, word):
'''Same as camelize but first char is lowercased
Converts a word like "send_email" to "sendEmail". It
will remove non alphanumeric character from the word, so
"who's online" will be converted to "whoSOnline"'''
word = self.camelize(word)
return word[0].lower() + word[1:]
| (self, word) |
723,700 | inflector | Inflector |
Inflector for pluralizing and singularizing nouns.
It provides methods for helping on creating programs
based on naming conventions like on Ruby on Rails.
| class Inflector(object):
"""
Inflector for pluralizing and singularizing nouns.
It provides methods for helping on creating programs
based on naming conventions like on Ruby on Rails.
"""
def __init__(self, language =English):
assert callable(language), "language should be a callable obj"
self._language = language()
def pluralize(self, word):
'''Pluralizes nouns.'''
return self._language.pluralize(word)
def singularize(self, word):
'''Singularizes nouns.'''
return self._language.singularize(word)
def conditional_plural(self, number_of_records, word):
'''Returns the plural form of a word if first parameter is
greater than 1.
'''
return self._language.conditional_plural(number_of_records, word)
def titleize(self, word, uppercase=''):
'''Converts an underscored or CamelCase word into a sentence.
The titleize function converts text like "WelcomePage",
"welcome_page" or "welcome page" to this "Welcome Page".
If the "uppercase" parameter is set to 'first' it will only
capitalize the first character of the title.
'''
return self._language.titleize(word, uppercase)
def camelize(self, word):
'''Returns given word as CamelCased.
Converts a word like "send_email" to "SendEmail". It
will remove non alphanumeric characters from the word, so
"who's online" will be converted to "WhoSOnline"
'''
return self._language.camelize(word)
def underscore(self, word):
''' Converts a word "into_it_s_underscored_version"
Convert any "CamelCased" or "ordinary Word" into an
"underscored_word".
This can be really useful for creating friendly URLs.
'''
return self._language.underscore(word)
def humanize(self, word, uppercase=''):
'''Returns a human-readable string from word
Returns a human-readable string from word, by replacing
underscores with a space, and by upper-casing the initial
character by default.
If you need to uppercase all the words you just have to
pass 'all' as a second parameter.
'''
return self._language.humanize(word, uppercase)
def variablize(self, word):
'''Same as camelize but first char is lowercased
Converts a word like "send_email" to "sendEmail". It
will remove non alphanumeric character from the word, so
"who's online" will be converted to "whoSOnline"'''
return self._language.variablize(word)
def tableize(self, class_name):
''' Converts a class name to its table name according to rails
naming conventions. Example. Converts "Person" to "people".
'''
return self._language.tableize(class_name)
def classify(self, table_name):
'''Converts a table name to its class name according to rails
naming conventions. Example: Converts "people" to "Person"
'''
return self._language.classify(table_name)
def ordinalize(self, number):
'''Converts number to its ordinal form.
This method converts 13 to 13th, 2 to 2nd ...
'''
return self._language.ordinalize(number)
def unaccent(self, text):
'''Transforms a string to its unaccented version.
This might be useful for generating "friendly" URLs'''
return self._language.unaccent(text)
def urlize(self, text):
'''Transform a string its unaccented and underscored
version ready to be inserted in friendly URLs.
'''
return self._language.urlize(text)
def demodulize(self, module_name):
return self._language.demodulize(module_name)
def modulize(self, module_description):
return self._language.modulize(module_description)
def foreign_key(self, class_name,
separate_class_name_and_id_with_underscore=1):
''' Returns class_name in underscored form, with "_id" tacked on at the end.
This is for use in dealing with the database.
'''
return self._language.foreign_key(
class_name,
separate_class_name_and_id_with_underscore
)
def conditionalPlural(self, number_of_records, word):
'''Deprecated, alias of #conditional_plural for backwards
compatibility.
'''
return self.conditional_plural(number_of_records, word)
def foreignKey(self, class_name, separate_class_name_and_id_with_underscore=1):
'''Deprecated, alias of #foreign_key for backwards compatibility.'''
return self.foreign_key(class_name,
separate_class_name_and_id_with_underscore)
| (language=<class 'inflector.languages.english.English'>) |
723,701 | inflector | __init__ | null | def __init__(self, language =English):
assert callable(language), "language should be a callable obj"
self._language = language()
| (self, language=<class 'inflector.languages.english.English'>) |
723,702 | inflector | camelize | Returns given word as CamelCased.
Converts a word like "send_email" to "SendEmail". It
will remove non alphanumeric characters from the word, so
"who's online" will be converted to "WhoSOnline"
| def camelize(self, word):
'''Returns given word as CamelCased.
Converts a word like "send_email" to "SendEmail". It
will remove non alphanumeric characters from the word, so
"who's online" will be converted to "WhoSOnline"
'''
return self._language.camelize(word)
| (self, word) |
723,703 | inflector | classify | Converts a table name to its class name according to rails
naming conventions. Example: Converts "people" to "Person"
| def classify(self, table_name):
'''Converts a table name to its class name according to rails
naming conventions. Example: Converts "people" to "Person"
'''
return self._language.classify(table_name)
| (self, table_name) |
723,704 | inflector | conditionalPlural | Deprecated, alias of #conditional_plural for backwards
compatibility.
| def conditionalPlural(self, number_of_records, word):
'''Deprecated, alias of #conditional_plural for backwards
compatibility.
'''
return self.conditional_plural(number_of_records, word)
| (self, number_of_records, word) |
723,705 | inflector | conditional_plural | Returns the plural form of a word if first parameter is
greater than 1.
| def conditional_plural(self, number_of_records, word):
'''Returns the plural form of a word if first parameter is
greater than 1.
'''
return self._language.conditional_plural(number_of_records, word)
| (self, number_of_records, word) |
723,706 | inflector | demodulize | null | def demodulize(self, module_name):
return self._language.demodulize(module_name)
| (self, module_name) |
723,707 | inflector | foreignKey | Deprecated, alias of #foreign_key for backwards compatibility. | def foreignKey(self, class_name, separate_class_name_and_id_with_underscore=1):
'''Deprecated, alias of #foreign_key for backwards compatibility.'''
return self.foreign_key(class_name,
separate_class_name_and_id_with_underscore)
| (self, class_name, separate_class_name_and_id_with_underscore=1) |
723,708 | inflector | foreign_key | Returns class_name in underscored form, with "_id" tacked on at the end.
This is for use in dealing with the database.
| def foreign_key(self, class_name,
separate_class_name_and_id_with_underscore=1):
''' Returns class_name in underscored form, with "_id" tacked on at the end.
This is for use in dealing with the database.
'''
return self._language.foreign_key(
class_name,
separate_class_name_and_id_with_underscore
)
| (self, class_name, separate_class_name_and_id_with_underscore=1) |
723,709 | inflector | humanize | Returns a human-readable string from word
Returns a human-readable string from word, by replacing
underscores with a space, and by upper-casing the initial
character by default.
If you need to uppercase all the words you just have to
pass 'all' as a second parameter.
| def humanize(self, word, uppercase=''):
'''Returns a human-readable string from word
Returns a human-readable string from word, by replacing
underscores with a space, and by upper-casing the initial
character by default.
If you need to uppercase all the words you just have to
pass 'all' as a second parameter.
'''
return self._language.humanize(word, uppercase)
| (self, word, uppercase='') |
723,710 | inflector | modulize | null | def modulize(self, module_description):
return self._language.modulize(module_description)
| (self, module_description) |
723,711 | inflector | ordinalize | Converts number to its ordinal form.
This method converts 13 to 13th, 2 to 2nd ...
| def ordinalize(self, number):
'''Converts number to its ordinal form.
This method converts 13 to 13th, 2 to 2nd ...
'''
return self._language.ordinalize(number)
| (self, number) |
723,712 | inflector | pluralize | Pluralizes nouns. | def pluralize(self, word):
'''Pluralizes nouns.'''
return self._language.pluralize(word)
| (self, word) |
723,713 | inflector | singularize | Singularizes nouns. | def singularize(self, word):
'''Singularizes nouns.'''
return self._language.singularize(word)
| (self, word) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.