Skip to content

Commit

Permalink
New features added
Browse files Browse the repository at this point in the history
  • Loading branch information
Dayal Chand Aichara committed Jul 9, 2019
1 parent c0982dd commit ac102fd
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 29 deletions.
Binary file modified PriceIndices/__pycache__/crypto_history.cpython-36.pyc
Binary file not shown.
Binary file modified PriceIndices/__pycache__/price_indicators.cpython-36.pyc
Binary file not shown.
50 changes: 28 additions & 22 deletions PriceIndices/price_indicators.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import warnings
warnings.filterwarnings('ignore')


class Indices(object):
class Indices:

def __abs__(self):

def get_bvol_index(self, price_data):
def get_bvol_index(price_data):

"""
Volatility Index is a measure of market's expectation of volatility over the near term.
Expand All @@ -22,6 +19,7 @@ def get_bvol_index(self, price_data):
:param price_data: pandas DataFrame
:return: pandas DataFrame
"""

try:
df = price_data
df = df.sort_values(by='date').reset_index(drop=True)
Expand All @@ -35,12 +33,12 @@ def get_bvol_index(self, price_data):
except Exception as e:
return e

def get_bvol_graph(self, bvol_data):
def get_bvol_graph(bvol_data):

"""Make a line graph of bvol index with respect to time"""
try:
df = bvol_data
fig, ax = plt.subplots(figsize=(16, 12))
fig, ax = plt.subplots(figsize=(14, 12))
rect = fig.patch
rect.set_facecolor('yellow')
ax1 = plt.subplot(211)
Expand All @@ -57,19 +55,18 @@ def get_bvol_graph(self, bvol_data):
plt.ylabel('Volatility Index', color='r', fontsize=20)
plt.legend()
plt.setp(ax2.xaxis.get_majorticklabels(), rotation=90)
ax2.xaxis.set_major_locator(ticker.MultipleLocator(30))
ax2.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)

ax2.tick_params(axis='x', colors='b')
ax2.tick_params(axis='y', colors='b')

plt.suptitle('Price and Volatility Index', color='red', fontsize=24)
plt.savefig('bvol_index.png')
plt.savefig('bvol_index.png',bbox_inches='tight', facecolor='orange')
return plt.show()
except Exception as e:
return e

def get_rsi(self, price_data):
def get_rsi(price_data):

"""
Type:
Expand All @@ -91,7 +88,7 @@ def get_rsi(self, price_data):
"""
try:
df = price_data
df['price_change'] = (df['price'] - df['price'].shift(1))
df['price_change'] = df['price'] - df['price'].shift(1)
df = df.dropna()
df['gain'] = df['price_change'].apply(lambda x: x if x >= 0 else 0)

Expand All @@ -118,7 +115,7 @@ def get_rsi(self, price_data):
def get_rsi_graph(rsi_data):
try:
df = rsi_data
fig, ax = plt.subplots(figsize=(16, 12))
fig, ax = plt.subplots(figsize=(14, 12))
rect = fig.patch
rect.set_facecolor('yellow')
ax1 = plt.subplot(211)
Expand All @@ -132,11 +129,10 @@ def get_rsi_graph(rsi_data):
ax2.plot(df['date'], df['RSI_2'], color='b', label='RSI')
plt.xlabel('Time', color='red', fontsize=20)
plt.ylabel('Relative Strength Index (RSI)', color='r', fontsize=20)
plt.text('2019-06-01', 71.5, '>70 OverBought', fontsize=20, color='green')
plt.text('2019-06-01', 23, '<30 OverSold', fontsize=20, color='green')
plt.text(df['date'][int(len(df)/2)], 80, '>70 OverBought', fontsize=20, color='black')
plt.text(df['date'][int(len(df)/2)], 15, '<30 OverSold', fontsize=20, color='black')
plt.legend()
plt.setp(ax2.xaxis.get_majorticklabels(), rotation=90)
ax2.xaxis.set_major_locator(ticker.MultipleLocator(30))

ax2.tick_params(axis='x', colors='b')
ax2.tick_params(axis='y', colors='b')
Expand All @@ -145,12 +141,12 @@ def get_rsi_graph(rsi_data):
ax2.axhline(y=30, color='r')

plt.suptitle('Price and Relative Strength Index', color='red', fontsize=24)
plt.save('rsi.png')
return plot.show()
plt.savefig('rsi.png', bbox_inches='tight', facecolor='orange')
return plt.show()
except Exception as e:
return e

