How to Plot Candlestick chart and indicators Using quantmod? - python

A few days back, accidentally, I was able to plot technical indicators using these codes
ch.add_BBANDS()
ch.add_RSI(14)
But now I am not able to do so as I am having a problem installing quantmod.
I know we can plot candlestick chart by using plotly but with quantmod there seems to be a single line code which would be easier.
I realized that the problem is in Installing and importing quantmod as it says:
ImportError:
The plotly.plotly module is deprecated,
please install the chart-studio package and use the
chart_studio.plotly module instead.
I also tried to degrade my plotly version as mentioned here but nothing worked. I want to know if someone has been able to install and import quantmod in jupyter notebook and plot some of the charts as indicated by following codes. I would appreciate if you show me the correct way to get quantmod working in my jupyter notebook.
ch = qm.Chart(df)
ch.to_figure(type='ohlc', dimensions=(2560,1440))
ch = qm.Chart(df)
ch.add_BBANDS()
ch.add_RSI(14)
ch.to_figure(type='candlestick', title='EQUITY')

Try using QuantFig to get what you are trying to get. Chart studio now requires a sign in. QuantFig uses the index of the pandas dataframe as the x axis for the chart. So take care to format it. the columns shall be named 'open', 'high', 'low', close' as it is expected by QuantFig. you can use the following snippet for inspiration.
import chart_studio.plotly as py
import cufflinks as cf
import python as pd
py.sign_in('Python-Demo-Account', 'gwt101uhh0')
def plotData(df=None):
if df == None:
df=cf.datagen.ohlc()
qf=cf.QuantFig(df,title='First Quant Figure',legend='top',name='GS')
qf.add_bollinger_bands()
qf.add_rsi()
fig = qf.iplot(asFigure=True)
fig.show()
plotData()

Related

Can't run Python visual element in Power BI

I'm trying to create a hist plot in Power BI.
I got installed ANaconda, MS Vusial Code.
Screenshots with my settings:
I'm trying make hist with simple table with 1 column.
The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script:
dataset = pandas.DataFrame(reg_min_ses_dt)
dataset = dataset.drop_duplicates()
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.histplot(data=dataset['reg_min_ses_dt'])
plt.show()
But I get this error:
I think, I just didn't set up some python extension or something else.
I just want make Python visual like this.
You need to activate conda before you can use its packages in PBIDesktop.exe. Simple as that.

Plotly express doesn't load and refuse to connect

I have this simple program that should display a pie chart, but whenever I run the program, it opens a page on Chrome and just keeps loading without any display, and sometimes it refuses to connect. How do I solve this?
P.S: I would like to use it offline, and I'm running it using cmd on windows10
import pandas as pd
import numpy as np
from datetime import datetime
import plotly.express as px
def graph(dataframe):
figure0 = px.pie(dataframe,values=dataframe['POPULATION'],names=dataframe['CONTINENT'])
figure0.show()
df = pd.DataFrame({'POPULATION':[60,17,9,13,1],'CONTINENT':['Asia','Africa','Europe','Americas','Oceania']})
graph(df)
Disclaimer: I extracted this answer from the OPs question. Answers should not be contained in the question itself.
Answer provided by g_odim_3:
So instead of figure0.show(), I used figure0.write_html('first_figure.html', auto_open=True) and it worked:
import pandas as pd
import numpy as np
from datetime import datetime
import plotly.express as px
def graph(dataframe):
figure0 = px.pie(dataframe,values=dataframe['POPULATION'],names=dataframe['CONTINENT'],title='Global Population')
# figure0.show()
figure0.write_html('first_figure.html', auto_open=True)
df = pd.DataFrame({'POPULATION':[60,17,9,13,1],'CONTINENT':['Asia','Africa','Europe','Americas','Oceania']})
graph(df)
I'm 99% sure that this is a version issue. It's a long time since you needed an internet connection to build Plotly figures. Follow the instructions here on how to upgrade your system. I've tried your exact code on my end at it produces the following plot:
I'm on Plotly 5.2.2. Run import plotly and plotly.__version__ to check the version on your end.

How to convert a pandas plot into an image

