I am trying to plot a candle stick chart in python. Here is my code
from pandas_datareader import data as pdr
import plotly.plotly as py
import plotly.graph_objs as go
import fix_yahoo_finance as yf
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py.iplot(data, filename='Candle Stick')
This is the error I am getting
PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'.
Any idea how I can draw a Candle Stick Chart?
The problem must be because you didn't provide the username and api key which you will get from the https://plot.ly/settings/api link. If you want to use plotly online to create this graph. First create an account, then get the username and api key and insert it in the below code.
from pandas_datareader import data as pdr
import plotly.plotly as py
import plotly.graph_objs as go
import fix_yahoo_finance as yf
py.sign_in('<<username here>>', '<<api key here>>')
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py.iplot(data, filename='Candle Stick')
There is another option of using plotly offline which does not need all this procedure, please find below the implementation code.
from pandas_datareader import data as pdr
import plotly.offline as py_offline
import plotly.graph_objs as go
import fix_yahoo_finance as yf
py_offline.init_notebook_mode()
yf.pdr_override()
mcd = pdr.get_data_yahoo("MCD", start="2004-01-01", end="2005-07-31")
mcd_candle = go.Candlestick(x=mcd.index,open=mcd.Open,high=mcd.High,low=mcd.Low,close=mcd.Close)
data = [mcd_candle]
py_offline.iplot(data, filename='Candle Stick')
#for Spyder plotting use the below line instead
#py_offline.plot(data, filename='Candle Stick')
Please make sure to install the libraries pandas_datareader and fix_yahoo_finance using pip, if these libraries are not already present!
Related
import ipywidgets as wd
import cufflinks as cf
import pandas as pd
import yfinance as yf
from plotly.offline import iplot,init_notebook_mode
from ipywidgets import interact,interact_manual
init_notebook_mode()
stocks=['QQQ','MSFT','GOOGL','FB','TSLA','AAPL']
indicators=['Bollinger Bands','MACD','RSI']
def ta_dashboard(asset,indicator,start_date,end_date,bb_k,bb_n,macd_fast,macd_slow,macd_signal,rsi_periods,rsi_upper,rsi_lower):
df=yf.download(asset,start=start_date,end=end_date,progress=False,auto_adjust=True)
qf=cf.QuantFig(df,title=f'TA Dashboard={asset}',legend='right',name=f'{asset}')
if 'Bollinger Bands' in indicator:
qf.add_bollinger_bands(periods=bb_n,boll_std=bb_k)
if 'MACD' in indicator:
qf.add_macd(fast_period=macd_fast,slow_period=macd_slow,signal_period=macd_signal)
if 'RSI' in indicator:
qf.add_rsi(period=rsi_periods,rsi_upper=rsi_upper,rsi_lower=rsi_lower,showbands=True)
return qf.iplot()
controls_dict={'asset':stocks_selector,
'indicator':indicator_selector,
'start_date':start_date_selector,
'end_date':end_date_selector,
'bb_k':k_param,
'bb_n':n_param,
'macd_fast':macd_fast,
'macd_slow':macd_slow,
'macd_signal':macd_signal,
'rsi_periods':rsi_period,
'rsi_upper':rsi_upper,
'rsi_lower':rsi_lower}
ui=wd.HBox([main_selector_box,secondary_selector_box])
out=wd.interactive_output(ta_dashboard,controls_dict)
I got the error message:
PlotlyRequestError: Authentication credentials were not provided which point to return qf.plot() part
I saw some post on stackoverflow says change iplot() to fig.show()
I want to change it to qf.show() but got another error qf don't have show()
what can I do now?
I notice this in recent github issue in cufflink respository.
Add cf.go_offline() help to solve the problem because now it have offline mode and online mode
I change it to
def ta_dashboard(asset,indicator,start_date,end_date,bb_k,bb_n,macd_fast,macd_slow,macd_signal,rsi_periods,rsi_upper,rsi_lower):
cf.go_offline()
df=yf.download(asset,start=start_date,end=end_date,progress=False,auto_adjust=True)
qf=cf.QuantFig(df,title=f'TA Dashboard={asset}',legend='right',name=f'{asset}')
if 'Bollinger Bands' in indicator:
qf.add_bollinger_bands(periods=bb_n,boll_std=bb_k)
if 'MACD' in indicator:
qf.add_macd(fast_period=macd_fast,slow_period=macd_slow,signal_period=macd_signal)
if 'RSI' in indicator:
qf.add_rsi(period=rsi_periods,rsi_upper=rsi_upper,rsi_lower=rsi_lower,showbands=True)
return qf.iplot()
and it works
From Cufflinks github issue: https://github.com/santosjorge/cufflinks/issues/267
I have this code from this website:
https://geopandas.org/en/stable/docs/user_guide/interactive_mapping.html
import geopandas as gpd
import matplotlib.pyplot as plt
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
world.explore(column='pop_est',cmap='Set2')
plt.show()
I try to run the code, the geodataframe data is printed but no plot is shown.
What am i missing?
Thnx in advanced.
world.explore(column='pop_est',cmap='Set2') should return and display a folium map object so you shouldn't need that plt.show() as the bottom.
Also, since you're using an IDE (not jupyter) we need to write the map to disk then open it up in the broswer.
Try
import geopandas as gpd
import webbrowser
import os
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
# world.explore() returns a folium map
m = world.explore(column='pop_est',cmap='Set2')
# and then we write the map to disk
m.save('my_map.html')
# then open it
webbrowser.open('file://' + os.path.realpath('my_map.html'))
export() creates a folium object, not a matplotlib figure
in jupyter just have m as last item in code cell
in other environments you can save as HTML and launch into a browser
import geopandas as gpd
import webbrowser
from pathlib import Path
world_filepath = gpd.datasets.get_path('naturalearth_lowres')
world = gpd.read_file(world_filepath)
print(world.head())
m = world.explore(column='pop_est',cmap='Set2')
f = Path.cwd().joinpath("map.html")
m.save(str(f))
webbrowser.open("file://" + str(f))
I'm trying to build an interactive, simple choropleth heatmap of all the countries in Asia. The plot displays well when in my Jupyter Notebook, but when I try to export it to html, it shows only blank.
The GeoJSON file that I'm using is this one, it's the first result when I google "asia geojson"
A preview of my DataFrame file can be seen here.
My code:
import pandas
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
import plotly
fig = px.choropleth(df, geojson=asia, locations='country', color='population', color_continuous_scale="reds", scope = 'asia', featureidkey="properties.admin", labels={'population':'Population Count'}, center={"lat": 30, "lon": 100})
fig.show()
plotly.offline.plot(fig, filename='myplot.html')
[Screenshot] How it looks on my Jupyter Notebook
[Screenshot] How it looks on my web browser
As we can see, the .html file shows nothing when opened in my web browser. I've read the documentations and the majority of users having similar problems, yet I can't seem to make mine work.
I tried to plot the sample dataset of USA Census Data from their official guide and it exports normally into .html, as expected.
How can I fix this? Any help would be appreciated :)
Here is an example code to output to html format. The geojson file you are using is associated with the data used on the official plotly website, and saved in an html file. My environment is jupyterLab 2.2.0 to check the file saving.
Data for some countries is not shown, but if you replace it with your own data, it should be fine.
from urllib.request import urlopen
import json
with urlopen('https://gist.githubusercontent.com/hrbrmstr/94bdd47705d05a50f9cf/raw/0ccc6b926e1aa64448e239ac024f04e518d63954/asia.geojson') as response:
asia = json.load(response)
import plotly.express as px
df = px.data.gapminder().query("year==2007")
fig = px.choropleth(df, geojson=asia,
locations='iso_alpha',
color='pop',
color_continuous_scale="reds",
scope = 'asia',
featureidkey="properties.sov_a3",
labels={'population':'Population Count'},
center={"lat": 30, "lon": 100})
fig.show()
fig.write_html("myplot.html")
EDIT: Try this.
I have imported plotly offline as pyo and ran your fig via pyo.plot() which outputs an html file to the dir of your notebook.
from urllib.request import urlopen
import json
with urlopen('https://gist.githubusercontent.com/hrbrmstr/94bdd47705d05a50f9cf/raw/0ccc6b926e1aa64448e239ac024f04e518d63954/asia.geojson') as response:
asia = json.load(response)
import plotly.express as px
import plotly.offline as pyo
df = px.data.gapminder().query("year==2007")
fig = px.choropleth(df, geojson=asia,
locations='iso_alpha',
color='pop',
color_continuous_scale="reds",
scope = 'asia',
featureidkey="properties.sov_a3",
labels={'population':'Population Count'},
center={"lat": 30, "lon": 100})
fig.show()
pyo.plot(fig)
class AQGraph:
import pandas as pd
import numpy as np
import matplotlib as plt
PrimaryA = pd.read_csv('PrimaryA.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryA sensor
PrimaryB = pd.read_csv('PrimaryB.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryB sensor
AverageData = np.mean(PrimaryA[:][2], PrimaryB[:][2])
print(AverageData)
plt.plot(PrimaryA[:][0], AverageData)
plt.show()
Attached is my python code. I'm running it in Pycharm and for some reason the green arrow that pops up for Pycharm files isn't there. I've looked through my settings and I'm running Python 3.7. Any advice?
The code you provided, doesn't comply with python rules and standards.
there is a class in your code without any constructor or any method.
Also, you didn't follow Python's indentation policy. Based on what you provided, as soon as you try to run it you should see an error.
import pandas as pd
import numpy as np
import matplotlib as plt
class AQGraph:
#staticmethod
def a_method():
PrimaryA = pd.read_csv('PrimaryA.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryA sensor
PrimaryB = pd.read_csv('PrimaryB.csv') # Daily data from 12/1/19 to 4/16/20 from PrimaryB sensor
AverageData = np.mean(PrimaryA[:][2], PrimaryB[:][2])
print(AverageData)
plt.plot(PrimaryA[:][0], AverageData)
plt.show()
if __name__ == "__main__":
AQGraph.a_method()
In the command line try:
> python python_file.py
I am trying to connect to FXCM throuhg an api and am constantly getting an error:
|ERROR|2020-01-11 20:42:41,825|Socket returns an error: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')")).
The code is :
import fxcmpy
import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
from datetime import date
import numpy as np
TOKEN = "hidden"
con = fxcmpy.fxcmpy(access_token=TOKEN, log_level='error')
I have been using this for a while now but error suddenly showed up today. How can i fix this?
I got the same problem. I got an email from api#fxcm.com below.
"We did a release on demo on 1/12 to improve the Rest API.
With that said, Our REST API wrapper fxcmpy has been updated, you need to install the latest fxcmpy version at 1.2.6.
Here is the link where you can find the library: https://pypi.org/project/fxcmpy/#files
Please have in mind that just with pip install fxcmpy it might not work as it won’t update the library, please use below command."
pip install –U fxcmpy