> ## Documentation Index
> Fetch the complete documentation index at: https://knowledge.cloudquant.com/llms.txt
> Use this file to discover all available pages before exploring further.

# CloudQuant Charting

> Python library for creating branded financial visualizations including candlestick charts, histograms, line charts, bar charts, and more.

# CloudQuant charting

CloudQuant Charting is a Python library for creating branded financial visualizations using the CloudQuant Data Liberator API.

**Import statement:**

```python theme={null}
from liberator import charting
```

## Chart types

### Histogram

Generates distribution/histogram charts with CloudQuant branding.

**Returns:** `plotly.graph_objs._figure.Figure`

**Required arguments:**

* `df` - pandas DataFrame containing data
* `col` - string name of column to visualize

**Optional arguments:**

* `title`, `xlabel`, `ylabel` - support HTML tags like `<b>`, `<i>`, `<br>`
* `histnorm` - normalization type: `'percent'`, `'probability'`, `'density'`, or `'probability density'`
* `width`, `height` - dimensions in pixels (min 400px)
* `overlay_df`, `overlay_col` - add comparison series

**Example:**

```python theme={null}
import liberator
from liberator import charting

res = liberator.query(name="daily_bars")
df_bars = liberator.get_dataframe(res)
df_bars = df_bars.sort_values(by=['volume'], ascending=[False])
change = df_bars.close - df_bars.open
df_bars["change"] = change

fig = charting.Histogram(
    df=df_bars[0:100],
    col="change",
    title="<b>Change Px Distribution</b> <br>of last trading day's top 100 High Volume Stocks",
    width=800,
    height=400,
    histnorm="probability"
)
fig.show()
```

### Candlestick

Generates OHLC candlestick charts with optional technical studies and overlays.

**Returns:** Single figure or array of figures (depending on studies)

**Required arguments:**

* `df` - DataFrame with OHLC data (minimum 20 bars)

**Optional arguments:**

* `title`, `xlabel`, `ylabel` - chart labels with HTML support
* `width`, `height` - dimensions (min 700px width, 400px height)
* `open`, `high`, `low`, `close`, `timestamp` - column names
* `entry_px`, `entry_time`, `close_px`, `close_time`, `entry_side` - trade annotations
* `overlay_df`, `overlay_col`, `overlay_col2` - secondary axis data

**Supported Studies (Single Figure):**
`BBANDS`, `DEMA`, `EMA`, `HT_TRENDLINE`, `KAMA`, `MA`, `MAMA`, `MIDPOINT`, `MIDPRICE`, `SAR`, `SAREXT`, `SMA`, `T3`, `TEMA`, `TRIMA`, `WMA`

**Supported Studies (Array of Figures):**
`ADX`, `ADXR`, `APO`, `AROON`, `AROONOSC`, `BOP`, `CCI`, `CMO`, `DX`, `MACD`, `MACDEXT`, `MFI`, `MINUS_DI`, `MINUS_DM`, `MOM`, `PLUS_DI`, `PLUS_DM`, `PPO`, `ROC`, `ROCP`, `ROCR`, `ROCR100`, `RSI`, `STOCH`, `STOCHF`, `STOCHRSI`, `TRIX`, `ULTOSC`, `WILLR`, `ATR`, `MACDFIX`, `NATR`, `TRANGE`

**Example:**

```python theme={null}
import liberator
import pandas as pd
from liberator import charting
from datetime import datetime, timedelta

back_to = (datetime.now() + timedelta(days=-360)).strftime('%Y-%m-%d 23:59:59')
symbol = "SPY"

res = liberator.query(name="daily_bars", symbols=symbol, back_to=back_to)
df_bars = liberator.get_dataframe(res)

res = liberator.query(name="eia_gas_prices", back_to=back_to)
gaspx = liberator.get_dataframe(res)

fig = charting.Candlestick(
    df=df_bars,
    overlay_df=gaspx,
    overlay_col="retail_gas_price",
    height=700,
    width=800,
    xlabel="Date",
    title="SPY vs Retail Gas Prices"
)
fig.show()
```

