Skip to content

Commit

Permalink
Added more QuickChart types + examples
Browse files Browse the repository at this point in the history
  • Loading branch information
saeedamen committed May 7, 2020
1 parent 7da93fb commit b9167e7
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 61 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,11 @@ In finmarketpy/examples you will find several examples, including some simple tr

# finmarketpy log

* 07 May 2020
* Improved QuickChart, adding additional labels, fixing example
* 06 May 2020
* Added QuickChart for one line download of market data and plotting
* Added feature to resample returns
* Added feature to resample returns
* Allow more custom parameters in backtest
* 17 Dec 2019
* Added link for Python for finance workshop installation notes for Anaconda
Expand Down
43 changes: 36 additions & 7 deletions finmarketpy/economics/quickchart.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@
from chartpy import Chart, Style, ChartConstants
from findatapy.util.dataconstants import DataConstants
from findatapy.market import Market, MarketDataRequest, MarketDataGenerator
from findatapy.timeseries import Calculations

import datetime

from datetime import timedelta

dataconstants = DataConstants()

class QuickChart(object):
"""Displays charts from downloaded data, in a single line code call. Ideal for quickly generating charts
"""Displays charts from downloaded data, in a single line code call. Ideal for quickly generating charts from sources
including Bloomberg, Quandl, ALFRED/FRED etc.
"""

Expand All @@ -30,8 +34,13 @@ def __init__(self, engine='plotly', data_source='bloomberg', market_data_generat
self._market = Market(market_data_generator=market_data_generator)
self._data_source = data_source

def plot_chart(self, tickers=None, tickers_rhs=None, start_date=None, finish_date=None, chart_file=None, chart_type='line', title='',
fields={'close' : 'PX_LAST'}, freq='daily'):
def plot_chart(self, tickers=None, tickers_rhs=None, start_date=None, finish_date=None,
chart_file=None, chart_type='line', title='',
fields={'close' : 'PX_LAST'}, freq='daily', source='Web', brand_label='Cuemacro', display_brand_label=True,
reindex=False, yoy=False, plotly_plot_mode='offline_png',
quandl_api_key=dataconstants.quandl_api_key,
fred_api_key=dataconstants.fred_api_key,
alpha_vantage_api_key=dataconstants.alpha_vantage_api_key):

if start_date is None:
start_date = datetime.datetime.utcnow().date() - timedelta(days=60)
Expand Down Expand Up @@ -66,21 +75,41 @@ def plot_chart(self, tickers=None, tickers_rhs=None, start_date=None, finish_dat
md_request = MarketDataRequest(start_date=start_date, finish_date=finish_date,
freq=freq,
data_source=self._data_source,
tickers=list(tickers.keys()), vendor_tickers=list(tickers.keys()),
tickers=list(tickers.keys()), vendor_tickers=list(tickers.values()),
fields=list(fields.keys()),
vendor_fields=list(fields.values()))
vendor_fields=list(fields.values()),
quandl_api_key=quandl_api_key,
fred_api_key=fred_api_key,
alpha_vantage_api_key=alpha_vantage_api_key)

df = self._market.fetch_market(md_request=md_request)
df = df.fillna(method='ffill')
df.columns = [x.split('.')[0] for x in df.columns]

style = Style(title=title, chart_type=chart_type, html_file_output=chart_file, scale_factor=-1,
height=400, width=600, file_output=datetime.date.today().strftime("%Y%m%d") + " " + title + ".png",
plotly_plot_mode='offline_png')
plotly_plot_mode=plotly_plot_mode, source=source, brand_label=brand_label,
display_brand_label=display_brand_label)

if reindex:
df = Calculations().create_mult_index_from_prices(df)

style.y_title = 'Reindexed from 100'

if yoy:
if freq == 'daily':
obs_in_year = 252
elif freq == 'intraday':
obs_in_year = 1440

df_rets = Calculations().calculate_returns(df)
df = Calculations().average_by_annualised_year(df_rets, obs_in_year=obs_in_year) * 100

style.y_title = 'Annualized % YoY'

if list(tickers_rhs.keys()) != []:
style.y_axis_2_series=list(tickers_rhs.keys())
style.y_axis_2_showgrid = False
style.y_axis_showgrid = False

return self._chart.plot(df, style=style)
return self._chart.plot(df, style=style), df
Binary file modified finmarketpy_examples/boe-rate.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions finmarketpy_examples/quandl_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
market = Market(market_data_generator=MarketDataGenerator())

# Choose run_example = 0 for everything
# run_example = 1 - download BoE data from quandl
# run_example = 1 - download

run_example = 0

Expand Down Expand Up @@ -60,4 +60,4 @@
style.file_output = "boe-rate.png"
style.source = 'Quandl/BoE'

chart.plot(df, style=style)
chart.plot(df, style=style)
22 changes: 0 additions & 22 deletions finmarketpy_examples/quickchart_example.py

This file was deleted.

52 changes: 52 additions & 0 deletions finmarketpy_examples/quickchart_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
__author__ = 'saeedamen'

#
# Copyright 2020 Cuemacro
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and limitations under the License.
#

"""
Shows how to use QuickChart to quickly download data and plot it
"""

# Choose run_example = 0 for everything
# run_example = 1 - Plot S&P 500 charts with Matplotlib
# run_example = 1 - Plot FX chart with Plotly

run_example = 0

###### Plot with Matplotlib
if run_example == 1 or run_example == 0:
from finmarketpy.economics import QuickChart

# Plot with Matplotlib - S&P 500 on LHS y-axis and S&P 500 net long spec positioning on RHS y-axis
QuickChart(engine='matplotlib', data_source='bloomberg').plot_chart(tickers={'S&P500' : 'SPX Index'},
tickers_rhs={'Net long spec S&P 500 futures' : 'IMM0ENCN Index'},
title='S&P500 vs. net spec pos RHS (2008-2010)',
start_date='01 Jan 2007', finish_date='01 Jan 2010', source='Bloomberg')

# Plot with Matplotlib - S&P 500 YoY returns
QuickChart(engine='matplotlib', data_source='bloomberg').plot_chart(tickers={'S&P500' : 'SPX Index'},
title='S&P 500 YoY', chart_type='bar',
start_date='01 Jan 2007', yoy=True, source='Bloomberg')

###### Plot with Plotly and Matplotlib
if run_example == 2 or run_example == 0:
from finmarketpy.economics import QuickChart

# Plot with matplotlib - Major USD crosses reindexed from 100 in 2020
QuickChart(engine='matplotlib', data_source='bloomberg').plot_chart(tickers=['EURUSD Curncy', 'GBPUSD Curncy', 'AUDUSD Curncy'],
title='USD crosses in 2020',
start_date='01 Jan 2020', reindex=True, source='Bloomberg')

# Plot with Plotly - Major USD crosses reindexed from 100 in 2020
QuickChart(engine='plotly', data_source='bloomberg').plot_chart(tickers=['EURUSD Curncy', 'GBPUSD Curncy', 'AUDUSD Curncy'],
title='USD crosses in 2020 (Plotly)',
start_date='01 Jan 2020', reindex=True, source='Bloomberg')
29 changes: 0 additions & 29 deletions finmarketpy_examples/test.py

This file was deleted.

0 comments on commit b9167e7

Please sign in to comment.