예제 #1
0
def get_date_intervals(start_date, end_date, terms):
    start_day = start_date.day
    start_month = start_date.month
    start_year = start_date.year

    end_day = end_date.day
    end_month = end_date.month
    end_year = end_date.year

    start = pendulum.Pendulum(start_year, start_month, start_day)
    end = pendulum.Pendulum(end_year, end_month, end_day)
    period = pendulum.period(start, end)

    if terms == 'Monthly':
        return [dt.format('%B %d, %Y') for dt in period.range('months')][1:]

    elif terms == 'Quarterly':
        return [dt.format('%B %d, %Y') for dt in period.range('months', 3)][1:]

    elif terms == 'Semi-Annually':
        return [dt.format('%B %d, %Y') for dt in period.range('months', 6)][1:]

    elif terms == 'Annually':
        return [dt.format('%B %d, %Y')
                for dt in period.range('months', 12)][1:]
예제 #2
0
async def test_user_create_not_matching_certified_on(alice_backend_sock, alice,
                                                     mallory):
    date1 = pendulum.Pendulum(2000, 1, 1)
    date2 = date1.add(seconds=1)
    cu = UserCertificateContent(
        author=alice.device_id,
        timestamp=date1,
        user_id=mallory.user_id,
        public_key=mallory.public_key,
        is_admin=False,
    ).dump_and_sign(alice.signing_key)
    cd = DeviceCertificateContent(
        author=alice.device_id,
        timestamp=date2,
        device_id=mallory.device_id,
        verify_key=mallory.verify_key,
    ).dump_and_sign(alice.signing_key)
    with freeze_time(date1):
        rep = await user_create(alice_backend_sock,
                                user_certificate=cu,
                                device_certificate=cd)
        assert rep == {
            "status":
            "invalid_data",
            "reason":
            "Device and User certifications must have the same timestamp.",
        }
예제 #3
0
async def test_user_create_certify_too_old(alice_backend_sock, alice, mallory):
    too_old = pendulum.Pendulum(2000, 1, 1)
    now = too_old.add(seconds=INVITATION_VALIDITY + 1)
    cu = UserCertificateContent(
        author=alice.device_id,
        timestamp=too_old,
        user_id=mallory.user_id,
        public_key=mallory.public_key,
        is_admin=False,
    ).dump_and_sign(alice.signing_key)
    cd = DeviceCertificateContent(
        author=alice.device_id,
        timestamp=too_old,
        device_id=mallory.device_id,
        verify_key=mallory.verify_key,
    ).dump_and_sign(alice.signing_key)

    with freeze_time(now):
        rep = await user_create(alice_backend_sock,
                                user_certificate=cu,
                                device_certificate=cd)
        assert rep == {
            "status": "invalid_certification",
            "reason": "Invalid timestamp in certification.",
        }
예제 #4
0
async def test_user_create_certificate_too_old(alice_backend_sock, alice,
                                               mallory):
    too_old = pendulum.Pendulum(2000, 1, 1)
    now = too_old.add(seconds=INVITATION_VALIDITY + 1)
    user_certificate = UserCertificateContent(
        author=alice.device_id,
        timestamp=too_old,
        user_id=mallory.user_id,
        public_key=mallory.public_key,
        profile=UserProfile.STANDARD,
    ).dump_and_sign(alice.signing_key)
    device_certificate = DeviceCertificateContent(
        author=alice.device_id,
        timestamp=too_old,
        device_id=mallory.device_id,
        verify_key=mallory.verify_key,
    ).dump_and_sign(alice.signing_key)

    with freeze_time(now):
        rep = await user_create(
            alice_backend_sock,
            user_certificate=user_certificate,
            device_certificate=device_certificate,
            redacted_user_certificate=user_certificate,
            redacted_device_certificate=device_certificate,
        )
        assert rep == {
            "status": "invalid_certification",
            "reason": "Invalid timestamp in certificate.",
        }
def main01_constant_input_simulation():
    """ Simple simulation of a pendulum system. Choose a constant
        control input Tss, and simulate system's output behavior. """
    m, g, l, k = 1, 10, 1, 2
    pend = pendulum.Pendulum(m, g, l, k)

    theta0, theta_dot0 = 1, 0
    x0 = np.array([theta0, theta_dot0])

    t_start, t_end = 0, 10
    sample_count = 1000
    t = np.linspace(t_start, t_end, sample_count)
    tspan = [t_start, t_end]

    # Constant control input
    Tss = 0
    T = lambda t, x: Tss
    f = lambda t, x: pend.state_space_static_controller(t, x, T)

    sol = scipy.integrate.solve_ivp(f, tspan, x0, t_eval=t)

    fig, ax = fc.new_figure()
    ax.plot(sol.t, sol.y[0], label='$\\theta$')
    ax.plot(sol.t, sol.y[1], label='$\\dot{\\theta}$')
    ax.set_xlabel('$t$')
    ax.grid()
    ax.legend()

    Path('./figures').mkdir(parents=True, exist_ok=True)
    plt.savefig('figures/unforced_response.pdf', pad_inches=0.0)