def get_bollinger_bands(self, price_data, days=20):
def get_bollinger_bands(price_data, days=20):
"""
Type:
Trend, volatility, momentum indicator
Expand Down Expand Up @@ -178,7 +174,7 @@ def get_bollinger_bands(self, price_data, days=20):
df['pluse'] = df['SMA'] + df['SD']*2
df['minus'] = df['SMA'] - df['SMA']*2

fig, ax = plt.subplots(figsize=(20, 16))
fig, ax = plt.subplots(figsize=(16, 12))
plt.plot(df['date'], df['pluse'], color='g')
plt.plot(df['date'], df['minus'], color='g')
plt.plot(df['date'], df['price'], color='orange')
Expand All @@ -189,13 +185,13 @@ def get_bollinger_bands(self, price_data, days=20):
plt.tick_params(labelsize =17)
fig.set_facecolor('yellow')
plt.grid()
plt.savefig('bollinger_bands.png', bbox_inches='tight', facecolor='yellow')
plt.savefig('bollinger_bands.png', bbox_inches='tight', facecolor='orange')
plt.show()
return df
except Exception as e:
return e

def moving_average_convergence_divergence(self, price_data):
def get_moving_average_convergence_divergence(price_data):
"""
Type
Trend and momentum indicator
Expand All @@ -212,10 +208,19 @@ def moving_average_convergence_divergence(self, price_data):
:param price_data: pandas DataFrame
:return:
"""
try:
df = price_data
df['SMA_12'] = df['price'].rolling(12).mean()
df['SMA_26'] = df['price'].rolling(26).mean()
df['MACD'] = df['SMA_12'] - df['SMA_26']
df = df.dropna()
return df
except Exception as e:
return print('MACD Error - {}'.format(e))



def simple_moving_average(self, price_data, days):
def get_simple_moving_average(price_data, days):
"""
Simple moving average of given days
:param price_data: pandas DataFrame
Expand All @@ -225,6 +230,7 @@ def simple_moving_average(self, price_data, days):
try:
df = price_data
df['SMA'] = df['price'].rolling(days).mean()
df = df.dropna()
return df
except Exception as e:
return print('SMA Error - {}'.format(e))
Expand Down
47 changes: 40 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ from PriceIndices import MarketHistory, Indices
```python
>>> history = MarketHistory()

>>> df = history.get_history('bitcoin', '20130428', '20190624') # Get Market History
>>> df.head()
>>> df_history = history.get_history('bitcoin', '20130428', '20190624') # Get Market History
>>> df_history.head()
Date Open* High Low Close** Volume Market Cap
0 2019-06-23 10696.69 11246.14 10556.10 10855.37 20998326502 192970090355
1 2019-06-22 10175.92 11157.35 10107.04 10701.69 29995204861 190214124824
Expand All @@ -35,9 +35,9 @@ from PriceIndices import MarketHistory, Indices
4 2019-06-19 9078.73 9299.62 9070.40 9273.52 15546809946 164780855869


>>> df = history.get_price('bitcoin', '20130428', '20190624') # Get closing price
>>>price_data = history.get_price('bitcoin', '20130428', '20190624') # Get closing price

>>> df.head()
>>> price_data .head()
date price
0 2019-06-23 10855.37
1 2019-06-22 10701.69
Expand All @@ -46,7 +46,7 @@ from PriceIndices import MarketHistory, Indices
4 2019-06-19 9273.52


>>> df_bvol = Indices.get_bvol_index(df) # Calculate Volatility Index
>>> df_bvol = Indices.get_bvol_index(price_data ) # Calculate Volatility Index
>>> df_bvol.head()
date price BVOL_Index
0 2019-06-22 10701.69 0.636482
Expand All @@ -60,8 +60,12 @@ from PriceIndices import MarketHistory, Indices
"""
This will return a plot of BVOL index against time also save volatility index plot in your working directory as 'bvol_index.png'
"""
```
![](plots/bvol_index.png)

```python

>>> df_rsi = Indices.get_rsi(df) # Calculate RSI
>>> df_rsi = Indices.get_rsi(price_data) # Calculate RSI

>>> print(df_rsi.tail())
date price price_change gain loss gain_average loss_average RS RSI_1 RS_Smooth RSI_2
Expand All @@ -76,7 +80,10 @@ This will return a plot of BVOL index against time also save volatility index pl
"""
This will return a plot of RSI against time and also save RSI plot in your working directory as 'rsi.png'
"""
>>> df_bb = Indices.get_bollinger_bands(df, 20) # Get Bollinger Bands and plot
```
![](plots/rsi.png)
```python
>>> df_bb = Indices.get_bollinger_bands(price_data , 20) # Get Bollinger Bands and plot
>>> df_bb.tail()
date price SMA SD pluse minus
2243 2013-05-02 105.21 115.2345 6.339257 127.913013 -115.2345
Expand All @@ -90,7 +97,33 @@ This will also save Bollingers bands plot in your working directory as 'bollinge
"""

```
![](plots/bollinger_bands.png)

```python

>>> df_macd= Indices.get_moving_average_convergence_divergence(price_data ) # Get moving average convergence divergence

>>> df_macd.tail()
date price SMA_12 SMA_26 MACD
2257 2013-05-02 105.21 112.235833 118.603077 -6.367244
2258 2013-05-01 116.99 112.153333 118.112692 -5.959359
2259 2013-04-30 139.00 114.153333 118.325000 -4.171667
2260 2013-04-29 144.54 116.595000 118.808077 -2.213077
2261 2013-04-28 134.21 118.012500 118.846923 -0.834423

```
```python
>>> df_sma = Indices.get_simple_moving_average(price_data,20) # Get simple moving average
>>> df_sma.tail()
date price SMA
2257 2013-05-02 105.21 115.2345
2258 2013-05-01 116.99 114.9400
2259 2013-04-30 139.00 115.7900
2260 2013-04-29 144.54 116.9175
2261 2013-04-28 134.21 117.4530


```
### License
[MIT](https://choosealicense.com/licenses/mit/) © [Dayal Chand Aichara](https://github.com/dc-aichara)

Expand Down
Binary file added plots/bollinger_bands.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added plots/bvol_index.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added plots/rsi.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit ac102fd

Please sign in to comment.