Exemplo n.º 1
0
def date_range_for_quarter(date=None):
    if date is None:
        date = dt_date.today()
    quarter = date_quarter(date)
    year = date.year
    return (dt_date(year, quarter * 3 - 2, 1),
            dt_date(year, quarter * 3 + 1, 1) - timedelta(days=1), quarter)
Exemplo n.º 2
0
    def determine_date(date: str):
        """
        When downloading from UKC dates come through in a rather messy way, this function makes assumptions and fixes
        this.

        :param date: The date as it comes from UKC
        :return: A date object
        """
        calander = {
            'jan': 1,
            'feb': 2,
            'mar': 3,
            'apr': 4,
            'may': 5,
            'jun': 6,
            'jul': 7,
            'aug': 8,
            'sep': 9,
            'oct': 10,
            'nov': 11,
            'dec': 12
        }  # A calander that can be used to map the str months to numerical months
        if date[:
                3] == '???':  # When no day or month is recorded then ??? preceeds the year
            return dt_date(int(date[-4:]), 1, 1)
        elif date[:
                  2] == '??':  # When no month is recorded then ?? preceeds the month and year
            month = calander[date[3:6].lower()]  # Find the numerical month
            return dt_date(int('20' + date[-2:]), month, 1)
        else:  # Otherwise all date information is given and determine the date
            month = calander[date[3:6].lower()]  # Find the numerical month
            return dt_date(int('20' + date[-2:]), month, int(date[:2]))
Exemplo n.º 3
0
Arquivo: avto.py Projeto: SFill/garage
    def save_to_db(self):
        if not self.validate_fields():
            self.dialog = MsgForm("Поля не прошли проверки")
            return
        connection = mysqlx.get_session(mysql_config)
        msg = "Сохранено"
        query = ""
        if self.insert:
            query = "Insert into garage.avto values(\"{0}\",\"{1}\", \"{2}\" ,{3})".format(
                self.MarkEdit.text(), self.NumberEdit.text(),
                str(dt_date(int(self.DateEdit.text()), 1, 1)),
                self.IdEdit.text())
        else:
            try:
                query = "Update garage.avto set mark=\"{0}\", number=\"{1}\", date=\"{2}\" where id={3}".format(
                    self.MarkEdit.text(), self.NumberEdit.text(),
                    str(dt_date(int(self.DateEdit.text()), 1, 1)),
                    self.IdEdit.text())
            except Exception as e:
                print(e)

        try:
            connection.sql(query).execute()
        except Exception as e:
            msg = "Ошибка сохранения"
        finally:
            connection.close()

        self.dialog = MsgForm(msg)
        if self.pre_exit is not None:
            self.pre_exit(self, self.obj_out)
        if self.insert:
            self.insert = False
Exemplo n.º 4
0
def select_all_events():
	files = glob.glob('./model/saved_events/*.json')
	events = []
	for f in files:
		with open(f, 'r') as nf:
			content = nf.read()
			event = Event(name=None)
			e = json.loads(content)

			if e['_Event__start_date'] is not None:
				d_start = e['_Event__start_date']
				d_start = list(map(int, d_start.split('/')))
				d_start.reverse()
				e['_Event__start_date'] = dt_date(*d_start)

			if e['_Event__end_date'] is not None:
				d_end = e['_Event__end_date']
				d_end = list(map(int, d_end.split('/')))
				d_end.reverse()
				e['_Event__end_date'] = dt_date(*d_start)

			event.__dict__.update(e)
			events.append(event)
	return events
Exemplo n.º 5
0
Arquivo: avto.py Projeto: SFill/garage
    def validate_fields(self):
        date = self.DateEdit.text().strip()
        id = self.IdEdit.text().strip()
        znak = self.NumberEdit.text().strip()
        valid = True

        try:
            date = dt_date(int(date), 1, 1)
            if (date < datetime(1970, 1, 1, 0,
                                0).date()) or date > datetime.today().date():
                valid = False
            if str(int(id)) != id:
                valid = False
            if len(znak) != 6 or re.match(
                    r'[abekmnopctyx]\d{3}[abekmnopctyx]{2}', znak) is None:
                valid = False

        except Exception:
            valid = False
        return valid
Exemplo n.º 6
0
def get_random_date():
    start = int(dt_date(2018, 1, 1).strftime("%s"))
    end = int(dt_date.today().strftime("%s"))
    rand_timestamp = random.randint(start, end)
    rand_date = dt_date.fromtimestamp(rand_timestamp)
    return rand_date
Exemplo n.º 7
0
os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()
from matplotlib.finance import quotes_historical_yahoo
import matplotlib.pyplot as plt