예제 #6
0
def get_datetime(date, tz_name=None, *args):
    tz = pytz.timezone(tz_name or DEFAULT_TZ_NAME)
    if isinstance(date, int):
        return pendulum.Pendulum(date, *args, tzinfo=tz)
    if isinstance(date, datetime.datetime):
        return pendulum.Pendulum.instance(date, tz).astimezone(tz)
    if isinstance(date, str):
        return parse_date(date)
    return pendulum.Pendulum.instance(
        datetime.datetime.combine(date, datetime.time.min), tz).astimezone(tz)
예제 #7
0
 def setUp(self):
     self.test_series = [
         {
             'parameters': [
                 {
                     'start_date': pendulum.Pendulum(1889, 2, 28),
                     'end_date': pendulum.Pendulum(2017, 5, 27),
                     'data_types': ['Data Types'],
                     'parameter_code': '00060',
                     'parameter_name': 'Discharge, dm3/s'
                 },
                 {
                     'start_date': pendulum.Pendulum(1890, 12, 1),
                     'end_date': pendulum.Pendulum(2018, 3, 25),
                     'data_types': ['Data Types'],
                     'parameter_code': '00010',
                     'parameter_name': 'Temperature, K'
                 }
             ]
         }
     ]
예제 #8
0
def main():

    #initialize environment
    env = pendulum.Pendulum()

    ppo = PPO(args, env)

    for epoch in range(args.epochs):
        print('Training Epoch ' + str(epoch + 1) + '/' + str(args.epochs))
        ppo.train()

    ppo.save_model()
    ppo.generate_results()
예제 #9
0
async def test_user_revoke_certify_too_old(backend, alice_backend_sock, alice,
                                           bob):
    now = pendulum.Pendulum(2000, 1, 1)
    revoked_user_certificate = RevokedUserCertificateContent(
        author=alice.device_id, timestamp=now,
        user_id=bob.user_id).dump_and_sign(alice.signing_key)

    with freeze_time(now.add(seconds=INVITATION_VALIDITY + 1)):
        rep = await user_revoke(
            alice_backend_sock,
            revoked_user_certificate=revoked_user_certificate)
        assert rep == {
            "status": "invalid_certification",
            "reason": "Invalid timestamp in certification.",
        }
예제 #10
0
async def test_device_create_certify_too_old(alice_backend_sock, alice,
                                             alice_nd):
    now = pendulum.Pendulum(2000, 1, 1)
    device_certificate = DeviceCertificateContent(
        author=alice.device_id,
        timestamp=now,
        device_id=alice_nd.device_id,
        verify_key=alice_nd.verify_key,
    ).dump_and_sign(alice.signing_key)

    with freeze_time(now.add(seconds=INVITATION_VALIDITY + 1)):
        rep = await device_create(alice_backend_sock,
                                  device_certificate=device_certificate,
                                  encrypted_answer=b"<good>")
        assert rep == {
            "status": "invalid_certification",
            "reason": "Invalid timestamp in certification.",
        }
def main03_feedback_state_stabilization():
    """ Simulation of a pendulum system. The system is controlled by
        a stabilizing state-feedback controller around desired angle
        delta. """
    m, g, l, k = 1, 10, 1, 2
    a, b, c = g / l, k / m, 1 / m / l / l
    delta = pi / 4  # Desired value of angle theta at equilibrium point
    pend = pendulum.Pendulum(m, g, l, k)

    theta0, theta_dot0 = 0, 0
    x0 = np.array([theta0, theta_dot0])

    # State feedback control
    k1, k2 = 1, 1
    T = lambda t, x: -k1 * (x[0] - delta) - k2 * x[1] + a * sin(delta) / c
    f = lambda t, x: pend.state_space_static_controller(t, x, T)

    t_start, t_end = 0, 10
    N = 1000
    t = np.linspace(t_start, t_end, N)
    tspan = [t_start, t_end]

    sol = scipy.integrate.solve_ivp(f, tspan, x0, t_eval=t)
    control = T(sol.t, sol.y)

    fig, axs = fc.new_figure(subplot_count=2, height=2 * fc.DEFAULT_HEIGHT)
    axs[0].plot([t_start, t_end], [pi / 4, pi / 4],
                'r--',
                label='Reference $\\delta$')
    axs[0].plot(sol.t, sol.y[0], label='$\\theta$')
    axs[0].plot(sol.t, sol.y[1], label='$\\dot{\\theta}$')
    axs[1].plot(sol.t, control, 'g', label='$T$')
    axs[0].set_xlabel('$t$')
    axs[0].grid()
    axs[0].legend()
    axs[1].set_xlabel('$t$')
    axs[1].grid()
    axs[1].legend()

    Path('./figures').mkdir(parents=True, exist_ok=True)
    plt.savefig('figures/state_feedback.pdf', pad_inches=0.0)
예제 #12
0
async def test_user_revoke_ok(backend, backend_sock_factory, adam_backend_sock,
                              alice, adam):
    now = pendulum.Pendulum(2000, 10, 11)
    alice_revocation = RevokedUserCertificateContent(
        author=adam.device_id, timestamp=now,
        user_id=alice.user_id).dump_and_sign(adam.signing_key)

    with backend.event_bus.listen() as spy:
        with freeze_time(now):
            rep = await user_revoke(adam_backend_sock,
                                    revoked_user_certificate=alice_revocation)
        assert rep == {"status": "ok"}
        await spy.wait_with_timeout("user.revoked", {
            "organization_id": alice.organization_id,
            "user_id": alice.user_id
        })

    # Alice cannot connect from now on...
    with pytest.raises(HandshakeRevokedDevice):
        async with backend_sock_factory(backend, alice):
            pass
