-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstatistics.py
84 lines (74 loc) · 2.65 KB
/
statistics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from yfinance import Ticker
import time
import json
settings = json.load(open("settings.json", "r"))
tickers_description = settings["tickersDescription"]
tickers_exchange = settings["tickersExchange"]
tickers_exchange_timezone = settings["tickersExchangeTimezone"]
tickers_currency = settings["tickersCurrency"]
def basic(asset_name):
"""
Returns basic statistics about an asset:
- current price;
- change for day %;
- long name.
"""
ticker = Ticker(asset_name)
# Sometimes yfinance returns one-day statistics if the period is 2d,
# so request 3 days period and consume only the last 2 days
asset_history = ticker.history(period='3d').dropna(subset=['Close'])
yesterday_info = asset_history.iloc[-2]
today_info = asset_history.iloc[-1]
previous_close = float(yesterday_info.get('Close'))
current_price = float(today_info.get('Close'))
return {
'current_price': current_price,
'change_for_day': current_price * 100.0 / previous_close - 100.0,
'long_name': tickers_description.get(asset_name),
}
def detailed(asset_name):
"""
Returns detailed statistics about an asset:
- long name;
- exchange;
- timezone;
- currency;
- datetime;
- current price;
- change for day;
- change for day %;
- volume;
- previous close;
- day range;
- year range;
- forward dividend;
- dividend yield.
"""
ticker = Ticker(asset_name)
year_info = ticker.history(period='1y').dropna(subset=['Close'])
yesterday_info = year_info.iloc[-2]
today_info = year_info.iloc[-1]
previous_close = float(yesterday_info.get('Close'))
current_price = float(today_info.get('Close'))
return {
'previous_close': previous_close,
'current_price': current_price,
'change_for_day': current_price * 100.0 / previous_close - 100.0,
'change_for_day_sum': current_price - previous_close,
'volume': today_info.get('Volume'),
'day_range_low': today_info.get('Low'),
'day_range_high': today_info.get('High'),
'year_range_low': year_info['Low'].min(),
'year_range_high': year_info['High'].max(),
'long_name': tickers_description.get(asset_name),
'exchange': tickers_exchange.get(asset_name),
'timezone': tickers_exchange_timezone,
'currency': tickers_currency,
'timestamp': round(time.time()),
}
def history(asset_name, period='5mo'):
"""
Returns history for the specified period of time in format `timestamp: price at day start`.
"""
asset = Ticker(asset_name)
return asset.history(period).dropna(subset=['Open']).loc[:, 'Open'].to_json()