from scipy.stats import gaussian_kde

from IPython.display import HTML

y = []
ma = []

def moving_average(interval, window_size):
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)

# vvv clip first and last points of convolution
mov_avg = go.Scatter( x=x[5:-4], y=ma[5:-4], \
                  line=dict(width=2,color='red',opacity=0.5), name='Moving average' )
Exemplo n.º 8
0
REGISTER_FAST_LOGIN_KEY = '@cardgame123'
REGISTER_NICK_COLOR = 'FF0066'
BORADCAST_CHANGE_NAME = 1
BORADCAST_SEND_CHAT = 7

DEFAULT_USER = {
    'avatar': [''],
    'sign': u'这家伙很懒,什么也没留下。',
    'nick': [u'游客', u'来宾', u'赌客'],
    'nick_num': ["%04d", (0, 9999)],
    'gold': 20000,
    'diamond': 0,
    'vip': 0,
    'money': 0,
    'charm': 0,
    'birthday': dt_date(2000, 1, 1),
    'sex': 0,
    'is_charge': 0,
    'vip_exp': 0,
    'default_item': (1, 0),
    'flow_card': 0,
}

DEFAULT_USER_GLODFLOWER = {
    'exp': 0,
    'win_games': 0,
    'total_games': 0,
    'best': '',
    'wealth_rank': 0,
    'win_rank': 0,
    'charm_rank': 0,
Exemplo n.º 9
0
def extract_datetime(s):
    '''Converts a datetime string into a datetime object'''
    now = datetime.now()
    args = s.upper().split()

    if len(args) == 1:
        # This is a good way to check if a single parameter is time,
        # because standalone time always has one of these substrings.
        # Careful though! If time is preceded by date, it's possible
        # to omit the colon for 24-hour time strings (e.g. "pdc 3/2 15").
        if ':' in args[0] or 'PM' in args[0] or 'AM' in args[0]:
            time = args[0]
            date = None
        else:
            time = None
            date = args[0]
    elif len(args) == 2:
        date, time = args
    else:
        print('Too many arguments. See "pdc --help" for reference.')
        return None

    day, month, year = (None, ) * 3
    hour, minute, second = (None, ) * 3
    pm_am = None

    if date is not None:

        # Extract date
        match = re.match(r'^(?P<day>\d+)\.(?P<month>\d+)(\.(?P<year>\d+))?$',
                         date)
        if match is None:
            match = re.match(r'^(?P<month>\d+)/(?P<day>\d+)(/(?P<year>\d+))?$',
                             date)
            if match is None:
                match = re.match(
                    r'^(?P<year>\d+)-(?P<month>\d+)(-(?P<day>\d+))?$', date)
                if match is None:
                    print(
                        'Unrecognized date format. Available: "dd.mm.yyyy", "mm/dd/yyyy", "yyyy-mm-dd"'
                    )
                    return None
        # Notice that in the first two formats year can be omitted,
        # while in the third format the day can be omitted.
        # If a day is omitted, we simply assume it to be 1.
        # If a year is omitted however, we have to pick the lowest possible
        # year for the rest of the datetime to make sense,
        # i.e. if it is currently August and the user request a date
        # in November, the year is assumed to be the current one,
        # but if the requested a date in March, the year would have to be
        # the subsequent one. The check will be performed later.

        # Store matches
        day = match.group('day')
        month = match.group('month')
        year = match.group('year')

        # Convert known values
        day = int(day if day is not None else 1)
        month = int(month)
        year = int(year) if year is not None else None

    # If date is omitted completely and there's only time,
    # then depending on the current time the date will either be
    # today or tomorrow. This check is also performed later.

    if time is not None:
        # Extract time
        # Some match strings contain unmatchable groups, e.g. '...$(?P<unmatchable>_)?'
        # This is a hacky way to enforce that these named groups always exist in the match object,
        # to avoid ugly checks later on. Basically, everything that doesn't exist always has None value.
        match = re.match(
            r'^(?P<hour>\d+):(?P<minute>\d+)(:(?P<second>\d+))?$(?P<pm_am>_)?',
            time)
        if match is None:
            match = re.match(
                r'^(?P<hour>\d+)(:(?P<minute>\d+)(:(?P<second>\d+))?)?(?P<pm_am>PM|AM)',
                time)
            if match is None and date is not None:
                match = re.match(
                    r'^(?P<hour>\d+)$(?P<minute>_)?(?P<second>_)?(?P<pm_am>_)?',
                    time)
                if match is None:
                    print(
                        'Unrecognized time format. See "pdc --help" for valid examples.'
                    )
                    return None

        # Store matches
        hour = match.group('hour')
        minute = match.group('minute')
        second = match.group('second')
        pm_am = match.group('pm_am')

    # Convert to int and if any time values were omitted, assume 0
    hour = int(hour if hour is not None else 0)
    minute = int(minute if minute is not None else 0)
    second = int(second if second is not None else 0)

    # Verify time validity
    try:
        dt = dt_time(hour, minute, second)
    except Exception as e:
        print(f'{type(e).__name__}: {e}')
        return None

    # Convert 12-hour time to 24-hour time
    if pm_am is not None:
        if hour == 12 and pm_am == 'AM':
            hour = 0
        elif hour != 12 and pm_am == 'PM':
            hour += 12

    # If date was omitted, find the closest suitable one
    if date is None:
        d = datetime(now.year, now.month, now.day, hour, minute, second)
        if d < now:
            d += timedelta(1)
        day = d.day
        month = d.month
        year = d.year

    # If year was omitted, find the closest suitable one
    elif year is None:
        # Verify month and day validity
        # Use 2016 as year, because it was a leap year (Feb 29 is a valid date)
        try:
            dt = dt_date(2016, month, day)
        except Exception as e:
            print(f'{type(e).__name__}: {e}')
            return None

        # Increment year till the date is valid and in the future
        year = now.year
        dt = datetime(year, month, day, hour, minute, second)
        while dt < now:
            year += 1
            try:
                dt = datetime(year, month, day, hour, minute, second)
            except ValueError:
                continue

    # Verify full timedate validity
    try:
        dt = datetime(year, month, day, hour, minute, second)
    except Exception as e:
        print(f'{type(e).__name__}: {e}')
        return None

    return dt
Exemplo n.º 10
0
    def test_snapable_find_snapshots(self):
        ds = poolset.lookup('rpool/USERDATA/jbloggs_jb327m')
        self.assertIsInstance(ds, zfs.Dataset)

        all_snaps = ds.get_all_snapshots()
        
        # Empty options
        snaps = ds.find_snapshots({})
        self.assertEqual(len(snaps), len(all_snaps))

        # Name only
        snaps = ds.find_snapshots({'name': '*zsys_w*'})
        self.assertEqual(len(snaps), 3)

        snaps = ds.find_snapshots({'name': '*'})
        self.assertEqual(len(snaps), len(all_snaps))

        # Name and dt_from
        snaps = ds.find_snapshots({'name': '*zsys_*e*'
            , 'dt_from': dt_from_creation('1609272411')})
        self.assertEqual(len(snaps), 2)

        # Name and tdelta and dt_to
        # . Note: tdelta alone cannot be used for static unit testing
        snaps = ds.find_snapshots({'name': '*zsys_*e*', 'tdelta': timedelta(hours=36)
            ,'dt_to': dt_from_creation('1609362247')})
        self.assertEqual(len(snaps), 5)
        snaps2 = ds.find_snapshots({'name': '*zsys_*e*', 'tdelta': '36H'
            ,'dt_to': dt_from_creation('1609362247')})
        self.assertEqual(len(snaps2), len(snaps))
        for i, snap in enumerate(snaps):
            self.assertIs(snap, snaps2[i])

        # Name, dt_from and tdelta
        snaps = ds.find_snapshots({'name': '*zsys_*w*'
            ,'dt_from': dt_from_creation('1608233673'), 'tdelta': timedelta(hours=48)})
        self.assertEqual(len(snaps), 5)
        snaps2 = ds.find_snapshots({'name': '*zsys_*w*'
            ,'dt_from': dt_from_creation('1608233673'), 'tdelta': '48H'})
        self.assertEqual(len(snaps2), len(snaps))
        for i, snap in enumerate(snaps):
            self.assertIs(snap, snaps2[i])

        # Name, dt_from and dt_to
        snaps = ds.find_snapshots({'name': '*zsys_*w*'
            ,'dt_from': dt_from_creation('1608233673')
            ,'dt_to': dt_from_creation('1608772856')})
        self.assertEqual(len(snaps), 6)

        # Name, dt_from and dt_to using date instead of datetime
        snaps = ds.find_snapshots({'name': '*zsys_*w*'
            ,'dt_from': dt_date(2020, 12, 17)
            ,'dt_to': dt_date(2020, 12, 23)})
        self.assertEqual(len(snaps), 5)

        for i, snap in enumerate(snaps):
            self.assertIsInstance(snap, zfs.Snapshot)

        # Name, dt_from and dt_to using date instead of datetime with index=True
        snaps = ds.find_snapshots({'name': '*zsys_*w*', "index": True
            ,'dt_from': dt_date(2020, 12, 17)
            ,'dt_to': dt_date(2020, 12, 23)})
        self.assertEqual(len(snaps), 5)
        self.assertIsInstance(snaps[0], tuple)
        self.assertEqual(len(snaps[0]), 2)
        self.assertIsInstance(snaps[0][0], int)
        self.assertIsInstance(snaps[0][1], zfs.Snapshot)

        # Negative Tests
        with self.assertRaises(TypeError): snaps = ds.find_snapshots()
        with self.assertRaises(AssertionError): snaps = ds.find_snapshots({'name': True})
        with self.assertRaises(AssertionError): snaps = ds.find_snapshots({'dt_from': 'asdf'})
        with self.assertRaises(AssertionError): snaps = ds.find_snapshots({'dt_to': 'asdf'})
        with self.assertRaises(AssertionError): snaps = ds.find_snapshots({'tdelta': 10})
        with self.assertRaises(AssertionError): snaps = ds.find_snapshots({'tdelta': '-10H'})
        with self.assertRaises(AssertionError): snaps = ds.find_snapshots({'index': 1})
        with self.assertRaises(AssertionError): 
            snaps = ds.find_snapshots({'dt_to': dt_date(2020, 12, 20)
                                     , 'dt_from': dt_date(2020, 12, 21)})
        with self.assertRaises(AssertionError): 
            snaps = ds.find_snapshots({'dt_to': dt_date(2020, 12, 21)
                                      ,'dt_from': dt_date(2020, 12, 20)
                                      ,'tdelta': "1H"})
import plotly.tools as plotly_tools
from plotly.graph_objs import *

import os
import tempfile
os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()
from matplotlib.finance import quotes_historical_yahoo
import matplotlib.pyplot as plt

from scipy.stats import gaussian_kde

from IPython.display import HTML

plotly.sign_in("jackp", "XXXX")


date1 = dt_date(2014, 1, 1)
date2 = dt_date(2014, 12, 12)

tickers = ['AAPL', 'GE', 'IBM', 'KO', 'MSFT', 'PEP']
prices = []
for ticker in tickers:
    quotes = quotes_historical_yahoo(ticker, date1, date2)
    prices.append( [q[1] for q in quotes] )


# We have all the stock prices in a list of lists - use the code snippet below to convert this into a Pandas dataframe.
df = pandas.DataFrame( prices ).transpose()
df.columns = tickers
df.head()
Exemplo n.º 12
0
 def add_month(sourcedate, months):
     month = sourcedate.month - 1 + months
     year = sourcedate.year + month / 12
     month = month % 12 + 1
     day = min(sourcedate.day, calendar.monthrange(year, month)[1])
     return dt_date(year, month, day)
Exemplo n.º 13
0
 def get_unix_time_date(date):
     return (date - dt_date(1970, 1, 1)).total_seconds()
Exemplo n.º 14
0
def recent_matches(request):

    today = datetime.now().date()
    yesterday = today - timedelta(1)
    today_start = datetime.combine(today, time())
    d = yesterday
    matches = Match.objects.filter(start_ts__gte=d).select_related(
        'tournament',
        'player0',
        'player1',
        'winner',
        'bets'
    ).order_by('-start_ts')
    result = 0
    for m in matches:
        bet = m.match_bets.first()

        if bet and bet.winner:
            bet.plus = bet.odd - 1
            m.bet = bet
            m.bet_on = bet.winner.name

            if bet.winner == m.winner:
                m.won = bet.odd - 1
                m.bet.plus = bet.odd - 1
                result += m.won
            elif m.winner and (bet.winner != m.winner):
                m.won = -1
                result += m.won

    DAYS = 60
    DAYS_H = []
    TOTAL = 0
    y2015 = dt_date(2015, 1, 1)
    for i in range(DAYS):
        date = datetime.today() - timedelta(i)
        if date.date() < y2015:
            continue
        bets = Bet.objects.filter(
            selection=BetSelection.MATCH_WINNER,
            winner__isnull=False,
            ts_created__range=(
                datetime.combine(date, time.min),
                datetime.combine(date, time.max)
            )
        ).select_related('match').order_by('-ts_created')
        total = 0
        for b in bets:
            if b.isWon():
                total += b.odd - 1
                TOTAL += b.odd - 1
            elif b.isLost():
                total -= 1
                TOTAL -= 1
        DAYS_H.append({'date': date.date(), 'total': total})

    return render_to_response(
        "recent_matches.html",
        {
            'matches': matches,
            'result': result,
            'daily': DAYS_H,
            'total': TOTAL
        }
    )