def main05_integral_control():
    """ Simulation of a pendulum system. The system is controlled by
        an integral controller, which is stabilized by linearization
        around desired angle delta and state-feedback. """
    # Good values for m to test are: 0.1, 1, 2 (1 is nominal)
    m, g, l, k = 0.1, 10, 1, 2
    pend = pendulum.Pendulum(m, g, l, k)
    delta = pi / 4
    k1, k2, k3 = 8, 2, 10
    K = np.array([k1, k2, k3])
    test_integral_controller_constraints(K, m, g, l, k, delta)

    theta0, theta_dot0, sigma0 = 0, 0, 0
    x0 = np.array([theta0, theta_dot0, sigma0])

    t_start, t_end = 0, 10
    N = 1000
    t = np.linspace(t_start, t_end, N)
    tspan = [t_start, t_end]

    f_original = pend.state_space_integral_controller
    f = lambda t, x: f_original(t, x, K, delta)

    sol = scipy.integrate.solve_ivp(f, tspan, x0, t_eval=t)

    fig, ax = fc.new_figure()
    ax.plot([t_start, t_end], [delta, delta],
            'r--',
            label='Reference $\\delta$')
    ax.plot(sol.t, sol.y[0], label='$\\theta$')
    ax.plot(sol.t, sol.y[1], label='$\\dot{\\theta}$')
    ax.plot(sol.t, sol.y[2], label='$\\sigma$')
    ax.set_xlabel('$t$')
    ax.grid()
    ax.legend()

    Path('./figures').mkdir(parents=True, exist_ok=True)
    plt.savefig('figures/integral_control_small_mass.pdf', pad_inches=0.0)
def main04_output_feedback_stabilization():
    """ Simulation of a pendulum system. The system is controlled by
        a stabilizing output-feedback controller around desired angle
        delta. States are estimated by an observer. """
    m, g, l, k = 1, 10, 1, 2
    delta = pi / 4
    pend = pendulum.Pendulum(m, g, l, k)

    x0 = np.array([0, 0, 0, 0])
    t_start, t_end = 0, 10
    N = 1000
    t = np.linspace(t_start, t_end, N)
    tspan = [t_start, t_end]

    k1, k2, h1, h2 = 1, 1, 1, 1
    K = np.array([k1, k2])
    H = np.array([h1, h2])

    f_original = pend.state_space_observer_controller
    f = lambda t, x: f_original(t, x, K, H, delta)

    sol = scipy.integrate.solve_ivp(f, tspan, x0, t_eval=t)

    fig, ax = fc.new_figure()
    ax.plot([t_start, t_end], [delta, delta],
            'r--',
            label='Reference $\\delta$')
    ax.plot(sol.t, sol.y[0], label='$\\theta$')
    ax.plot(sol.t, sol.y[1], label='$\\dot{\\theta}$')
    ax.plot(sol.t, sol.y[2], label='$\\hat{\\theta}$')
    ax.plot(sol.t, sol.y[3], label='$\\hat{\\dot{\\theta}}$')
    ax.set_xlabel('$t$')
    ax.grid()
    ax.legend()

    Path('./figures').mkdir(parents=True, exist_ok=True)
    plt.savefig('figures/output_feedback.pdf', pad_inches=0.0)
def main02_constant_input_simulation_fixed_delta():
    """ Simple simulation of a pendulum system. Choose a constant
        desired output angle delta; a constant control input Tss
        will be calculated to obtain a stable equilibrium at the
        desired output angle delta. """
    m, g, l, k = 1, 10, 1, 2
    a, b, c = g / l, k / m, 1 / m / l / l
    pend = pendulum.Pendulum(m, g, l, k)

    theta0, theta_dot0 = 0, 0
    x0 = np.array([theta0, theta_dot0])

    t_start, t_end = 0, 10
    sample_count = 1000
    t = np.linspace(t_start, t_end, sample_count)
    tspan = [t_start, t_end]

    # Constant control input derived from desired constant angle
    delta = pi / 4
    Tss = a / c * sin(delta)
    T = lambda t, x: Tss
    f = lambda t, x: pend.state_space_static_controller(t, x, T)

    sol = scipy.integrate.solve_ivp(f, tspan, x0, t_eval=t)

    fig, ax = fc.new_figure()
    ax.plot([t_start, t_end], [delta, delta],
            'r--',
            label='Reference $\\delta$')
    ax.plot(sol.t, sol.y[0], label='$\\theta$')
    ax.plot(sol.t, sol.y[1], label='$\\dot{\\theta}$')
    ax.set_xlabel('$t$')
    ax.grid()
    ax.legend()

    Path('./figures').mkdir(parents=True, exist_ok=True)
    plt.savefig('figures/constant_control.pdf', pad_inches=0.0)