### LineChart

Creates line charts with support for studies and secondary Y-axis.

**Returns:** `plotly.graph_objs._figure.Figure`

**Required arguments:**

* `df` - pandas DataFrame
* `cols` - list of column names to plot
* `x_column` - column name for X-axis (defaults to index)

**Optional arguments:**

* `title`, `xlabel`, `ylabel` - chart labels with HTML support
* `width`, `height` - dimensions
* `y2axis_name` - activates secondary Y-axis
* `overlay_df`, `overlay_cols` - secondary axis data
* `study` - technical study name
* `study_columns` - columns for study calculation
* `timeperiod` - study periods

**Supported Studies:**
`BBANDS`, `MAMA`, `DEMA`, `EMA`, `HT_TRENDLINE`, `KAMA`, `MA`, `MIDPOINT`, `MIDPRICE`, `SAR`, `SAREXT`, `SMA`, `T3`, `TEMA`, `TRIMA`, `WMA`

**Example:**

```python theme={null}
import cloudquantcharting
import liberator

res = liberator.query(
    symbols='AMZN',
    name='Twitter',
    back_to='12/22/2020 08:00:00',
    as_of='12/22/2020 16:00:00'
)
twitter_df = liberator.get_dataframe(res)

fig = cloudquantcharting.LineChart(
    df=twitter_df,
    cols=['s-score', 's-buzz', 's', 's-mean', 'sv-score', 's-dispersion', 's-buzz', 's-delta'],
    x_column="timestamp"
)
fig.show()
```

### BarChart

Generates bar charts, including stacked bars for repeated X values.

**Returns:** `plotly.graph_objs._figure.Figure`

**Required arguments:**

* `df` - pandas DataFrame
* `xcol` - column name for X-axis
* `ycol` - numeric column for Y-axis

**Optional arguments:**

* `title`, `xlabel`, `ylabel` - labels with HTML support
* `width`, `height` - dimensions
* `singlecolor` - boolean for uniform color (defaults `True`)
* `orientation` - `'v'` (vertical) or `'h'` (horizontal)

**Example:**

```python theme={null}
import liberator
import pandas as pd
from liberator import charting

res = liberator.query(name="daily_bars")
df_bars = liberator.get_dataframe(res)
df_bars = df_bars.sort_values(by=['volume'], ascending=[False])

fig = charting.BarChart(
    df=df_bars[0:20],
    xcol="symbol",
    ycol="spread",
    title="Spread Price of High Volume Stocks",
    width=800,
    height=400
)
fig.show()
```

### PieChart

Generates pie/donut charts with customizable hole size.

**Returns:** `plotly.graph_objs._figure.Figure`

**Required arguments:**

* `df` - pandas DataFrame
* `labelcol` - column name for labels
* `valuecol` - numeric column for slice size

**Optional arguments:**

* `title` - chart title with HTML support
* `width`, `height` - dimensions
* `hole` - donut hole size (0-1, where 0 = no hole)
* `colors` - color sequence: default CQ palette, or `'reds'`, `'greens'`, `'blues'`

**Example:**

```python theme={null}
import liberator
import pandas as pd
from liberator import charting

values = [
    ['Jan', '150000', 'USD'],
    ['Feb', '200000', 'USD'],
    ['Mar', '330000', 'USD'],
    ['Apr', '440000', 'USD'],
    ['May', '555000', 'USD'],
    ['June', '355000', 'USD'],
    ['July', '150000', 'USD'],
    ['Aug', '130000', 'USD'],
    ['Sept', '330000', 'USD'],
    ['Oct', '440000', 'USD'],
    ['Nov', '130000', 'USD'],
    ['Dec', '330000', 'USD']
]
df = pd.DataFrame(values, columns=["month", "sales", "currency"])
title = "<B>Sales</b><br>by month"

fig = charting.PieChart(
    df=df,
    labelcol='month',
    valuecol="sales",
    title=title,
    height=700
)
fig.show()
```