I am working on an app which will be able to show a graph of the company's performance in stocks, I wanted to turn the pandas plot of that company into an image without saving it. Can someone tell me what to do?
from fastquant import get_pse_data
import matplotlib.pyplot as plt
import pandas as pd
df = get_pse_data(symbol, '2019-01-01', '2020-01-01')
ma30 = df.close.rolling(30).mean()
close_ma30 = pd.concat([df.close, ma30], axis=1).dropna()
I am actually thinking of adding this plot derived from a pandas dataframe close_ma30 = pd.concat([df.close, ma30], axis=1).dropna() into my html code:
I want to create a python function that will allow me to return it as an image for a django code. Thank you for the help!
You can use Dataframe-image to convert a pandas plot into a image, you can Visit https://pypi.org/project/dataframe-image/.
dataframe_image has the ability to export both normal and styled DataFrames as images from within a Python script. Pass your normal or styled DataFrame to the export function along with a file location to save it as an image.
>>> import dataframe_image as dfi
>>> dfi.export(df_styled, 'df_styled.png')
You may also export directly from the DataFrame or styled DataFrame using the dfi.export and export_png methods, respectively.
>>> df.dfi.export('df.png')
>>> df_styled.export_png('df_styled.png)
As a Python Library
Dataframe_image can also be used outside of the notebook as a normal Python library. In a separate Python script, import the dataframe_image package and pass the file name of your notebook to the convert function.
>>> import dataframe_image as dfi
>>> dfi.convert('path/to/your_notebook.ipynb',
to='pdf',
use='latex',
center_df=True,
max_rows=30,
max_cols=10,
execute=False,
save_notebook=False,
limit=None,
document_name=None,
table_conversion='chrome'
chrome_path=None,
latex_command=None,
output_dir=None,
)
By default, the new file(s) will be saved in the same directory where the notebook resides. Do not run this command within the same notebook that is being converted.
From the Command Line
The command line tool dataframe_image will be available upon installation with the same options as the convert function from above.
dataframe_image --to=pdf "my notebook with dataframes.ipynb"
Finding Google Chrome
You must have Google Chrome (or Brave) installed in order for dataframe_image to work. The path to Chrome should automatically be found. If Chrome is not in a standard location, set it with the chrome_path parameter.
Using matplotlib instead of Chrome
If you do not have Chrome installed or cannot get it to work properly, you can alternatively use matplotlib to convert the DataFrames to images. Select this option by setting the table_conversion parameter to 'matplotlib'.
Publish to Medium
Closely related to this package is jupyter_to_medium, which publishes your notebooks directly and quickly as Medium blog posts.
Dependencies
You must have the following Python libraries installed.

Plotting a geopandas dataframe using plotly

I have a geopandas dataframe, which consists of the region name(District), the geometry column, and the amount column. My goal is to plot a choropleth map using the method mentioned below
https://plotly.com/python/choropleth-maps/#using-geopandas-data-frames
Here’s a snippet of my dataframe
I also checked that my columns were in the right format/type.
And here's the code I used to plot the map
fig = px.choropleth(merged,
geojson=merged.geometry,
locations=merged.index,
color="Amount")
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
It produced the below figure
which is obviously not the right figure. For some reasons, it doesn't show the map, instead it shows a line and when I zoom in, I am able to see the map but it has lines running through it. Like this
Has anyone ran into a similar problem? If so how were you able to resolve it?
The Plotly version I am using is 4.7.0. I have tried upgrading to a most recent version but it still didn’t work.
Any help is greatly appreciated. Please find my code and the data on my github.
I'll give you the answer to #tgrandje's comment that solved the problem. Thanks to #Poopah and #tgrandje for the opportunity to raise the answer.
import pandas as pd
import plotly.express as px
import geopandas as gpd
import pyproj
# reading in the shapefile
fp = "./data/"
map_df = gpd.read_file(fp)
map_df.to_crs(pyproj.CRS.from_epsg(4326), inplace=True)
df = pd.read_csv("./data/loans_amount.csv")
# join the geodataframe with the cleaned up csv dataframe
merged = map_df.set_index('District').join(df.set_index('District'))
#merged = merged.reset_index()
merged.head()
fig = px.choropleth(merged, geojson=merged.geometry, locations=merged.index, color="Amount")
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
Another possible source of the problem (when using Plotly graph_objects) is mentioned in this answer over at gis.stackexchange.com:
The locations argument has to point to a column that matches GeoJSON's 'id's.
The geojson argument expects a dictionary.
To solve your problem, you should: (i) point locations to the dataframe's index, and (ii) turn your GeoJSON string to a dictionary.
It's not exactly the answer to your question, but I thought my problem was the same as yours and this helped me. So I am including the answer here.

How can I access IPython's "display" function?

I tried this code, expecting it to use IPython's display function:
import pandas as pd
data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])
display(data.head(10))
But I get an error message that says NameError: name 'display' undefined. Why? How do I make it so that I can use display?
display is a function in the IPython.display module that runs the appropriate dunder method to get the appropriate data to ... display. If you really want to run it
from IPython.display import display
import pandas as pd
data = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['Tweets'])
display(data.head(10))
But don't. IPython is already doing that for you. Just do:
data.head(10)
You even might have IPython uninstalled, try:
pip install IPython
or if running pip3:
pip3 install IPython
To solve the problem on pycaret, you have to open the below file -
..\env\Lib\site-packages\pycaret\datasets.py
and add the line of code -
from IPython.display import display

Categories