async def test_organization_with_expiration_date_create_and_bootstrap(
    backend,
    organization_factory,
    local_device_factory,
    alice,
    administration_backend_sock,
    apiv1_backend_sock_factory,
):
    neworg = organization_factory("NewOrg")

    # 1) Create organization, note this means `neworg.bootstrap_token`
    # will contain an invalid token

    with freeze_time("2000-01-01"):

        expiration_date = pendulum.Pendulum(2000, 1, 2)
        rep = await organization_create(administration_backend_sock,
                                        neworg.organization_id,
                                        expiration_date=expiration_date)
        assert rep == {
            "status": "ok",
            "bootstrap_token": ANY,
            "expiration_date": expiration_date
        }
        bootstrap_token = rep["bootstrap_token"]

        # 2) Bootstrap organization

        # Use an existing user name to make sure they didn't mix together
        newalice = local_device_factory("alice@dev1",
                                        neworg,
                                        profile=UserProfile.ADMIN)
        backend_newalice, backend_newalice_first_device = local_device_to_backend_user(
            newalice, neworg)

        async with apiv1_backend_sock_factory(backend,
                                              neworg.organization_id) as sock:
            rep = await organization_bootstrap(
                sock,
                bootstrap_token,
                backend_newalice.user_certificate,
                backend_newalice_first_device.device_certificate,
                neworg.root_verify_key,
            )
        assert rep == {"status": "ok"}

        # 3) Now our new device can connect the backend
        async with apiv1_backend_sock_factory(backend, newalice) as sock:
            await ping(sock)

        # 4) Make sure alice from the other organization is still working

        async with apiv1_backend_sock_factory(backend, alice) as sock:
            await ping(sock)

    # 5) Now advance after the expiration
    with freeze_time("2000-01-02"):
        # Both anonymous and authenticated connections are refused
        with pytest.raises(HandshakeOrganizationExpired):
            async with apiv1_backend_sock_factory(backend, newalice):
                pass
        with pytest.raises(HandshakeOrganizationExpired):
            async with apiv1_backend_sock_factory(backend,
                                                  neworg.organization_id):
                pass
UTC = pendulum.timezone('UTC')

datetime_now = datetime.datetime.now(pytz.timezone('MST'))
# Mongo drops portion of microsecond, field truncates automatically for consistency
datetime_now = datetime_now.replace(microsecond=int(math.floor(datetime_now.microsecond / 1000) * 1000))
pendulum_now = pendulum.instance(datetime_now)

pendulum_interval = pendulum.interval(minutes=5)


@pytest.mark.parametrize('field_name,dt,expected_raw', [
    ('Incident Closed', pendulum_now, DatetimeField.format_datetime(pendulum_now)),
    (
        'Date Field',
        pendulum_now,
        DatetimeField.format_datetime(pendulum.Pendulum(pendulum_now.year, pendulum_now.month, pendulum_now.day))
    ),
    ('Time Field', pendulum_now, DatetimeField.format_datetime(pendulum_now)),
    ('Incident Duration', pendulum_interval, pendulum_interval.in_seconds() * 1000)
])
def test_raw_serialization(mock_record, field_name, dt, expected_raw):
    """Test that datetime field values are appropriately serialized to raw"""
    mock_record[field_name] = dt
    field_id = mock_record.app.get_field_definition_by_name(field_name)['id']
    assert mock_record._raw['values'][field_id] == expected_raw