### GroupedBarChart

Generates grouped bar charts comparing multiple numeric columns.

**Returns:** `plotly.graph_objs._figure.Figure`

**Required arguments:**

* `df` - pandas DataFrame
* `groups` - column name for grouping
* `values` - list of numeric column names

**Optional arguments:**

* `title`, `group_label`, `value_label` - labels with HTML support
* `width`, `height` - dimensions
* `colors` - color list (cycles through bars)
* `orientation` - `'v'` or `'h'`

**Example:**

```python theme={null}
import liberator
import pandas as pd
from liberator import charting

dataset_name = 'reddit_wallstreetbets_comments'
df = liberator.get_dataframe(liberator.query(name=dataset_name))
df = df.loc[df['vader_body_sentiment_compound'] > 0]
df = df.sort_values(by=['vader_body_sentiment_compound'], ascending=[False])

charting.GroupedBarChart(
    df=df[0:5],
    groups="symbol",
    values=["vader_body_sentiment_pos", "vader_body_sentiment_compound", "textblob_body_sentiment_subjectivity"],
    title="WS Bets Sentiment",
    group_label="Symbol",
    value_label="sentiment score"
)
```

### ScatterPlot

Generates scatter plots with optional bubble sizing and color coding.

**Returns:** `plotly.graph_objs._figure.Figure`

**Required arguments:**

* `df` - pandas DataFrame
* `x_column` - numeric column for horizontal axis
* `y_column` - numeric column(s) for vertical axis

**Optional arguments:**

* `title`, `xlabel`, `ylabel` - labels with HTML support
* `width`, `height` - dimensions
* `size_column` - numeric column for bubble size (negative values show red/green)
* `size_multiplier` - multiplier to adjust bubble sizes

**Example:**

```python theme={null}
import liberator
import pandas as pd
from liberator import charting

dataset_name = 'reddit_wallstreetbets_comments'
df = liberator.get_dataframe(liberator.query(name=dataset_name))
df = df.loc[df['vader_body_sentiment_compound'] > 0]
df = df.sort_values(by=['vader_body_sentiment_compound'], ascending=[False])

fig = charting.ScatterPlot(
    df=df[0:200],
    x_column="textblob_body_sentiment_subjectivity",
    y_column=['vader_body_sentiment_neu'],
    title="WS Bets Sentiment",
    size_multiplier=.15,
    width=800,
    height=800
)
fig.show()
```

### addNotes

Adds annotations/callouts to existing charts for highlighting specific data points.

**Returns:** `plotly.graph_objs._figure.Figure`

**Arguments:**

* `thefig` - figure from a CloudQuant charting function
* `notes` - list of dictionaries with `x`, `y`, and `note` keys

**Example:**

```python theme={null}
import liberator
import pandas as pd
from liberator import charting
from datetime import datetime, timedelta

back_to = (datetime.now() + timedelta(days=-2)).strftime('%Y-%m-%d 23:59:59')
symbol = "AAPL"

res = liberator.query(name="minute_bars", symbols=symbol, back_to=back_to)
df_bars = liberator.get_dataframe(res)

fig = charting.Candlestick(df=df_bars, title=symbol)

mydata = []
data = {'x': df_bars.timestamp[7], 'y': df_bars.open[7], 'note': "T1"}
mydata.append(data)

data = {'x': df_bars.timestamp[155], 'y': df_bars.open[155], 'note': "T2"}
mydata.append(data)

data = {'x': df_bars.timestamp[1000], 'y': df_bars.open[1000], 'note': "T3"}
mydata.append(data)

fig = charting.addNotes(fig, mydata)
fig.show()
```
