ml-finance-python
python scripts for finance machine learning
git clone https://9o.is/git/ml-finance-python.git
broker.py
(1238B)
1 import time
2 import json
3 from datetime import datetime as dt
4 import requests
5 import pandas as pd
6
7
8 def get_access_token():
9 with open('/home/user/trading/quantopian/research_public/scratch/credentials', 'r') as file:
10 data = file.read()
11 obj = json.loads(data)
12 return obj['access_token']
13
14
15 def get_pricing(symbol, start_date, end_date):
16 start = str(int(time.mktime(dt.strptime(start_date, '%Y-%m-%d').timetuple()) * 1000))
17 end = str(int(time.mktime(dt.strptime(end_date, '%Y-%m-%d').timetuple()) * 1000))
18
19 url = 'https://api.tdameritrade.com/v1/marketdata/' + symbol + '/pricehistory'
20
21 headers = {
22 'Authorization': 'Bearer ' + get_access_token()
23 }
24
25 params = (
26 ('apikey', 'UHQLAYUDK3GCXEDLJBFXMUTEDNOCCBL4'),
27 ('periodType', 'month'),
28 ('frequencyType', 'daily'),
29 ('frequency', '1'),
30 ('endDate', end),
31 ('startDate', start),
32 )
33
34 response = requests.get(url=url, headers=headers, params=params)
35
36 content = [{
37 'date': dt.fromtimestamp(int(tick.get('datetime')) / 1000),
38 'price': tick.get('close'),
39 } for tick in response.json()['candles']]
40
41 df = pd.DataFrame(content)
42 df = df.set_index('date')
43
44 return df