Gemini 2 Flash Multimodal Live API Text and Audio
Gemini 2 Flash Multimodal Live API Text and Audio
January 2, 2025
os.environ['GOOGLE_API_KEY'] = userdata.get('GEMINI_API_KEY')
1 Import lib
[4]: import asyncio
import base64
import contextlib
import datetime
import os
import json
import wave
import itertools
1
2 Text to Text
“response_modalities”: [“TEXT”]
From docs api: only one cal ==> no loop.
Have a look on the following cell code to see how I implemented multiple calls
[ ]: config={"generation_config": {"response_modalities": ["TEXT"]}}
# For text responses, When the model's turn is complete it breaks out of the␣
loop.
↪
turn = session.receive()
async for chunk in turn:
if chunk.text is not None:
print(f'- {chunk.text}')
- Hi
- there! How can I help you today?
2
message = input("You: ")
nest_asyncio.apply()
await chat_with_model()
**Moment
Model: um Trading Strategy: Relative Strength Index (RSI) with Moving Average
Confirmation**
**Concept:**
This strategy looks for stocks exhibiting strong recent upward price momentum.
We
Model: 'll use the following indicators:
1. **Relative Strength Index (RSI):** The RSI measures the speed and change of
price movements. It's typically
Model: used to identify overbought (RSI above 70) or oversold (RSI below 30)
conditions. For momentum, we'll look for RSI crossing above 50 as an initial
sign of building strength.
2.
3
Model: **Simple Moving Average (SMA):** We'll use a short-term SMA (e.g.,
20-day) and a longer-term SMA (e.g., 50-day). We'll look
Model: for the short-term SMA crossing above the long-term SMA ("golden
cross"), which indicates a potential upward trend confirmation.
**Trading Rules:**
* **Buy Signal:**
* RSI crosses above 50
* Short-term SMA crosses above long-term SMA.
*
Model: A valid buy signal occurs only when both conditions are met.
* **Sell Signal:**
* RSI crosses below 50.
* A simple trailing stop is implemented using the minimum price over the
last 10 bars. This protects against large losses.
* **Position
Model: Sizing:** We'll use a fixed amount of capital per trade (e.g., 10% of
account equity), or a fixed position size (100 shares).
* **No shorting:** This example will be long-only.
* **Historical lookback:** This strategy
Model: is applied to daily stock data.
* **No intraday rebalancing:** Once the positions have been decided, they will
be maintained until a signal to exit.
**Python Implementation**
We'll use the `yfinance` library for stock data and `pandas` for data
manipulation. You might
Model: need to install them:
```bash
pip install yfinance pandas numpy ta
```
```python
import yfinance as yf
import pandas as pd
import numpy as np
import ta # for technical indicators
import matplotlib.pyplot as plt # for visualization
def
Model: fetch_data(ticker, start_date, end_date):
"""Fetches stock data using yfinance."""
try:
4
data = yf.download(ticker, start=start_date, end=end_date)
if data.empty:
print(f"No data
Model: found for ticker {ticker}")
return None
return data
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
return None
df["SMA_short"] = df["Close"].rolling(window=short_ma_period).mean()
df["SMA_long"] = df["Close"].rolling(window=long_ma_
Model: period).mean()
df["RSI"] = ta.momentum.rsi(df["Close"], window=rsi_period)
df["min_price_10"] = df['Low'].rolling(window=10).min()
return df
def generate_signals(df):
# Buy Signal
buy_condition = (
(df["RSI"].shift(1) < 50) & (df["R
Model: SI"] >= 50) &
(df["SMA_short"].shift(1) <= df["SMA_long"].shift(1)) &
(df["SMA_short"] > df["SMA_long"])
)
df.loc[buy_condition, "signal
Model: "] = 1.0
5
# If the signal is -1 then sell.
df.loc[0, 'position'] =
Model: 0
for i in range(1, len(df)):
if df['signal'][i] == 1:
df.loc[i, 'position'] = 1
elif df['signal'][i] == -1:
df.loc[i, 'position
Model: '] = 0
else:
df.loc[i, 'position'] = df['position'][i-1]
return df
Model: positions = 0
trade_log = []
6
#Add the portfolio amount for each day.
df.loc[index, 'portfolio'] = portfolio
def
Model: plot_strategy(df, ticker):
"""Plots the trading strategy and portfolio value."""
plt.figure(figsize=(14, 8))
7
plt.tight_layout()
plt.show()
def main():
"""Main execution."""
ticker = "AAPL"
start_date = "2020-01-
Model: 01"
end_date = "2024-01-01"
#Fetch data
df = fetch_data(ticker, start_date, end_date)
if df is None:
return
#Calculate indicators
df = calculate_indicators(
Model: df)
# Run backtest
df, trade_log = backtest(df)
print(f"Trade log:\n{trade_log}")
# Plot strategy
plot
Model: _strategy(df, ticker)
# Calculate performance metrics (e.g., total return, max drawdown, etc.) can
be added here.
# This requires extending the backtest method
if __name__ == "__main__":
main()
```
**How to Use:**
8
a plot of the price and signals, the RSI, and your portfolio value.
**Explanation:**
**Important Notes:**
**Further Enhancements:**
9
* **Trailing Stop:** Implement a trailing stop mechanism.
* **Multiple Assets:** Extend this to trading multiple assets.
* **Backtesting Improvements:** Add more sophisticated methods for
backtesting (e.g., walk-forward
Model: analysis).
* **Combine Indicators:** Experiment with combining other technical indicators
with this strategy.
This provides a good starting point for you to explore momentum trading.
Remember, real-world trading requires a lot of research, testing, and a strong
understanding of market dynamics. Good luck!
Here's the modified `main()` function within the code to plot Nvidia data:
```python
import
Model: yfinance as yf
import pandas as pd
import numpy as np
import ta # for technical indicators
import matplotlib.pyplot as plt # for
Model: visualization
10
df["SMA_short"] = df["
Model: Close"].rolling(window=short_ma_period).mean()
df["SMA_long"] = df["Close"].rolling(window=long_ma_period).mean()
df["RSI"] = ta.momentum.rsi(df["Close"], window=rsi_period)
def generate_signals(df):
"""Generates buy and sell signals."""
df["signal"] = 0.0
df["position"] =
Model: 0.0
# Buy Signal
buy_condition = (
(df["RSI"].shift(1) < 50) & (df["RSI"] >= 50) &
(df["SMA_short"].shift(1) <= df["SMA_long"].shift(
Model: 1)) &
(df["SMA_short"] > df["SMA_long"])
)
df.loc[buy_condition, "signal"] = 1.0
return df
11
Model: def backtest(df, initial_capital=10000, risk_pct = 0.1):
"""Performs backtesting.
df: DataFrame with 'signal' and 'Close' columns
initial_capital: the inital amount of equity to start trading with.
risk_
Model: pct: the percentage of capital at risk per trade.
"""
portfolio = initial_capital
cash = initial_capital
positions = 0
trade_log = []
#Add the
Model: portfolio amount for each day.
df.loc[index, 'portfolio'] = portfolio
# Plotting
12
Model: the stock price
plt.subplot(3, 1, 1)
plt.plot(df.index, df["Close"], label="Price", color='blue')
plt.plot(df.index, df["SMA_short"], label="SMA Short", color='orange',
Model: linestyle='--')
plt.plot(df.index, df["SMA_long"], label="SMA Long", color='red',
linestyle='--')
plt.tight_layout()
plt.show()
Model:
def main():
"""Main execution."""
ticker = "NVDA" # Changed to Nvidia
start_date = "2020-01-01"
end_date = "2024-01-01"
#Fetch data
df
Model: = fetch_data(ticker, start_date, end_date)
13
if df is None:
return
#Calculate indicators
df = calculate_indicators(df)
# Run
Model: backtest
df, trade_log = backtest(df)
print(f"Trade log:\n{trade_log}")
# Plot strategy
plot_strategy(df, ticker)
if __name__ == "__main__":
main()
```
**Key Changes:**
14
Here's the complete code that you can copy and paste directly into a
Model: file named `momentum_nvidia.py`:
```python
import yfinance as yf
import pandas as pd
import numpy as np
import ta #
Model: for technical indicators
import matplotlib.pyplot as plt # for visualization
df["SMA_short"] = df["Close"].rolling(window=short_ma_period).mean()
df["
Model: SMA_long"] = df["Close"].rolling(window=long_ma_period).mean()
df["RSI"] = ta.momentum.rsi(df["Close"], window=rsi_period)
df["min_price_10"] = df['Low'].rolling(window
Model: =10).min()
return df
def generate_signals(df):
"""Generates buy and sell signals."""
df["signal"] = 0.0
df["position"] = 0.0
# Buy Signal
buy_condition = (
15
Model: (df["RSI"].shift(1) < 50) & (df["RSI"] >= 50) &
(df["SMA_short"].shift(1) <= df["SMA_long"].shift(1)) &
(df["SMA_short"] > df["
Model: SMA_long"])
)
df.loc[buy_condition, "signal"] = 1.0
return df
Model: """
portfolio = initial_capital
cash = initial_capital
positions = 0
trade_log = []
16
position_size = (cash * risk_pct) / row['Close']
positions = position_size
cash -= positions*row['Close']
trade_log.append({'date':index, 'action': 'buy', 'price':
row['Close'], 'qty':
Model: positions})
# print(f"Buy signal at {row['Close']}. Holding shares:
{positions}")
# Close position
elif row['signal'] == -1 and positions > 0:
cash += positions * row['Close']
positions = 0
Model: plt.subplot(3, 1, 1)
plt.plot(df.index, df["Close"], label="Price", color='blue')
plt.plot(df.index, df["SMA_short"], label="SMA Short", color='orange',
linestyle='--')
17
Model: 100)
plt.title(f"{ticker} Price, SMA and Trading Signals")
plt.legend()
plt.tight_layout()
plt.show()
def main():
"""Main execution."""
#Fetch data
df = fetch_data(ticker, start
Model: _date, end_date)
if df is None:
return
#Calculate indicators
df = calculate_indicators(df)
# Run backtest
df, trade_log
Model: = backtest(df)
print(f"Trade log:\n{trade_log}")
# Plot strategy
18
plot_strategy(df, ticker)
# Calculate performance metrics (e.g., total return, max drawdown, etc.) can
be added here.
#
Model: This requires extending the backtest method
if __name__ == "__main__":
main()
```
**How to Use:**
This will execute the code, and the plots using Nvidia stock data will be
displayed.
**Method 1
Model: : Using `%%writefile` Magic Command (Easiest)**
1. **Create a New Code Cell:** In your Colab notebook, add a new code
Model: cell.
2. **Paste the Code:** Paste the entire Python code into this new code cell.
3. **Add `%%writefile momentum_nvidia.py`:** In the first line of this code
cell (
Model: above the `import` statements), add the line:
```python
%%writefile momentum_nvidia.py
```
```python
%%writefile momentum_
19
Model: nvidia.py
import yfinance as yf
import pandas as pd
import numpy as np
import ta
import matplotlib.pyplot as plt
if __name__ == "__main__":
main()
```
4. **Run the Cell:** Execute this code cell by clicking the play button (or
pressing Shift + Enter). This will create a file named `momentum_nvidia.py`
Model: in the current working directory of your Colab environment.
You can also create the file programmatically using Python's file handling:
```python
if __name__ == '__main__':
20
Model: data = yf.download(ticker, start=start_date, end=end_date)
if data.empty:
print(f"No data found for ticker {ticker}")
return None
return data
except Exception as e:
print(f"
Model: Error fetching data for {ticker}: {e}")
return None
df["SMA
Model: _short"] = df["Close"].rolling(window=short_ma_period).mean()
df["SMA_long"] = df["Close"].rolling(window=long_ma_period).mean()
df["RSI"] = ta.momentum.rsi(df["Close"], window
Model: =rsi_period)
df["min_price_10"] = df['Low'].rolling(window=10).min()
return df
def generate_signals(df):
\"\"\"Generates buy and sell signals.\"\"\"
df["signal"] = 0
Model: .0
df["position"] = 0.0
# Buy Signal
buy_condition = (
(df["RSI"].shift(1) < 50) & (df["RSI"] >= 50) &
(df["SMA_short"].shift
Model: (1) <= df["SMA_long"].shift(1)) &
(df["SMA_short"] > df["SMA_long"])
)
df.loc[buy_condition, "signal"] = 1.0
21
Model: signal, it will return 1.
# Otherwise it will maintain the position if we are already holding.
# If the signal is -1 then sell.
df.loc[0, 'position'] = 0
for i in range(1, len(df)):
if df
Model: ['signal'][i] == 1:
df.loc[i, 'position'] = 1
elif df['signal'][i] == -1:
df.loc[i, 'position'] = 0
else:
df.loc[i, 'position'] = df
Model: ['position'][i-1]
return df
for index,
Model: row in df.iterrows():
# Open position
if row['signal'] == 1:
if positions == 0:
position_size = (cash * risk_pct) / row['Close']
positions = position_size
cash -= positions*row['Close
Model: ']
trade_log.append({'date':index, 'action': 'buy', 'price':
row['Close'], 'qty': positions})
# print(f"Buy signal at {row['Close']}. Holding shares:
{positions}")
# Close position
elif row['signal
Model: '] == -1 and positions > 0:
cash += positions * row['Close']
positions = 0
trade_log.append({'date':index, 'action': 'sell', 'price':
row['Close']})
22
# print(f"Sell signal at {row
Model: ['Close']}")
# Plot
Model: ting the RSI
plt.subplot(3, 1, 2)
plt.plot(df.index, df["RSI"], label="RSI", color='purple')
plt.axhline(50, color='grey', linestyle='--', label='RSI 5
Model: 0')
plt.title("RSI")
plt.legend()
23
plt.subplot(3, 1, 3)
plt.plot(df.index, df["portfolio"], label='Portfolio Value', color='black')
plt.title
Model: ("Portfolio Value")
plt.legend()
plt.tight_layout()
plt.show()
def main():
\"\"\"Main execution.\"\"\"
ticker = \"NVDA\" # Changed to Nvidia
start_date = \"2020-01-
Model: 01\"
end_date = \"2024-01-01\"
#Fetch data
df = fetch_data(ticker, start_date, end_date)
if df is None:
return
#Calculate indicators
df = calculate_
Model: indicators(df)
# Run backtest
df, trade_log = backtest(df)
print(f"Trade log:\\n{trade_log}")
# Plot strategy
# Calculate performance metrics (e.g., total return, max drawdown, etc.) can
be added here.
# This requires extending the backtest method
""")
Model: ```
4. **Run the Cell:** Execute this code cell. It will now create a
24
`momentum_nvidia.py` file, and run the script as usual.
**Choosing a Method:**
Choose either method, run the code cell, and you will
Model: have your python file created locally in your Google Colab environment.
You: exit
Ending the chat session. Goodbye!
turn = session.receive()
async for n,response in async_enumerate(turn):
25
if response.data is not None:
wav.writeframes(response.data)
if n==0:
print(response.server_content.model_turn.parts[0].inline_data.
↪mime_type)
print('.', end='')
display(Audio(file_name, autoplay=True))
audio/pcm;rate=24000
…
<IPython.lib.display.Audio object>
nest_asyncio.apply()
[8]: @contextlib.contextmanager
def wave_file(filename, channels=1, rate=24000, sample_width=2):
with wave.open(filename, "wb") as wf:
wf.setnchannels(channels)
wf.setsampwidth(sample_width)
wf.setframerate(rate)
yield wf
26
# Check if the user wants to exit
if message.lower() == "exit":
print("Ending the chat session. Goodbye!")
break
file_name = 'audio.wav'
with wave_file(file_name) as wav:
if n==0:
print(response.server_content.model_turn.parts[0].
↪inline_data.mime_type)
print('.', end='')
await chat_with_model()
# audio/pcm;rate=24000
# ..............................................................................
↪.............................................................................
# You: Can you create a 4-week plan for me to dive into algorithmic trading,␣
↪considering I’m a beginner?
# audio/pcm;rate=24000
# ..............................................................................
↪...............................................................Model: (Audio␣
↪response)
27
# You: Can you provide more detailed activities and resources for Week 1 of my␣
↪4-week plan to dive into algorithmic trading?
# audio/pcm;rate=24000
# ..............................................................................
↪..........................................................................
# You: exit
# Ending the chat session. Goodbye!
28