Skip to content

Commit 2d6f20e

Browse files
add some issues
1 parent 8a26525 commit 2d6f20e

File tree

3 files changed

+177
-0
lines changed

3 files changed

+177
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from select import select
2+
from datetime import datetime
3+
4+
import time
5+
import pandas as pd
6+
import mplfinance as mpf
7+
import sys
8+
9+
coin = 'BTC'
10+
bot_status = 'trading'
11+
12+
def limit():
13+
timeout = 2.5
14+
print(end='')
15+
rlist, _, _ = select([sys.stdin], [], [], timeout)
16+
print('rlist=',rlist)
17+
if rlist:
18+
s = sys.stdin.readline().strip()
19+
print('s=',s)
20+
if s == 'g':
21+
print('\033[1;34m show chart')
22+
chart()
23+
24+
25+
def dataframe():
26+
# response = **_api exchange_**.candles(coin + '-EUR', '1m', {})
27+
# ohlcv = []
28+
# for s in range(len(response)):
29+
# timestamp = (int(response[s][0]))/1000
30+
# open = float(response[s][1])
31+
# high = float(response[s][2])
32+
# low = float(response[s][3])
33+
# close = float(response[s][4])
34+
# volume = float(response[s][5])
35+
# candles = {'timestamp': (datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')), 'open': open, 'high': high, 'low': low, 'close': close, 'volume': volume}
36+
# ohlcv.append(candles)
37+
# dataframe = pd.DataFrame(data=ohlcv, dtype=float)
38+
dataframe = pd.read_csv('../../data/SP500_NOV2019_Hist.csv',index_col=0, parse_dates=True)
39+
return dataframe
40+
41+
42+
def chart():
43+
df = dataframe()
44+
df.index = pd.DatetimeIndex(df['timestamp'])
45+
df = df.iloc[::-1]
46+
s = mpf.make_mpf_style(base_mpf_style='charles', gridcolor='#555555', gridstyle="--", rc={'axes.edgecolor': 'white', 'font.size': 5})
47+
fig, axlist = mpf.plot(df, type='candle', style=s, title= coin, ylabel = 'Price (€)', volume=True, warn_too_much_data=9999999, returnfig=True)
48+
mpf.show(block=True)
49+
50+
51+
# trade loop
52+
while bot_status == 'trading':
53+
limit()
54+
print('test')
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import mplfinance as mpf
2+
import pandas as pd
3+
4+
#daily = pd.read_csv('/Users/jsb/Desktop/mplfinance-master/examples/data/SP500_NOV2019_Hist.csv',
5+
# index_col=0, parse_dates=True)
6+
daily = pd.read_csv('../../data/SP500_NOV2019_Hist.csv',
7+
index_col=0, parse_dates=True)
8+
daily.index.name = 'Date'
9+
# print(daily.shape)
10+
print(daily)
11+
# daily = daily.loc[:, ['Open', 'High', 'Low', 'Close', 'Volume']]
12+
13+
mpf.figure(figsize=(20, 8), dpi=100)
14+
15+
mpf.plot(daily, type='candle', tight_layout=True)
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
### !pip install yfinance
2+
### !pip install mplfinance
3+
import yfinance as yf
4+
import mplfinance as mpf
5+
import numpy as np
6+
import pandas as pd
7+
8+
# get the data from yfiance
9+
df=yf.download('BTC-USD',start='2008-01-04',end='2021-06-3',interval='1d')
10+
11+
#code snippet 5.1
12+
# Fit linear regression on close
13+
# Return the t-statistic for a given parameter estimate.
14+
def tValLinR(close):
15+
#tValue from a linear trend
16+
x = np.ones((close.shape[0],2))
17+
x[:,1] = np.arange(close.shape[0])
18+
ols = sm1.OLS(close, x).fit()
19+
return ols.tvalues[1]
20+
21+
#code snippet 5.2
22+
'''
23+
#search for the maximum absolutet-value. To identify the trend
24+
# - molecule - index of observations we wish to labels.
25+
# - close - which is the time series of x_t
26+
# - span - is the set of values of L (look forward period) that the algorithm will #try (window_size)
27+
# The L that maximizes |tHat_B_1| (t-value) is choosen - which is the look-forward #period
28+
# with the most significant trend. (optimization)
29+
'''
30+
def getBinsFromTrend(molecule, close, span):
31+
32+
#Derive labels from the sign of t-value of trend line
33+
#output includes:
34+
# - t1: End time for the identified trend
35+
# - tVal: t-value associated with the estimated trend coefficient
36+
#- bin: Sign of the trend (1,0,-1)
37+
#The t-statistics for each tick has a different look-back window.
38+
39+
#- idx start time in look-forward window
40+
#- dt1 stop time in look-forward window
41+
#- df1 is the look-forward window (window-size)
42+
#- iloc ?
43+
44+
out = pd.DataFrame(index=molecule, columns=['t1', 'tVal', 'bin', 'windowSize'])
45+
hrzns = range(*span)
46+
windowSize = span[1] - span[0]
47+
maxWindow = span[1]-1
48+
minWindow = span[0]
49+
for idx in close.index:
50+
idx += (maxWindow*pd.Timedelta('1 day'))
51+
if idx >= close.index[-1]:
52+
break
53+
df_tval = pd.Series(dtype='float64')
54+
iloc0 = close.index.get_loc(idx)
55+
if iloc0+max(hrzns) > close.shape[0]:
56+
continue
57+
for hrzn in hrzns:
58+
dt1 = close.index[iloc0-hrzn+1]
59+
df1 = close.loc[dt1:idx]
60+
df_tval.loc[dt1] = tValLinR(df1.values) #calculates t-statistics on period
61+
dt1 = df_tval.replace([-np.inf, np.inf, np.nan], 0).abs().idxmax() #get largest t-statistics calculated over span period
62+
63+
print(df_tval.index[-1])
64+
print(dt1)
65+
print(abs(df_tval.values).argmax() + minWindow)
66+
out.loc[idx, ['t1', 'tVal', 'bin', 'windowSize']] = df_tval.index[-1], df_tval[dt1], np.sign(df_tval[dt1]), abs(df_tval.values).argmax() + minWindow #prevent leakage
67+
out['t1'] = pd.to_datetime(out['t1'])
68+
out['bin'] = pd.to_numeric(out['bin'], downcast='signed')
69+
70+
#deal with massive t-Value outliers - they dont provide more confidence and they ruin the scatter plot
71+
tValueVariance = out['tVal'].values.var()
72+
tMax = 20
73+
if tValueVariance < tMax:
74+
tMax = tValueVariance
75+
76+
out.loc[out['tVal'] > tMax, 'tVal'] = tMax #cutoff tValues > 20
77+
out.loc[out['tVal'] < (-1)*tMax, 'tVal'] = (-1)*tMax #cutoff tValues < -20
78+
return out.dropna(subset=['bin'])
79+
80+
if __name__ == '__main__':
81+
#snippet 5.3
82+
idx_range_from = 3
83+
idx_range_to = 10
84+
df1 = getBinsFromTrend(df.index, df['Close'], [idx_range_from,idx_range_to,1]) #[3,10,1] = range(3,10) This is the issue
85+
tValues = df1['tVal'].values #tVal
86+
87+
doNormalize = False
88+
#normalise t-values to -1, 1
89+
if doNormalize:
90+
np.min(tValues)
91+
minusArgs = [i for i in range(0, len(tValues)) if tValues[i] < 0]
92+
tValues[minusArgs] = tValues[minusArgs] / (np.min(tValues)*(-1.0))
93+
94+
plus_one = [i for i in range(0, len(tValues)) if tValues[i] > 0]
95+
tValues[plus_one] = tValues[plus_one] / np.max(tValues)
96+
97+
#+(idx_range_to-idx_range_from+1)
98+
plt.scatter(df1.index, df0.loc[df1.index].values, c=tValues, cmap='viridis') #df1['tVal'].values, cmap='viridis')
99+
plt.plot(df0.index, df0.values, color='gray')
100+
plt.colorbar()
101+
plt.show()
102+
plt.savefig('fig5.2.png')
103+
plt.clf()
104+
plt.df['Close']()
105+
plt.scatter(df1.index, df0.loc[df1.index].values, c=df1['bin'].values, cmap='vipridis')
106+
107+
#Test methods
108+
ols_tvalue = tValLinR( np.array([3.0, 3.5, 4.0]) )

0 commit comments

Comments
 (0)