So I've been through stack overflow and have used solutions from other posts.
But no matter what I try my ticks always remain as just ints and don't adopt the datetime format i yearn for. Any help would be appreciated!
from datetime import datetime, time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker
import mpl_finance
import MySQLdb
def isolated_candle_graph():
#Access my database
conn = MySQLdb.connect(host='localhost',
user='root',
passwd='*******',#
db='********') # falsified information
cursor = conn.cursor()
sql = "SELECT * FROM ddr"
cursor.execute(sql)
result = cursor.fetchall()
df = pd.DataFrame(list(result), columns=["Date", "Open", "High","Low", "Close", "Adj_Close", "Volume"])
fig, ax = plt.subplots()
#the plot
mpl_finance.candlestick2_ohlc(ax, df.Open, df.High, df.Low, df.Close,
width=0.6, colorup='r', colordown='c', alpha=1)
xdate = df.index
def mydate(x, pos):
try:
return xdate[int(x)]
except IndexError:
return ''
ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
plt.show()
isolated_candle_graph()
Thanks!
This is what I've been following.
matplotlib.finance.candlestick_ohlc plot intraday 1min bar data with time breaks and proper xticklabels at every hour
Related
I try to make a line graph with python and the graph only appears a little in the end of the canvas in the GUI.
import sqlite3
###----------------Connecting to the database-------------#####
DB = sqlite3.connect ("personal_project.db")
CURSOR = DB.cursor()
###----------------create the SQL command to create the table and save data-------------######
COMMAND1 = """CREATE TABLE IF NOT EXISTS
balance (
UserID INTEGER PRIMARY KEY,
Date TEXT,
Amount TEXT,
Descriotion)"""
CURSOR.execute(COMMAND1)
from tkinter import *
from tkinter import messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
###----------------Create the window-------------#####
main_WINDOW = Tk()
main_WINDOW.title("Study App")
main_WINDOW.geometry("1940x1080")#width*length
main_WINDOW.configure(bg="#ffffff")
###------Show Information Using Graph-------###
graquery = '''SELECT Date, Amount FROM balance'''
CURSOR.execute(graquery)
graresults = CURSOR.fetchall()
Date = [result[0] for result in graresults]
Amount = [result[1] for result in graresults]
figure = plt.figure()
plt.plot(Date, Amount)
plt.xlabel('Date')
plt.ylabel('Amount')
plt.title('Balance graph Graph')
gracanvas = Canvas(main_WINDOW, width=1070, height=452)
gracanvas.pack()
gracanvas.place(x=356, y=270)
figure_canvas = FigureCanvasTkAgg(figure, gracanvas)
gracanvas.create_window(0,0,window=figure_canvas.get_tk_widget())
I'm trying to make a real time graph for plotting stock data but I can't get .get_position to work. The error message I get is APIError: position does not exist and 404 Client Error: Not Found for url: https://paper-api.alpaca.markets/v2/positions/AAPL. If I follow the link directly I get a forbidden message.
import matplotlib.pyplot as plt
from itertools import count
from matplotlib.animation import FuncAnimation
import threading
import time
api_key = '<API_KEY>'
api_secret = '<SECRET_KEY>'
base_url = 'https://paper-api.alpaca.markets'
api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')
account = api.get_account()
def stock_grabber():
global position
SYMBOL = 'AAPL'
try:
position = api.get_position(symbol=SYMBOL)
except Exception as exception:
if exception.__str__() == 'position does not exist':
position = 0
print(position)
def threadz():
while True:
x = threading.Thread(target=stock_grabber)
x.start()
time.sleep(0.4)
t = threading.Thread(target=threadz)
t.start()
stock_grabber()
x = []
y = []
index = count()
def animate(i):
x.append(next(index))
y.append(position)
plt.cla()
plt.plot(x, y)
ani = FuncAnimation(plt.gcf(), animate, interval=400)
plt.tight_layout()
plt.show()```
I recently discovered that I am dumb. What I was trying to do was to get the real time price not the position.
instead of
position = api.get_position(symbol=SYMBOL)
use
position = (api.get_position('SYMBOL'))
realprice = position.current_price
Also the forbidden message was because I was on school wifi
I have a table stored in a database in MySQL.
I fetched the results using MySQL connector and copied it to DataFrame. There are no problems till that.
Now as I'm taking the results from MySQL, they are in the form of strings, so I've converted the strings to int for the values of CONFIRMED_CASES, and leave the STATE_NAME as str.
Now I want to plot it in a bar graph, with Numeric data as CONFIRMED_CASES and state names as STATE_NAME but it shows me this error:
Traceback (most recent call last):
File "c:\Users\intel\Desktop\Covid Tracker\get_sql_data.py", line 66, in <module>
fd.get_graph()
File "c:\Users\intel\Desktop\Covid Tracker\get_sql_data.py", line 59, in get_graph
ax = df.plot(y='STATE_NAME', x='CONFIRMED_CASES',
...
raise TypeError("no numeric data to plot")
TypeError: no numeric data to plot
Here's my code:
from operator import index
from sqlalchemy import create_engine
import mysql.connector
import pandas as pd
import matplotlib.pyplot as plt
mydb = mysql.connector.connect(
host="localhost",
user="abhay",
password="1234",
database="covid_db"
)
mycursor = mydb.cursor()
class fetch_data():
def __init__(self):
...
def get_data(self, cmd):
...
def get_graph(self):
mydb = mysql.connector.connect(
host="localhost",
user="abhay",
password="1234",
database="covid_db"
)
mycursor = mydb.cursor(buffered=True)
mycursor.execute(
"select CONFIRMED_CASES from india;")
query = mycursor.fetchall()
# the data was like 10,000 so I removed the ',' and converted it to int
query = [int(x[0].replace(',', '')) for x in query]
print(query)
query2 = mycursor.execute(
"select STATE_NAME from india;")
query2 = mycursor.fetchall()
# this is the query for state name and i kept it as str only...
query2 = [x[0] for x in query2]
print(query2)
df = pd.DataFrame({
'CONFIRMED_CASES': [query],
'STATE_NAME': [query2],
})
# it gives me the error here...
ax = df.plot(y='STATE_NAME', x='CONFIRMED_CASES',
kind='bar')
ax.ticklabel_format(style='plain', axis='y')
plt.show()
fd = fetch_data()
fd.get_graph()
I don't know why there is no numeric value. I set it to int, but still...
Your dataframe is defined using lists of a list. query and query2 are lists already. Define your dataframe as:
df = pd.DataFrame({
'CONFIRMED_CASES': query, # no brackets
'STATE_NAME': query2, # no brackets
})
Use below code for converting data to integer before plotting graph.
df['CONFIRMED_CASES'] = df['CONFIRMED_CASES'].astype('int64')
Heyy guys,
It's solved.
I used query.values and it worked...
I am trying to read the latest row from a table and plot the graph using animate and matplotlib in python. The table gets updated every 1 second with a new value. I need to simulate the graph by live plotting the values.
However, when I use animate function with an interval of 1 second, I get the same value for every interval fetch.
I am adding the code for your reference. Please let me know what I am missing. The same code is working good when I use a flat file instead of MySql table.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import mysql.connector
import pandas as pd
style.use('fivethirtyeight')
mydb = mysql.connector.connect(
host="xxxxxxxxxx",
user="xxxxx",
passwd="xxxxxxx",
database="sakila"
)
fig = plt.figure(figsize=(8,5))
ax = plt.subplot2grid((1,1), (0,0))
plt.ion()
cursor = mydb.cursor()
def animate(i):
df = pd.read_sql("SELECT * FROM DATA_TEST ORDER BY ID DESC LIMIT 1", mydb)
y = df["VALUE"]
x = df["ID"]
xs = []
ys = []
xs.append(x)
ys.append(float(y)*100)
ax.clear()
ax.plot(xs,ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
## TESTING CURSOR IN FOR LOOP
import mysql.connector
import pandas as pd
import time
mydb = mysql.connector.connect(
host="xxxxxxx",
user="xxxx",
passwd="xxxxxx",
database="xxxxx"
)
for i in range(10):
cursor = mydb.cursor()
cursor.execute("SELECT * FROM DATA_TEST ORDER BY ID DESC LIMIT 1")
result = cursor.fetchall()
print("Total rows are: ", len(result))
for j in result:
print(j[0])
print(j[1])
time.sleep(10)
cursor.close()
I want to create a simple chart with these library written below. Here is how I did:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import MySQLdb
def mysql_select_all():
conn = MySQLdb.connect(host='localhost',
user='root',
passwd='password',
db='databse')
cursor = conn.cursor()
sql = "SELECT price,size1 FROM 008_table"
cursor.execute(sql)
result = cursor.fetchall()
df = pd.DataFrame(list(sql),columns=["price","size1"])
x = df.price
y = df.size1
plt.title("Table", fontsize="24")
plt.scatter(x, y, s=100)
plt.xlabel("Size1")
plt.ylabel("Price")
plt.tick_params(axis='both',which='major',labelsize=14)
cursor.close()
print("Start")
mysql_select_all()
print("End")
I got the Value Error with this code, where should I fix this code ?
By:
df = pd.DataFrame(list(sql),columns=["price","size1"])
did you mean to type:
df = pd.DataFrame(list(result),columns=["price","size1"])
?