Exemplo n.º 1
0
    def bitcoin_data():
        ''' Gets bitcoin values from last 365 days. '''
        b = BtcConverter()

        year_ago = DATE - timedelta(days=365)
        bitcoin_values = list(
            b.get_previous_price_list('USD', year_ago, DATE).values())

        return bitcoin_values
Exemplo n.º 2
0
    def load_dreammarket(self):
        with pymongo.MongoClient('localhost', 27017) as client:
            db = client['drug_database']
            table = db['dreammarket-testbase']
            table1 = db['dreammarket']

            docs = list(table.find()) + list(table1.find())

        docs = add_scraping_session(docs)

        docs = {(doc['vendor'], doc['title'], doc['scraping_session'], doc['price']): doc for doc in docs}.values() #remove duplicates
        counts = sorted(Counter(d['scraping_session'] for d in docs).items())

        bad_dates = [date for date, count in counts if count < 40000]
        docs = [d for d in docs if d['scraping_session'] not in bad_dates]

        c = BtcConverter()
        start_date = min(d['scraping_session'] for d in docs)
        end_date = max(d['scraping_session'] for d in docs)
        self.btc_rates = c.get_previous_price_list('EUR', start_date, end_date)
        self.btc_rates = {dt.datetime.strptime(date, '%Y-%m-%d'): rate for date, rate in self.btc_rates.items()}

        find_unit = re.compile(r'(\d+\.?\d*)\s*({})'.format('|'.join(self.units)), re.IGNORECASE)
        find_multi = re.compile(r'(\d+)\s*x', re.IGNORECASE)
        for doc in docs:
            del doc['_id']
            doc['market'] = 'dreammarket'

            doc['ships_from'] = doc['ships_from'].strip()
            doc['ships_to'] = [s.strip() for s in doc['ships_to'].split(',')]

            match = find_unit.search(doc['title'])
            doc['price_unit'] = match.group(2).lower() if match else None

            doc['amount'] = float(match.group(1)) if match and float(match.group(1)) != 0 else 1
            multi = find_multi.search(doc['title'])
            if multi and int(multi.group(1)) != 0:
                doc['amount'] *= int(multi.group(1))

            if doc['price_unit'] not in self.gram_factors:
                self.bad_docs.append(doc)
            else:
                doc['price'] = to_float(doc['price'].strip('฿')) / doc['amount'] / self.gram_factors[doc['price_unit']]
                doc['date_mid'] = dt.datetime.combine(doc['scraping_session'].date(), dt.datetime.min.time()) # transfer dates to midnight

                doc['price'] *= self.btc_rates[doc['date_mid']]
                self.docs.append(doc)
Exemplo n.º 3
0
class TestBitCoinForceDecimal(TestCase):
    def setUp(self):
        self.b = BtcConverter(force_decimal=True)

    def test_latest_price_valid_currency(self):
        price = self.b.get_latest_price('USD')
        self.assertEqual(type(price), Decimal)

    def test_latest_price_invalid_currency(self):
        price = self.b.get_latest_price('XYZ')
        self.assertFalse(price)

    def test_previous_price_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        price = self.b.get_previous_price('USD', date_obj)
        self.assertEqual(type(price), Decimal)

    def test_previous_price_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.get_previous_price,
                          'XYZ', date_obj)

    def test_previous_price_list_with_valid_currency(self):
        start_date = datetime.datetime.today() - datetime.timedelta(days=15)
        end_date = datetime.datetime.today()
        price_list = self.b.get_previous_price_list('USD', start_date,
                                                    end_date)
        self.assertTrue(price_list)
        self.assertEqual(type(price_list), dict)

    def test_previous_price_list_with_invalid_currency(self):
        start_date = datetime.datetime.today() - datetime.timedelta(days=15)
        end_date = datetime.datetime.today()
        price_list = self.b.get_previous_price_list('XYZ', start_date,
                                                    end_date)
        self.assertFalse(price_list)
        self.assertEqual(type(price_list), dict)

    def test_convet_to_btc_with_valid_currency(self):
        coins = self.b.convert_to_btc(Decimal('250'), 'USD')
        self.assertEqual(type(coins), Decimal)

    def test_convet_to_btc_with_invalid_currency(self):
        self.assertRaises(RatesNotAvailableError, self.b.convert_to_btc,
                          Decimal('250'), 'XYZ')

    def test_convert_btc_to_cur_valid_currency(self):
        amount = self.b.convert_btc_to_cur(Decimal('2'), 'USD')
        self.assertEqual(type(amount), Decimal)

    def test_convert_btc_to_cur_invalid_currency(self):
        self.assertRaises(RatesNotAvailableError, self.b.convert_btc_to_cur,
                          Decimal('250'), 'XYZ')

    def test_convert_to_btc_on_with_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        coins = self.b.convert_to_btc_on(Decimal('300'), 'USD', date_obj)
        self.assertEqual(type(coins), Decimal)

    def test_convert_to_btc_on_with_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.convert_to_btc_on,
                          Decimal('250'), 'XYZ', date_obj)

    def test_convert_to_btc_on_with_valid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        amount = self.b.convert_btc_to_cur_on(Decimal('250'), 'USD', date_obj)
        self.assertEqual(type(amount), Decimal)

    def test_convert_to_btc_on_with_invalid_currency(self):
        date_obj = datetime.datetime.today() - datetime.timedelta(days=15)
        self.assertRaises(RatesNotAvailableError, self.b.convert_btc_to_cur_on,
                          Decimal('3'), 'XYZ', date_obj)