@pytest.mark.parametrize('valid_date_obj', [
    datetime_now,
    datetime_now.date(),
    pendulum_now,
    'g': g
}
# compute the dynamic trajectories for all grid points (
trajectories = np.zeros((grids.shape[1], int(T / dt) * 2))
steps = int(T / dt)

# for ind, point in enumerate(grids.T):
#     print(f'ind = {ind}')
# print(f'ind = {ind}')
# print(f'point = {point}')
# if ind >= 2:
#     break
ind = 0
point = grids.T[0]
wave = {'phi': point[0], 'dphi': point[1]}
vary_length_pendulum = pendulum.Pendulum(wave, attributes)
vary_length_pendulum.main()
states = np.hstack((vary_length_pendulum.asym_control_phi,
                    vary_length_pendulum.asym_control_dphi))
trajectories[ind, :] = np.copy(states)

t = np.arange(0, T, dt)
x0 = grids.T[0]
beta = np.linalg.norm(x0) * np.exp(-.05 * t)
states = np.vstack((trajectories[0, :steps], trajectories[1, :steps]))
phi = np.linalg.norm(states, axis=0)

fig = plt.figure(figsize=[16, 9])
plt.plot(t, beta, 'r--')
plt.plot(t, phi, 'k')
plt.show()
예제 #19
0
# we can create a robot
import numpy as np
import tqdm

import pendulum

robot = pendulum.Pendulum()

# assume we set theta and dtheta = 0 and u = -5, we can get the next state using
x = np.array([0, 0])
u = -5
x_next = robot.next_state(x, u)

# we don't want 2pi to be in the set because it's the same as 0
discretized_theta = np.linspace(0, 2 * np.pi, 50, endpoint=False)

discretized_thetadot = np.linspace(-6, 6, 50)

# now given an arbitrary continuous state theta
theta_arbitrary = 0.23471

# we can find the index of the closest element in the set of discretized states
index_in_discretized_theta = np.argmin(np.abs(discretized_theta - theta_arbitrary))

# and find the closed discretized state
closest_state = discretized_theta[index_in_discretized_theta]
print(f'the discretized theta closest to {theta_arbitrary} is {closest_state} with index {index_in_discretized_theta}')


def cost(x, u):
    theta = x[0]
예제 #20
0
def test_derivative():
    ta = pendulum.Pendulum(L=2.7)
    theta, v = ta(0, [math.pi / 6, 0.15])
    assert math.isclose(theta, 0.15)
    assert math.isclose(v, -1.81666666667)
예제 #21
0
def test_motionless():
    ta = pendulum.Pendulum()
    theta, v = ta(0, [0, 0])
    assert math.isclose(theta, 0)
    assert math.isclose(v, 0)
예제 #22
0
def main():
    # Create environment
    env = pendulum.Pendulum()

    ######################################
    #
    #   EXAMPLE OF CREATING A VIDEO
    #

    # Define a policy that maps every state to the "zero torque" action
    policy = lambda s: np.array([0])

    # Simulate an episode and save the result as an animated gif
    env.video(policy, filename='results_pendulum.gif')

    #
    ######################################

    ######################################
    #
    #   EXAMPLE OF CREATING A PLOT
    #

    # Initialize simulation
    s = env.reset()

    # Create dict to store data from simulation
    data = {
        't': [0],
        's': [s],
        'a': [],
        'r': [],
    }

    # Simulate until episode is done
    done = False
    while not done:
        a = np.array([random.gauss(0, 1)])
        (s, r, done) = env.step(a)
        data['t'].append(data['t'][-1] + 1)
        data['s'].append(s)
        data['a'].append(a)
        data['r'].append(r)

    # Parse data from simulation
    data['s'] = np.array(data['s'])
    data['a'] = np.array(data['a'])
    theta = data['s'][:, 0]
    thetadot = data['s'][:, 1]
    tau = data['a'][:, 0]

    # Plot data and save to png file
    fig, ax = plt.subplots(3, 1, figsize=(10, 10))
    ax[0].plot(data['t'], theta, label='theta')
    ax[0].plot(data['t'], thetadot, label='thetadot')
    ax[0].legend()
    ax[1].plot(data['t'][:-1], tau, label='tau')
    ax[1].legend()
    ax[2].plot(data['t'][:-1], data['r'], label='r')
    ax[2].legend()
    ax[2].set_xlabel('time step')
    plt.tight_layout()
    plt.savefig('results_pendulum.png')
예제 #23
0
def test_exceptions():
    ta = pendulum.Pendulum(L=2.7)
    with pytest.raises(AttributeError):
        ta.t
        ta.theta
        ta.omega
예제 #24
0
def test_atrest():
    ta = pendulum.Pendulum(L=2.7)
    ta.solve((0, 0), [0, 30], 0.2)
    assert all(np.isclose(0, ta.theta))
    assert all(np.isclose(0, ta.omega))
    assert all(np.isclose(ta.t, np.arange(0, 30 + 0.2, 0.2)))
예제 #25
0
def get_feed_prices(node):
    active_providers = defaultdict(set)
    for chain in ['bts', 'steem']:
        provider_names = {p.lower() for p in cfg[chain]['feed_providers']}
        for name, provider in ALL_FEED_PROVIDERS.items():
            if name in provider_names:
                active_providers[chain].add(provider())

    # get currency rates from yahoo
    # do not include:
    # - BTC as we don't get it from yahoo
    # - USD as it is our base currency
    yahoo_prices = []
    # try:
    #     yahoo = YahooFeedProvider()
    #     yahoo_prices = yahoo.get(YAHOO_ASSETS | {'CNY'}, 'USD')  # still get CNY, we might need it later
    #
    # except Exception as e:
    #     log.warning(e)

    currency_layer_prices = []
    try:
        currency_layer = CurrencyLayerFeedProvider()
        currency_layer_prices = currency_layer.get(
            tuple(YAHOO_ASSETS | {'CNY'}), 'USD')

    except Exception as e:
        log.debug('Could not get feeds from CurrencyLayer: {}'.format(e))

    fixer_prices = []
    try:
        fixer_prices = FixerFeedProvider().get_all(base='USD')
    except Exception as e:
        log.warning('Could not get feeds from fixer.io: {}'.format(e))

    # get gold and silver
    gold_silver_prices = []

    quandl = QuandlFeedProvider()
    try:
        gold_silver_prices += [
            quandl.get('GOLD', 'USD'),
            quandl.get('SILVER', 'USD')
        ]
    except Exception as e:
        log.debug('Could not get gold/silver feeds from Quandl')

    # uphold = UpholdFeedProvider()
    # try:
    #     gold_silver_prices += [uphold.get('GOLD', 'USD'),
    #                            uphold.get('SILVER', 'USD')]
    # except Exception as e:
    #     log.debug('Could not get gold/silver feeds from Uphold')

    base_usd_price = FeedSet(yahoo_prices + currency_layer_prices +
                             fixer_prices + gold_silver_prices)

    # 1- get the BitShares price in major markets: BTC, USD and CNY
    btcavg = core.config['credentials']['bitcoinaverage']

    bitcoinavg = BitcoinAverageFeedProvider(btcavg['secret_key'],
                                            btcavg['public_key'])
    bitfinex = BitfinexFeedProvider()
    bitstamp = BitstampFeedProvider()
    bittrex = BittrexFeedProvider()
    btc38 = Btc38FeedProvider()
    bter = BterFeedProvider()
    cmc = CoinMarketCapFeedProvider()
    coincap = CoinCapFeedProvider()
    poloniex = PoloniexFeedProvider()
    yunbi = YunbiFeedProvider()
    livecoin = LivecoinFeedProvider()
    aex = AEXFeedProvider()
    zb = ZBFeedProvider()

    # 1.1- first get the bts/btc valuation
    providers_bts_btc = {poloniex, bittrex, livecoin, aex, zb
                         } & active_providers['bts']
    if not providers_bts_btc:
        log.warning('No feed providers for BTS/BTC feed price')
    all_feeds = get_multi_feeds('get', [('BTS', 'BTC')], providers_bts_btc)

    feeds_bts_btc = all_feeds.filter('BTS', 'BTC')

    if not feeds_bts_btc:
        # in last resort, just get our data from coinmarketcap and coincap
        log.info(
            'getting bts/btc directly from coinmarketcap, no other sources available'
        )
        feeds_bts_btc = FeedSet(
            [cmc.get('BTS', 'BTC'),
             coincap.get('BTS', 'BTC')])

    if not feeds_bts_btc:
        raise core.NoFeedData('Could not get any BTS/BTC feeds')

    btc_price = feeds_bts_btc.price()

    # 1.2- get the btc/usd (bitcoin avg)
    feeds_btc_usd = get_multi_feeds(
        'get', [('BTC', 'USD')],
        {bitcoinavg, cmc, bitfinex, bitstamp} & active_providers['bts']
    )  # coincap seems to be off sometimes, do not use it
    if not feeds_btc_usd:
        raise core.NoFeedData('Could not get any BTC/USD feeds')

    btc_usd = feeds_btc_usd.price()

    usd_price = btc_price * btc_usd

    # 1.3- get the bts/cny valuation directly from cny markets. Going from bts/btc and
    #      btc/cny to bts/cny introduces a slight difference (2-3%) that doesn't exist on
    #      the actual chinese markets
    providers_bts_cny = {bter, btc38, yunbi} & active_providers['bts']

    # TODO: should go at the beginning: submit all fetching tasks to an event loop / threaded executor,
    # compute valuations once we have everything
    #all_feeds.append(get_multi_feeds('get', [('BTS', 'CNY')], providers_bts_cny))
    feeds_bts_cny = get_multi_feeds('get', [('BTS', 'CNY')], providers_bts_cny)
    if not feeds_bts_cny:
        # if we couldn't get the feeds for cny, go BTS->BTC, BTC->CNY
        log.debug('Could not get any BTS/CNY feeds, going BTS->BTC, BTC->CNY')
        bts_cny = btc_price * btc_usd / base_usd_price.price('CNY')

        # # if we couldn't get the feeds for cny, try picking up our last value
        # if price_history.get('cny'):
        #     log.warning('Could not get any BTS/CNY feeds, using last feed price')
        #     bts_cny = price_history['cny'][-1]
        # else:
        #     raise core.NoFeedData('Could not get any BTS/CNY feeds')
    else:
        bts_cny = feeds_bts_cny.price()

    cny_price = bts_cny

    feeds = {
    }  # TODO: do we really want to reset the global var 'feeds' everytime we come here?
    feeds['BTC'] = btc_price
    feeds['USD'] = usd_price
    feeds['CNY'] = cny_price

    feeds['HERO'] = usd_price / (1.05**(
        (pendulum.today() - pendulum.Pendulum(1913, 12, 23)).in_days() /
        365.2425))

    log.debug('Got btc/usd price: {}'.format(btc_usd))
    log.debug('Got usd price: {}'.format(usd_price))
    log.debug('Got cny price: {}'.format(cny_price))

    # 2- now get the BitShares price in all other required currencies
    for asset in YAHOO_ASSETS:
        try:
            feeds[asset] = usd_price / base_usd_price.price(asset)
        except Exception:
            log.warning('no feed price for asset {}'.format(asset))

    # 2.1- RUBLE is used temporarily by RUDEX instead of bitRUB (black swan)
    #      see https://bitsharestalk.org/index.php/topic,24004.0/all.html
    feeds['RUBLE'] = feeds['RUB']

    # 3- get the feeds for major composite indices   # REMOVED, was using yahoo, GoogleFeedProvider, BloombergFeedProvider

    # 4- get other assets
    altcap = get_multi_feeds('get', [('ALTCAP', 'BTC')], {coincap, cmc})
    altcap = altcap.price(stddev_tolerance=0.08)
    feeds['ALTCAP'] = altcap

    gridcoin = get_multi_feeds('get', [('GRIDCOIN', 'BTC')],
                               {poloniex, bittrex})
    feeds['GRIDCOIN'] = btc_price / gridcoin.price(stddev_tolerance=0.1)

    steem_btc = get_multi_feeds('get', [('STEEM', 'BTC')], {poloniex, bittrex}
                                & active_providers['steem'])
    steem_usd = steem_btc.price() * btc_usd
    feeds['STEEM'] = steem_usd

    # 5- Bit20 asset
    if 'BTWTY' not in get_disabled_assets():
        bit20 = get_bit20_feed(node, usd_price)
        if bit20 is not None:
            feeds['BTWTY'] = bit20

    # 6- HERTZ asset
    if 'HERTZ' not in get_disabled_assets():
        hertz_reference_timestamp = "2015-10-13T14:12:24+00:00"  # Bitshares 2.0 genesis block timestamp
        hertz_current_timestamp = pendulum.now().timestamp(
        )  # Current timestamp for reference within the hertz script
        hertz_amplitude = 1 / 3  # 33.33..% fluctuation
        hertz_period_days = 28  # 30.43 days converted to an UNIX timestamp // TODO: Potentially change this value to 28
        hertz_phase_days = 0.908056  # Time offset from genesis till the first wednesday, to set wednesday as the primary Hz day.
        hertz_reference_asset_price = usd_price

        hertz = get_hertz_feed(hertz_reference_timestamp,
                               hertz_current_timestamp, hertz_period_days,
                               hertz_phase_days, hertz_reference_asset_price,
                               hertz_amplitude)
        if hertz is not None:
            feeds['HERTZ'] = hertz

    # 7- update price history for all feeds
    for cur, price in feeds.items():
        price_history[cur].append(price)

    return feeds
예제 #26
0
def test_radius():
    ta = pendulum.Pendulum(L=2.7)
    ta.solve((math.pi / 6, 0.15), [0, 30], 0.2)
    assert all(np.isclose(ta.x**2 + ta.y**2, 2.7**2))
예제 #27
0
def get(asset, base):
    log.debug('checking feeds for %s/%s at %s' % (asset, base, NAME))

    price_usd = 1.05 ** ((pendulum.today() - pendulum.Pendulum(1913, 12, 23)).in_days() / 365.2425)

    return FeedPrice(price_usd, asset, base)
예제 #28
0
def mod_15_mins(t):
    if not isinstance(t, pendulum.Pendulum):
        raise TypeError('function mod_15_mins expects a pendulum.Pendulum object')
    quarter_in_hour = t.minute / 15
    return pendulum.Pendulum()
예제 #29
0
파일: feeds.py 프로젝트: rahulsps/bts_tools
def get_feed_prices(node):
    def active_providers_bts(providers):
        feed_providers = {p.lower() for p in cfg['bts']['feed_providers']}
        return {p for p in providers if p.NAME.lower() in feed_providers}

    def active_providers_steem(providers):
        feed_providers = {p.lower() for p in cfg['steem']['feed_providers']}
        return {p for p in providers if p.NAME.lower() in feed_providers}

    providers = core.get_plugin_dict('bts_tools.feed_providers')

    # 0- get forex data + gold/silved in USD
    currency_layer_prices = []
    try:
        currency_layer_prices = providers.CurrencyLayer.get(
            BASE_ASSETS - {'BTC', 'USD'}, 'USD')
    except Exception as e:
        log.debug('Could not get feeds from CurrencyLayer: {}'.format(e))

    fixer_prices = []
    try:
        fixer_prices = providers.Fixer.get_all(base='USD')
    except Exception as e:
        log.debug('Could not get feeds from fixer.io: {}'.format(e))

    gold_silver_prices = []
    try:
        gold_silver_prices += [
            providers.Quandl.get('GOLD', 'USD'),
            providers.Quandl.get('SILVER', 'USD')
        ]
    except Exception as e:
        log.debug('Could not get gold/silver feeds from Quandl: {}'.format(e))

    base_usd_price = FeedSet(currency_layer_prices + fixer_prices +
                             gold_silver_prices + providers.Uphold.get_all())

    base_usd_price = base_usd_price.filter(base='USD')

    # 1- get the BitShares price in major markets: BTC, USD and CNY

    # 1.1- first get the bts/btc valuation
    providers_bts_btc = active_providers_bts({
        providers.Poloniex, providers.Bittrex, providers.Livecoin,
        providers.aex, providers.zb, providers.Binance
    })
    if not providers_bts_btc:
        log.warning('No feed providers for BTS/BTC feed price')
    all_feeds = get_multi_feeds('get', [('BTS', 'BTC')], providers_bts_btc)

    feeds_bts_btc = all_feeds.filter('BTS', 'BTC')

    if not feeds_bts_btc:
        # in last resort, just get our data from coinmarketcap and coincap
        log.info(
            'getting bts/btc directly from coinmarketcap, no other sources available'
        )
        feeds_bts_btc = FeedSet([
            providers.CoinMarketCap.get('BTS', 'BTC'),
            providers.CoinCap.get('BTS', 'BTC')
        ])

    if not feeds_bts_btc:
        raise core.NoFeedData('Could not get any BTS/BTC feeds')

    btc_price = feeds_bts_btc.price()

    # 1.2- get the btc/usd (bitcoin avg)
    feeds_btc_usd = get_multi_feeds(
        'get', [('BTC', 'USD')],
        active_providers_bts({
            providers.BitcoinAverage, providers.CoinMarketCap,
            providers.Bitfinex, providers.Bitstamp
        }))  # coincap seems to be off sometimes, do not use it
    if not feeds_btc_usd:
        raise core.NoFeedData('Could not get any BTC/USD feeds')

    btc_usd = feeds_btc_usd.price()

    usd_price = btc_price * btc_usd

    # 1.3- get the bts/cny valuation directly from cny markets. Going from bts/btc and
    #      btc/cny to bts/cny introduces a slight difference (2-3%) that doesn't exist on
    #      the actual chinese markets

    # TODO: should go at the beginning: submit all fetching tasks to an event loop / threaded executor,
    # compute valuations once we have everything
    feeds_bts_cny = get_multi_feeds(
        'get', [('BTS', 'CNY')],
        active_providers_bts(
            {providers.Bter, providers.BTC38, providers.Yunbi}))
    if not feeds_bts_cny:
        # if we couldn't get the feeds for cny, go BTS->BTC, BTC->CNY
        log.debug('Could not get any BTS/CNY feeds, going BTS->BTC, BTC->CNY')
        bts_cny = btc_price * btc_usd / base_usd_price.price('CNY')

        # # if we couldn't get the feeds for cny, try picking up our last value
        # if price_history.get('cny'):
        #     log.warning('Could not get any BTS/CNY feeds, using last feed price')
        #     bts_cny = price_history['cny'][-1]
        # else:
        #     raise core.NoFeedData('Could not get any BTS/CNY feeds')
    else:
        bts_cny = feeds_bts_cny.price()

    cny_price = bts_cny

    feeds = {
    }  # TODO: do we really want to reset the global var 'feeds' everytime we come here?
    feeds['BTC'] = btc_price
    feeds['USD'] = usd_price
    feeds['CNY'] = cny_price

    feeds['HERO'] = usd_price / (1.05**(
        (pendulum.today() - pendulum.Pendulum(1913, 12, 23)).in_days() /
        365.2425))

    log.debug('Got btc/usd price: {}'.format(btc_usd))
    log.debug('Got usd price: {}'.format(usd_price))
    log.debug('Got cny price: {}'.format(cny_price))

    # 2- now get the BitShares price in all other required currencies
    for asset in BASE_ASSETS - {'BTC', 'USD', 'CNY'}:
        try:
            feeds[asset] = usd_price / base_usd_price.price(asset, 'USD')
        except Exception:
            log.warning('no feed price for asset {}'.format(asset))

    # 2.1- RUBLE is used temporarily by RUDEX instead of bitRUB (black swan)
    #      see https://bitsharestalk.org/index.php/topic,24004.0/all.html
    feeds['RUBLE'] = feeds['RUB']

    # 3- get the feeds for major composite indices   # REMOVED, was using yahoo, GoogleFeedProvider, BloombergFeedProvider

    # 4- get other assets
    altcap = get_multi_feeds('get', [('ALTCAP', 'BTC')],
                             {providers.CoinCap, providers.CoinMarketCap})
    altcap = altcap.price(stddev_tolerance=0.08)
    feeds['ALTCAP'] = altcap

    gridcoin = get_multi_feeds('get', [('GRIDCOIN', 'BTC')],
                               {providers.Poloniex, providers.Bittrex})
    feeds['GRIDCOIN'] = btc_price / gridcoin.price(stddev_tolerance=0.1)

    steem_btc = get_multi_feeds(
        'get', [('STEEM', 'BTC')],
        active_providers_steem({providers.Poloniex, providers.Bittrex}))
    steem_usd = steem_btc.price() * btc_usd
    feeds['STEEM'] = steem_usd

    golos_btc = get_multi_feeds(
        'get', [('GOLOS', 'BTC')],
        active_providers_steem({providers.Bittrex, providers.Livecoin}))
    golos_bts = btc_price / golos_btc.price()
    feeds['GOLOS'] = golos_bts

    # 5- Bit20 asset
    if 'BTWTY' not in get_disabled_assets():
        try:
            bit20 = get_bit20_feed(node, usd_price)
            if bit20 is not None:
                feeds['BTWTY'] = bit20
        except core.NoFeedData as e:
            log.warning(e)

    # 6- HERTZ asset
    if 'HERTZ' not in get_disabled_assets():
        hertz_reference_timestamp = "2015-10-13T14:12:24+00:00"  # Bitshares 2.0 genesis block timestamp
        hertz_current_timestamp = pendulum.now().timestamp(
        )  # Current timestamp for reference within the hertz script
        hertz_amplitude = 0.14  # 14% fluctuation (1% per day)
        hertz_period_days = 28  # 28 days
        hertz_phase_days = 0.908056  # Time offset from genesis till the first wednesday, to set wednesday as the primary Hz day.
        hertz_reference_asset_price = usd_price

        hertz = get_hertz_feed(hertz_reference_timestamp,
                               hertz_current_timestamp, hertz_period_days,
                               hertz_phase_days, hertz_reference_asset_price,
                               hertz_amplitude)
        if hertz is not None:
            feeds['HERTZ'] = hertz

    # 7- update price history for all feeds
    for cur, price in feeds.items():
        price_history[cur].append(price)

    return feeds
예제 #30
0
import os
from math import sin, cos, pi

import matplotlib.pyplot as plt

import pendulum

pendulum = pendulum.Pendulum(
    .001,
    [0, 0., pi, 0.],
    10,
)
data = pendulum.integrate()

fig = plt.figure(0)
fig.suptitle("Pendulum on Cart")

cart_time_line = plt.subplot2grid((12, 12), (9, 0), colspan=12, rowspan=3)
cart_time_line.axis([
    0,
    10,
    min(data[:, 1]) * 1.1,
    max(data[:, 1]) * 1.1 + .1,
])
cart_time_line.set_xlabel('time (s)')
cart_time_line.set_ylabel('x (m)')
cart_time_line.plot(data[:, 0], data[:, 1], 'r-')

pendulum_time_line = cart_time_line.twinx()
pendulum_time_line.axis(
    [0, 10, min(data[:, 3]) * 1.1 - .1,