Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
vlad-bezden / first.py
Last active November 2, 2018 12:31
Python doesn't have 'first' function. Here is an example of implementation of it.
from typing import Callable, Iterable, Any
def first(predicate: Callable, collection: Iterable) -> Any:
for x in collection:
if predicate(x):
return x
def first(predicate: Callable, collection: Iterable) -> Any:
return next((x for x in collection if predicate(x)), None)
@vlad-bezden
vlad-bezden / legs.py
Last active October 28, 2018 17:35
Function example of pair/legs of iterable. The type variable, T_, created with the TypeVar function, is used to clarify precisely how the legs() function restructures the data. The hint says that the input type is preserved on output. The input type is an Iterator of some arbitrary type, T_; the output will include tuples of the same type, T_. N…
from typing import Iterator, Any, Iterable, TypeVar, Tuple
T_ = TypeVar('T_')
Pairs_Iter = Iterator[Tuple[T_, T_]]
def legs(iterable: Iterator[T_]) -> Pairs_Iter:
begin = next(iterable)
for end in iterable:
yield begin, end
begin = end
@vlad-bezden
vlad-bezden / transform.py
Last active January 21, 2019 17:41
Example of Transform function. It rotate 2D array by 90 degree
def transform(data):
return [list(x) for x in zip(*data)]
data = [[*range(3)], [*range(3, 6)], [*range(6, 9)]]
# [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
data_t = transform(data)
# [[0, 3, 6], [1, 4, 7], [2, 5, 8]]
@vlad-bezden
vlad-bezden / with_previous.py
Created October 19, 2018 12:10
Yield each iterable item along with the item before it
def couple(iterable, *, first=None):
"""Yield each iterable item along with the item before it."""
prev = first
for item in iterable:
yield prev, item
prev = item
# >>> list(couple(range(5)))
# >>> [(None, 0), (0, 1), (1, 2), (2, 3), (3, 4)]
# >>> list(couple(range(5), first=10))
@vlad-bezden
vlad-bezden / timer.py
Last active August 7, 2018 18:49
python timer contextmanager
from contextlib import contextmanager
import time
@contextmanager
def timer():
start = time.time()
yield
print(f'\N{greek capital letter delta}t \N{rightwards arrow} {time.time() - start:.2f}s')
@vlad-bezden
vlad-bezden / postgesql_asyncio.py
Last active March 24, 2018 19:15
How to use async PostgreSQL queries execution using aiopg and asynio libraries
from time import time
import aiopg
import asyncio
CONN_INFO = {
'host': 'POSTGRESQL_SERVER',
'user': 'user_name',
'port': 1234,
'database': 'some_dabase',
@vlad-bezden
vlad-bezden / time_calculator.py
Created February 21, 2018 15:05
Calculates time from any time passed format H:M:S M:S S
from datetime import timedelta
from functools import reduce
from itertools import chain, repeat
from typing import List
def calc(times: List[str]) -> timedelta:
'''Calculates total time from the list of times'''
result = timedelta()
for t in times:
@vlad-bezden
vlad-bezden / securities_data.py
Created November 25, 2017 20:01
How to get securities data using pandas_datareader
import pandas_datareader as pdr
import pandas as pd
import datetime
def get(tickers, start_date, end_date=None):
def data(ticker):
return pdr.get_data_yahoo(ticker, start=start_date, end=end_date)
datas = map(data, tickers)
return(pd.concat(datas, keys=tickers, names=['Ticker', 'Date']))
@vlad-bezden
vlad-bezden / appl_returns.py
Created November 25, 2017 18:37
Calculate monthly and quarterly Apple (aapl) security returns
import pandas_datareader as pdr
import datetime
aapl = pdr.get_data_yahoo('AAPL',
start=datetime.datetime(2007, 1, 1),
end=datetime.datetime(2018, 1, 1))
# resample 'aapl' to business months, take last observation
monthly = aapl.resample('BM').apply(lambda x: x[-1])
@vlad-bezden
vlad-bezden / exchange_rate.py
Created November 23, 2017 15:13
Gets Currency Exchange Rate
import pandas_datareader as web
uah = web.DataReader('UAH=X', 'yahoo', start='2017-01-01')