Exemplo n.º 4
0
print('\n' + from_currency + " To " + to_currency, amount)
print('The current conversion rate for {} to {} is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency)))    #Get conversion rate from USD to INR
result = c.convert(from_currency, to_currency, amount)   #Convert the amount
print('Latest Conversion: ',result)

#Get conversion rate as of 2021-01-01
print('\nThe conversion rate from {} to {} as per 1st Jan 2021 is {}'.format(from_currency, to_currency, c.get_rate(from_currency, to_currency, date_obj)))
print('The conversion as per 1st Jan 2021: ', c.convert(from_currency, to_currency, amount, date_obj))

b = BtcConverter()
print('\n\nBitcoin Symbol: ', b.get_symbol())  # get_btc_symbol()
print('Bitcoin Latest Price in USD : ', b.get_latest_price('USD'))     #Get latest Bitcoin price.
print('Convert 10 Million USD to Bitcoin', b.convert_to_btc(10000000, 'USD'))     #Convert Amount to Bitcoins based on latest exchange price.
print('The Equivalent of 10.99 Bitcoin in USD: ',b.convert_btc_to_cur(10.99, 'USD'))         #Convert Bitcoins to valid currency amount based on lates price

print('\nBitcoin price as per 1st Jan 2021: ',b.get_previous_price('USD', date_obj)) #Get price of Bitcoin based on prevois date
print('The conversion of 10 Million Dollars to Bitcoin as of 1st Jan 2021',b.convert_to_btc_on(10000000, 'USD', date_obj))      #Convert Amount to bitcoins based on previous date prices
print('The conversion of 10.99 Bitcoin in USD as of 1st Jan 2021: ',b.convert_btc_to_cur_on(10.99, 'USD', date_obj))       #Convert Bitcoins to valid currency amount based on previous date price

start_date = datetime.datetime(2021, 2, 1, 19, 39, 36, 815417)
end_date = datetime.datetime(2021, 2, 7, 19, 39, 36, 815417)
print('\nBitcoin rates over the week in USD: ',b.get_previous_price_list('USD', start_date, end_date))         #Get list of prices list for given date range

d = CurrencyCodes()
print('\nUS Dollar Symbol:', d.get_symbol('USD'))          #Get currency symbol using currency code
print(d.get_currency_name('USD'))          #Get Currency Name using currency code

print('\nThe latest rate of USD for various currencies\n', c.get_rates('USD'))          #list all latest currency rates for "USD"
print('\nThe rate of USD for various currencies as per 1st Jan 2021\n',c.get_rates('USD', date_obj))             #List all Currency rates for “USD” on 2021-01-01
Exemplo n.º 5
0
from forex_python.bitcoin import BtcConverter
import datetime
import matplotlib.pyplot as plt

print("BTC Chart Change (USD) PROGRAM")
print("โปรแกรมจะแสดงผลตั้งแต่วันที่เลือกไม่เกิน 2 ปี")
print(
    "กรุณาเลือกก่อนวันที่ 6 มิถุนายน 2013 (ประมาณวันแรกๆ ที่ราคา BTC ถูกซื้อขาย)"
)
print("-" * 80)
print("Input start date : (ex. 2013 6 24)")
start_date_year = int(input("Input year:"))
start_date_month = int(input("Input month:"))
start_date_day = int(input("Input day:"))

b = BtcConverter()
start_date = datetime.date(start_date_year, start_date_month, start_date_day)
end_date = datetime.date(start_date_year + 2, start_date_month, start_date_day)
result_price_list = b.get_previous_price_list("USD", start_date, end_date)

date_result = result_price_list.keys()
rate_result = result_price_list.values()

plt.figure("Akkawat Wongkaew")
plt.title("BTC Chart Change PROGRAM")
plt.plot(date_result, rate_result)
plt.xlabel("Date")
plt.ylabel("BTC / USD Rate")
plt.show()
Exemplo n.º 6
0
df[["ready", "pending"]] = df[["ready", "pending"]].replace("нет",
                                                            0).astype(int)
df["quantity"] = df["quantity"].str[:-2].astype(float)

# And set the day
df["date"] = pd.to_datetime(df["time_stamp"].dt.date)

#%% This is a very large and complex function, buried in utils
print("Labelling substances")
df = label_df(df)

#%%
# Pull in bitcoin prices and convert prices to USD.
print("Converting bitcoin prices")
b = BtcConverter()
rates = b.get_previous_price_list("USD", START_DATE, END_DATE)
btc = (pd.DataFrame(rates, index=[0]).T.reset_index().rename(columns={
    "index": "date",
    0: "btc_usd"
}))

btc["date"] = pd.to_datetime(btc["date"])

df = pd.merge_asof(
    df.sort_values("time_stamp"),
    btc.sort_values("date"),
    left_on="date",
    right_on="date",
)

df["usd_calc"] = df["btc_usd"] * df["BTC"]
Exemplo n.º 7
0
            'date':
            dt.datetime.combine(
                d['scraping_session'].date(),
                dt.datetime.min.time()),  # transfer dates to midnight
            'price':
            to_float(d['price'].strip('฿')) / d['amount'] /
            gram_factors[d['price_unit'].lower()]
        } for d in filtered_docs
    ]

    c = BtcConverter()
    start_date = min(d['date'] for d in filtered_docs)
    end_date = max(d['date'] for d in filtered_docs)

    print('getting exchange rates...')
    rates = c.get_previous_price_list('EUR', start_date, end_date)
    rates = {
        dt.datetime.strptime(date, '%Y-%m-%d'): rate
        for date, rate in rates.items()
    }

    for doc in filtered_docs:
        doc['price'] *= rates[doc['date']]

    print('DONE')

    dates = sorted({d['date'] for d in filtered_docs})

    prices_per_date = {
        date: [p['price'] for p in filtered_docs if p['date'] == date]
        for date in dates